@zibby/agent-workflow 2.0.4 → 2.0.5

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.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Fetch deadlines — the ONE declaration, so the engine's HTTP doors cannot
3
+ * drift apart.
4
+ * ============================================================================
5
+ *
6
+ * WHY THIS FILE EXISTS AT ALL. Node's global fetch has NO default timeout, and
7
+ * A HANG IS NOT A THROW: a connection that is accepted and then never answered
8
+ * is not an error any `catch` can see, it is a process that stops. Every HTTP
9
+ * door in this engine is already written for failure — a trigger rejection is
10
+ * booked per-child by the caller's `Promise.allSettled`, a poll transport throw
11
+ * is retried, a `begin` failure falls back to the HTTP path — and NONE of that
12
+ * code can run for the one failure mode that actually costs a run.
13
+ *
14
+ * MEASURED, not hypothetical: board-runner run 4b49371e (2026-08-24) sat 7m33s
15
+ * inside the identical unbounded shape until the container watchdog killed it,
16
+ * and a tick that had already done all of its work recorded nothing. The same
17
+ * class has been closed in workflow-templates' lib/kb.js (d7e3184),
18
+ * lib/platform-api.js (7a355cc), _shared/tracker.js (539483e) and
19
+ * @zibby/core's backend-client.js.
20
+ *
21
+ * WHY THE HELPERS LIVE HERE AND NOT NEXT TO THEIR CALL SITES. The engine has
22
+ * two files that dispatch a child — `sub-graph-executor.ts` (HTTP) and
23
+ * `in-process-subgraph.ts` (in-process, which FALLS BACK to the other) — and
24
+ * they are two halves of one dispatch. Copying a clamp, a `TimeoutError` check
25
+ * and a budget into both is precisely the TWO-PLACES shape that produced every
26
+ * incident this rule was written for: a pair that must agree with nothing to
27
+ * scream when it drifts. One declaration, N consumers, no tripwire needed
28
+ * because there is nothing to keep in sync.
29
+ *
30
+ * ⚠️ Deliberately DEPENDENCY-FREE (not even the logger) so any module can
31
+ * import it without a cycle — `in-process-subgraph.ts` is imported BY
32
+ * `sub-graph-executor.ts`, so the budgets could not have lived in the latter.
33
+ */
34
+ export declare const SUBGRAPH_TRIGGER_TIMEOUT_MS = 30000;
35
+ export declare const SUBGRAPH_POLL_TIMEOUT_MS = 15000;
36
+ export declare const SUBGRAPH_BUNDLE_TIMEOUT_MS = 60000;
37
+ /** curl's connect phase only — a stalled DNS/TCP handshake, distinct from a
38
+ * slow but progressing transfer. Not separately overridable: it is a fixed
39
+ * fraction of the class, and one more knob would be one more thing to drift. */
40
+ export declare const SUBGRAPH_CONNECT_TIMEOUT_MS = 10000;
41
+ export declare const TIMEOUT_FLOOR_MS = 1000;
42
+ export declare const TIMEOUT_CEILING_MS = 120000;
43
+ /**
44
+ * Read a budget from the environment, or fall back. Clamped to
45
+ * [TIMEOUT_FLOOR_MS, TIMEOUT_CEILING_MS]; anything unparseable or non-positive
46
+ * (`0`, `-1`, `''`, `'soon'`) falls back rather than disabling the bound.
47
+ */
48
+ export declare function timeoutMsFrom(knob: string, fallback: number, env?: any): number;
49
+ /**
50
+ * ONE deadline for ONE call: the `signal` the request AND its body reads share
51
+ * — a response whose headers arrive and whose body then stalls is the same
52
+ * hang, and bounding only the first half leaves the door open — plus the
53
+ * `label` a timeout reports itself with.
54
+ *
55
+ * The label names the budget AND its knob because whoever reads the run log has
56
+ * to tell a SLOW control plane (raise the knob, or accept the failure) from a
57
+ * BROKEN one (an ordinary transport error, which keeps its existing wording).
58
+ * One spelling for both is how a hang stays invisible for as long as this one
59
+ * did.
60
+ */
61
+ export declare function makeDeadline(ms: number, knob: string): {
62
+ signal: AbortSignal;
63
+ label: string;
64
+ };
65
+ /** Build a deadline straight from a knob + default. */
66
+ export declare function deadlineFor(knob: string, fallback: number): {
67
+ signal: AbortSignal;
68
+ label: string;
69
+ };
70
+ /**
71
+ * `AbortSignal.timeout` aborts with a `TimeoutError` DOMException (undici
72
+ * rejects the fetch — and any in-flight body read — with that same reason); a
73
+ * caller-cancelled signal aborts with `AbortError`. Both mean "we stopped
74
+ * waiting"; NEITHER means "the far end said no", which is why every call site
75
+ * branches on this before deciding whether to reword an error or rethrow it
76
+ * unchanged.
77
+ */
78
+ export declare function isTimeoutError(err: any): boolean;
@@ -0,0 +1 @@
1
+ var i=3e4,M=15e3,T=6e4,u=1e4,s=1e3,E=12e4;function o(t,r,e=process.env){let n=Number(e[t]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):r}function _(t,r){return{signal:AbortSignal.timeout(t),label:`after ${t}ms (${r})`}}function a(t,r){return _(o(t,r),t)}function m(t){return t?.name==="TimeoutError"||t?.name==="AbortError"}export{T as SUBGRAPH_BUNDLE_TIMEOUT_MS,u as SUBGRAPH_CONNECT_TIMEOUT_MS,M as SUBGRAPH_POLL_TIMEOUT_MS,i as SUBGRAPH_TRIGGER_TIMEOUT_MS,E as TIMEOUT_CEILING_MS,s as TIMEOUT_FLOOR_MS,a as deadlineFor,m as isTimeoutError,_ as makeDeadline,o as timeoutMsFrom};
@@ -1,50 +1,50 @@
1
- var qt=Object.defineProperty;var $e=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var le=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var Ke=(n,e)=>{for(var t in e)qt(n,t,{get:e[t],enumerable:!0})};var Ve,Vt,Te,pe,E,W=le(()=>{Ve=()=>{},Vt={debug:Ve,info:Ve,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Te=Symbol.for("@zibby/agent-workflow.logger");globalThis[Te]||(globalThis[Te]={impl:Vt});pe=globalThis[Te],E={debug:(...n)=>pe.impl.debug?.(...n),info:(...n)=>pe.impl.info?.(...n),warn:(...n)=>pe.impl.warn?.(...n),error:(...n)=>pe.impl.error?.(...n)}});var ct=le(()=>{});var lt={};Ke(lt,{clearSkills:()=>sn,getAllSkills:()=>on,getSkill:()=>oe,getSkillSource:()=>nn,hasSkill:()=>tn,listSkillIds:()=>rn,registerSkill:()=>en});function en(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(G.has(r)&&!o){let s=ne.get(r);if(!(s===t)){let a=s||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" 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).`)}}G.set(r,Object.freeze({...n})),t===void 0?ne.delete(r):ne.set(r,t)}function oe(n){return G.get(n)||null}function tn(n){return G.has(n)}function nn(n){return ne.get(n)||null}function on(){return new Map(G)}function rn(){return Array.from(G.keys())}function sn(){G.clear(),ne.clear()}var Oe,Pe,G,ne,he=le(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Pe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Pe]||(globalThis[Pe]=new Map);G=globalThis[Oe],ne=globalThis[Pe]});var re={};Ke(re,{getAgentStrategy:()=>pt,invokeAgent:()=>ln,listStrategies:()=>cn,registerStrategy:()=>an,resolveInvocationExtras:()=>dt,resolveInvocationModel:()=>ut});function an(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===n.getName());e>=0?H[e]=n:H.push(n)}function cn(){return H.map(n=>n.getName())}function ut({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let s=n.models||{},i=typeof r=="string"&&r.trim()?r.trim():null,a=e.nodeName&&s[e.nodeName]||null,u=s.default||null,d=n.agent?.[t]?.model||null,m=(typeof o=="string"?o.trim():"")||null;return i||a||u||d||e.model||m||null}function dt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function pt(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${o}`);let r=H.find(s=>s.getName()===o);if(!r){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${s}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${r.getName()}`),r}async function ln(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},s=pt(r),i=o.config||t.config||{},a=o._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===s.name?a.model:null,m=ut({config:i,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:m,...dt({options:t,stateView:o,context:e}),config:i},c=n,p=l.skills||[];if(p.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let g=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof g=="string"&&g.trim()!==""){A={};for(let y of g.split(",").map(w=>w.trim()).filter(Boolean))A[y]=!0}}let T=g=>{let y=g&&g.requiresIntegration;return!y||!A?!0:(Array.isArray(y)?y:[y]).some($=>A[$]===!0)},f=s.name==="assistant",_=g=>g?.inProcessOnly!==!0||f,b=p.map(g=>{let y=oe(g);if(!T(y)||!_(y))return null;let w=y?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);b.length>0&&(c+=`
1
+ var en=Object.defineProperty;var xe=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var he=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var nt=(n,e)=>{for(var t in e)en(n,t,{get:e[t],enumerable:!0})};var ot,nn,Pe,ye,I,z=he(()=>{ot=()=>{},nn={debug:ot,info:ot,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Pe=Symbol.for("@zibby/agent-workflow.logger");globalThis[Pe]||(globalThis[Pe]={impl:nn});ye=globalThis[Pe],I={debug:(...n)=>ye.impl.debug?.(...n),info:(...n)=>ye.impl.info?.(...n),warn:(...n)=>ye.impl.warn?.(...n),error:(...n)=>ye.impl.error?.(...n)}});var ht=he(()=>{});var gt={};nt(gt,{clearSkills:()=>dn,getAllSkills:()=>ln,getSkill:()=>ie,getSkillSource:()=>cn,hasSkill:()=>an,listSkillIds:()=>un,registerSkill:()=>sn});function sn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,r=n.id;if(Y.has(r)&&!o){let i=se.get(r);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}Y.set(r,Object.freeze({...n})),t===void 0?se.delete(r):se.set(r,t)}function ie(n){return Y.get(n)||null}function an(n){return Y.has(n)}function cn(n){return se.get(n)||null}function ln(){return new Map(Y)}function un(){return Array.from(Y.keys())}function dn(){Y.clear(),se.clear()}var Ce,Be,Y,se,we=he(()=>{Ce=Symbol.for("@zibby/agent-workflow.skills"),Be=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ce]||(globalThis[Ce]=new Map);globalThis[Be]||(globalThis[Be]=new Map);Y=globalThis[Ce],se=globalThis[Be]});var ae={};nt(ae,{getAgentStrategy:()=>St,invokeAgent:()=>hn,listStrategies:()=>fn,registerStrategy:()=>pn,resolveInvocationExtras:()=>yt,resolveInvocationModel:()=>mt});function pn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=Z.findIndex(t=>t.getName()===n.getName());e>=0?Z[e]=n:Z.push(n)}function fn(){return Z.map(n=>n.getName())}function mt({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let i=n.models||{},s=typeof r=="string"&&r.trim()?r.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,d=n.agent?.[t]?.model||null,S=(typeof o=="string"?o.trim():"")||null;return s||a||l||d||e.model||S||null}function yt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function St(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${o}`);let r=Z.find(i=>i.getName()===o);if(!r){let i=Z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${r.getName()}`),r}async function hn(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},i=St(r),s=o.config||t.config||{},a=o._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",d=!l||l===i.name?a.model:null,S=mt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),u={...t,model:S,...yt({options:t,stateView:o,context:e}),config:s},c=n,g=u.skills||[];if(g.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){A={};for(let w of f.split(",").map(m=>m.trim()).filter(Boolean))A[w]=!0}}let $=f=>{let w=f&&f.requiresIntegration;return!w||!A?!0:(Array.isArray(w)?w:[w]).some(y=>A[y]===!0)},h=i.name==="assistant",b=f=>f?.inProcessOnly!==!0||h,v=g.map(f=>{let w=ie(f);if(!$(w)||!b(w))return null;let m=w?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);v.length>0&&(c+=`
2
2
 
3
- ${b.join(`
3
+ ${v.join(`
4
4
 
5
- `)}`)}let h=o._currentNodeConfig?.stores;if(Array.isArray(h)&&h.length>0&&typeof h[0]=="object"){let A=h.length<=8,T=h.map(f=>{let _=f?.id??f?.storeId??"",b=(f?.name??"").toString().trim()||_,g=f?.type?` \xB7 ${f.type}`:"",y=(f?.description||"").toString().replace(/\s+/g," ").trim(),w=`- ${b} \xB7 ${y||"(no description)"}${g} (id: ${_})`;if(A&&f?.schema&&typeof f.schema=="object"){let $=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);$.length&&(w+=`
6
- fields: ${$.join(", ")}`)}return w});c+=`
5
+ `)}`)}let p=o._currentNodeConfig?.stores;if(Array.isArray(p)&&p.length>0&&typeof p[0]=="object"){let A=p.length<=8,$=p.map(h=>{let b=h?.id??h?.storeId??"",v=(h?.name??"").toString().trim()||b,f=h?.type?` \xB7 ${h.type}`:"",w=(h?.description||"").toString().replace(/\s+/g," ").trim(),m=`- ${v} \xB7 ${w||"(no description)"}${f} (id: ${b})`;if(A&&h?.schema&&typeof h.schema=="object"){let y=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);y.length&&(m+=`
6
+ fields: ${y.join(", ")}`)}return m});c+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${T.join(`
10
- `)}`}let v=o._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(c+=`
9
+ ${$.join(`
10
+ `)}`}let T=o._currentNodeConfig?.extraPromptInstructions?.trim();return T&&(c+=`
11
11
 
12
12
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
13
13
  PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
- ${v}
17
- `),E.debug(`[workflow] prompt length: ${c.length} chars`),s.invoke(c,l)}var Ne,H,se=le(()=>{ct();W();he();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);H=globalThis[Ne]});var Kt=new Set(["__proto__","constructor","prototype"]);function ve(n){if(Kt.has(n))throw new Error(`Invalid state key: "${n}"`)}var ue=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){ve(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)ve(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){ve(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 J from"handlebars";var de=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 o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let s=typeof e[o];s!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${s}`)}if(r.validate&&o in e){let s=r.validate(e[o]);s&&t.push(`Field '${o}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
16
+ ${T}
17
+ `),I.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,u)}var Ue,Z,ce=he(()=>{ht();z();we();Ue=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ue]||(globalThis[Ue]=[]);Z=globalThis[Ue]});var tn=new Set(["__proto__","constructor","prototype"]);function ke(n){if(tn.has(n))throw new Error(`Invalid state key: "${n}"`)}var ge=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){ke(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)ke(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){ke(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 q from"handlebars";var me=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 o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let i=typeof e[o];i!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${i}`)}if(r.validate&&o in e){let i=r.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};W();import{writeFileSync as Ce,readFileSync as ft,existsSync as ht,mkdirSync as un}from"node:fs";import{join as Re,dirname as dn}from"node:path";import O from"chalk";var Xt="__WORKFLOW_GRAPH_LOG__",te=O.gray("\u2502"),Qt=O.gray("\u250C"),Xe=O.gray("\u2514"),Ae=O.green("\u25C6"),Qe=O.hex("#c084fc")("\u25C6"),et=O.hex("#2dd4bf")("\u25C6"),ke=O.red("\u25C6"),tt=`${te} `,nt=2;function ot(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function rt(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let s=process.stdout.columns||120,i="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(i+=tt,e.col=nt,e.lineStart=!1),u===`
20
- `?(i+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,i+=u):e.inEsc?(i+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,i+=u,e.col>=s&&(i+=`
21
- ${tt}`,e.col=nt))}return n(i,o,r)}}var xe=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=rt(this._origStdoutWrite,e),process.stderr.write=rt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};z();import{writeFileSync as De,readFileSync as wt,existsSync as _t,mkdirSync as gn}from"node:fs";import{join as je,dirname as mn}from"node:path";import P from"chalk";var on="__WORKFLOW_GRAPH_LOG__",re=P.gray("\u2502"),rn=P.gray("\u250C"),rt=P.gray("\u2514"),Ne=P.green("\u25C6"),st=P.hex("#c084fc")("\u25C6"),it=P.hex("#2dd4bf")("\u25C6"),Me=P.red("\u25C6"),at=`${re} `,ct=2;function lt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ut(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=at,e.col=ct,e.lineStart=!1),l===`
20
+ `?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
21
+ ${at}`,e.col=ct))}return n(s,o,r)}}var Re=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=ut(this._origStdoutWrite,e),process.stderr.write=ut(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=`${Xt}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${on}${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(Ae,e):process.stdout.write.bind(process.stdout)(`${te} ${Ae} ${e}
29
- `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Qe,e):process.stdout.write.bind(process.stdout)(`${te} ${Qe} ${e}
30
- `)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(et,t):process.stdout.write.bind(process.stdout)(`${te} ${et} ${t}
31
- `)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,O.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${ke} ${O.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Qt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let i of r)this._rawWrite(`${Ae} ${i}`);let s=o?O.dim(` ${ot(o)}`):"";this._rawWrite(`${Xe} ${O.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,s=r?O.dim(` ${ot(r)}`):"";this._rawWrite(`${ke} ${O.red(t)}`),this._rawWrite(`${Xe} ${O.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new xe;var fe=".zibby/output",st="sessions",K=".session-info.json",it=".zibby-stop";var oo=Object.freeze(["codebase-memory","code-scan","artifact"]),at=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",n=>Number(n)+1);J.helpers.json||J.registerHelper("json",n=>JSON.stringify(n,null,2));J.helpers.eq||J.registerHelper("eq",(n,e)=>n===e);var U=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 de(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let l=null;for(let c=0;c<=this.retries;c++){try{let p=await this.customExecute(e);if(typeof p=="object"&&p!==null&&p.success===!1)l={success:!1,error:p.error||"Node execution failed",raw:p.raw||null};else return this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){E.error(`[workflow] node '${this.name}' failed: ${p.message}`),p.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(p.issues||p.errors,null,2)}`),l={success:!1,error:p.message,raw:null}}c<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return l}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let i=r("_skillHints");i&&(s=`${i}
28
+ `)}step(e){this._origStdoutWrite?this._writeDot(Ne,e):process.stdout.write.bind(process.stdout)(`${re} ${Ne} ${e}
29
+ `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(st,e):process.stdout.write.bind(process.stdout)(`${re} ${st} ${e}
30
+ `)}stepMemory(e){let t=P.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(it,t):process.stdout.write.bind(process.stdout)(`${re} ${it} ${t}
31
+ `)}stepFail(e){this._origStdoutWrite?this._writeDot(Me,P.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Me} ${P.red(e)}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${rn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let s of r)this._rawWrite(`${Ne} ${s}`);let i=o?P.dim(` ${lt(o)}`):"";this._rawWrite(`${rt} ${P.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,i=r?P.dim(` ${lt(r)}`):"";this._rawWrite(`${Me} ${P.red(t)}`),this._rawWrite(`${rt} ${P.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(P.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},M=new Re;var Se=".zibby/output",dt="sessions",ee=".session-info.json",pt=".zibby-stop";var ho=Object.freeze(["codebase-memory","code-scan","artifact"]),ft=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];q.helpers.inc||q.registerHelper("inc",n=>Number(n)+1);q.helpers.json||q.registerHelper("json",n=>JSON.stringify(n,null,2));q.helpers.eq||q.registerHelper("eq",(n,e)=>n===e);var W=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 me(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let u=null;for(let c=0;c<=this.retries;c++){try{let g=await this.customExecute(e);if(typeof g=="object"&&g!==null&&g.success===!1)u={success:!1,error:g.error||"Node execution failed",raw:g.raw||null};else return this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(g),raw:null}):{success:!0,output:g,raw:null}}catch(g){I.error(`[workflow] node '${this.name}' failed: ${g.message}`),g.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(g.issues||g.errors,null,2)}`),u={success:!1,error:g.message,raw:null}}c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return u}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=q.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let s=r("_skillHints");s&&(i=`${s}
33
33
 
34
- ${s}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(ht(l)){let p=JSON.parse(ft(l,"utf-8"));p.currentNode=this.name,Ce(l,JSON.stringify(p,null,2),"utf-8")}let c=Re(d,"..",K);if(ht(c))try{let p=JSON.parse(ft(c,"utf-8"));p.currentNode=this.name,Ce(c,JSON.stringify(p,null,2),"utf-8")}catch{}}}catch(l){E.debug(`[workflow] could not update session info: ${l.message}`)}let m=null;for(let l=0;l<=this.retries;l++)try{E.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},p=c.agents||{},h=this.config.agent??p[this.name]??null,v={state:o()};h&&(v.preferredAgent=h);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},T=e?._coreInvokeAgent;T||(T=(await Promise.resolve().then(()=>(se(),re))).invokeAgent);let f=await T(s,v,A),_,b;if(typeof f=="string"?(_=f,b=null):f.structured?(_=f.raw||JSON.stringify(f.structured,null,2),b=f.structured):(_=f.raw||JSON.stringify(f,null,2),b=f.extracted||null),d)try{let g=Re(d,this.name,"raw_stream_output.txt");un(dn(g),{recursive:!0}),Ce(g,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(g){E.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&b){E.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(b,null,2)}`);let g=b;if(typeof this.onComplete=="function")try{g=await this.onComplete(o(),b)}catch(y){E.warn(`[workflow] onComplete hook failed: ${y.message}`)}return{success:!0,output:g,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:_}),raw:_}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(_);return E.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),P.step("Output parsed"),{success:!0,output:g,raw:_}}return{success:!0,output:_,raw:_}}catch(c){m=c,l<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};W();W();import{mkdirSync as hn,existsSync as Y,statSync as $t,readdirSync as vt,rmSync as gn}from"node:fs";import{spawn as bt}from"node:child_process";import{join as F}from"node:path";import{pathToFileURL as mn}from"node:url";import{AsyncLocalStorage as yn}from"node:async_hooks";import{AsyncLocalStorage as pn}from"node:async_hooks";var ie=new pn;function V(){let n=ie.getStore();return n||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,agent:null,signal:null})}function gt(n,e){let t=ie.getStore()||V(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ie.run(o,e)}function mt(n,e,t){let o=ie.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ie.run(r,t)}var Me=new Map,Be=new Map,yt=new Map;function wt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Me.set(n,e),Be.set(n,"ready"),yt.set(n,{...t,cachedAt:Date.now()})}function St(n,e){Be.set(n,"failed"),yt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Me.delete(n)}function _t(n){return Be.get(n)==="ready"?Me.get(n):null}var ge=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function wn(){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"}};function me(n,e,t,o="timeout",r=null){let s=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(r?`; the status API was unreachable on the last attempt (${r})`:""));return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=e,s.subgraphStatus=o,r&&(s.subgraphTransportError=r),s}function Sn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,r=Number(e&&e.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(t)&&t>0?t*1e3:0,i=Number.isFinite(r)&&r>0?r-s:null;if(o===null&&i===null)return null;let a=o===null?i:i===null?o:Math.min(o,i);return Math.max(1,a)}function _n(n,e){let t=new AbortController,o=!1,r=null,s=()=>{t.abort(n?.reason)};return n&&(n.aborted?s():n.addEventListener("abort",s,{once:!0})),e!=null&&!t.signal.aborted&&(r=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof r.unref=="function"&&r.unref()),{signal:t.signal,timedOut:()=>o,dispose(){r&&(clearTimeout(r),r=null),n&&n.removeEventListener("abort",s)}}}var It=new yn,Et=Promise.resolve();async function bn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([i,a])=>typeof i=="string"&&i&&typeof a=="string"):[];if(t.length===0)return e();let o=It.getStore()===!0,r=null;if(!o){let i=Et;Et=new Promise(a=>{r=a}),await i}let s=new Map;try{for(let[i,a]of t)s.set(i,Object.prototype.hasOwnProperty.call(process.env,i)?process.env[i]:void 0),process.env[i]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await It.run(!0,e)}finally{for(let[i,a]of s)a===void 0?delete process.env[i]:process.env[i]=a;r&&r()}}function In(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function En({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/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 r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.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(o.status===429){let s=r?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=s,i}if(o.status===400&&r?.validationErrors){let s=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=r.validationErrors,s.missing=r.missing,s}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||E.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){E.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function $n(n,e){let t=F(e,".ready"),o=F(e,"graph.mjs");if(Y(t)&&Y(o))return;hn(e,{recursive:!0});let r=F(e,".lock"),s=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),u=i(r,"wx");a(u),s=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!s){let i=Date.now()+3e4;for(;Date.now()<i;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let m=bt("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=bt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(l.stdin);let c,p,h=()=>{if(c!==void 0&&p!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(p!==0)return d(new Error(`tar exited ${p}`));u()}};m.on("close",v=>{c=v,h()}),l.on("close",v=>{p=v,h()}),m.on("error",d),l.on("error",d)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(t,"");try{a(r)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",i.message)}}async function vn(n){let e=F(n,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(mn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function Tt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=In()}catch(w){throw w}E.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await En({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:m,bundleReady:l,nodeConfigs:c}=r,p=wn();if(i&&i!==p)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("runtime-mismatch",`${p} vs ${i}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let h=_t(n);if(!h){let w=F(ge,`${m}@${d||"0"}`);try{await $n(a,w);try{An()}catch{}}catch($){throw $.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await vn(w),wt(n,h,{workflowUuid:m,version:d,runtimeTag:i,cacheDir:w})}catch($){throw St(n,$),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new N("import-failed",$.message)}}let v=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,T=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...T?{nodeConfigs:c}:{}},_=Sn(e.timeoutMs),b=_n(e.signal,_),g,y;try{g=await bn(A,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return gt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,f,{signal:b.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(w){let $=b.timedOut();throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:$?"timeout":"failed",error:$?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:w.message,code:w.code||"CHILD_THREW",stack:w.stack},durationMs:Date.now()-v}}),$?me(n,s,_):w}finally{b.dispose()}if(g&&typeof g=="object"&&g.stoppedExternally){let w=b.timedOut();if(await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:w?"timeout":"canceled",finalState:y,durationMs:Date.now()-v}}),w)throw me(n,s,_);let $=new Error(`Sub-graph '${n}' canceled by parent abort`);throw $.code="SUBGRAPH_CANCELED",$.subgraphJobId=s,$}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:s}}function Tn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=$t(o)}catch{continue}if(r.isDirectory()){let s;try{s=vt(o)}catch{continue}for(let i of s)t.push(F(o,i))}else e+=r.size}return e}function An({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ge))return{evicted:0,freedBytes:0};let e=vt(ge),t=[],o=0;for(let a of e){let u=F(ge,a),d;try{d=$t(u)}catch{continue}let m=d.isDirectory()?Tn(u):d.size;o+=m,t.push({name:a,full:u,size:m,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),s=0,i=0;for(let a of t){if(o-s<=r)break;if(!Y(F(a.full,".lock")))try{gn(a.full,{recursive:!0,force:!0}),s+=a.size,i+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return i>0&&E.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:s,totalBytes:o-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var kn=2e3,xn=600*1e3,On=new Set(["completed","failed","canceled","timeout"]);function Pn(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function Nn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Cn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Rn(){return process.env.EXECUTION_ID||null}function At(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function kt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let r=Number.isFinite(e.timeoutMs)?e.timeoutMs:xn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:b}=await Tt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),g=At(b,e.output);return E.info(`[sub-graph] '${n}' completed in-process`),g}catch(b){if(b instanceof N||b?.fallback)E.info(`[sub-graph] in-process fallback for '${n}': ${b.reason||"unknown"} \u2014 using HTTP`);else throw b}let s=Pn(),i=Nn(),a=Cn(),u=Rn(),d=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,m={input:e.input||{},...u?{parentExecutionId:u}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${u||"<none>"}`);let l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(m)});if(!l.ok){let b=null,g="";try{b=await l.json(),g=b?.error||b?.message||JSON.stringify(b)}catch{g=await l.text().catch(()=>"")}if(l.status===429){let w=b?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw $.code="SUBGRAPH_QUOTA_EXCEEDED",$.status=429,$.subgraph=n,$.quotaInfo=w,$}if(l.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=b?.validationErrors||null,w.missing=b?.missing||null,w}let y=new Error(`Sub-graph '${n}' trigger rejected (${l.status}): ${g}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=l.status,y.subgraph=n,y}let c=await l.json(),p=c?.data?.jobId||c?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:kn,v=`${s}/executions/${encodeURIComponent(p)}`,A=Date.now()+r,T="accepted",f=0,_=null;for(;Date.now()<A;){await new Promise(w=>setTimeout(w,h)),f+=1;let b;try{b=await fetch(v,{headers:{Authorization:`Bearer ${a}`}})}catch(w){_=w?.message||String(w),E.warn(`[sub-graph] status poll for ${p} could not reach the API (${_}), will retry`);continue}if(!b.ok){if(b.status>=500){E.warn(`[sub-graph] status poll for ${p} returned ${b.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${b.status}`)}let g;try{g=await b.json()}catch(w){_=w?.message||String(w),E.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${_}), will retry`);continue}let y=g?.data||g?.execution||g;if(T=y?.status||T,On.has(T)){if(T!=="completed"){let X=new Error(`Sub-graph '${n}' (${p}) ended in status '${T}'`);throw X.subgraphJobId=p,X.subgraphStatus=T,X}let w=y?.finalState||y?.state||{},$=At(w,e.output);return E.info(`[sub-graph] '${n}' (${p}) completed after ${f} polls`),$}}throw me(n,p,r,T,_)}import{existsSync as xt,readFileSync as Mn}from"node:fs";import{join as je,dirname as Ot}from"node:path";var ye=class{static async loadContext(e,t,o={}){let r={},s=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ot(je(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let m=u.replace(/\.[^.]+$/,"").toLowerCase();r[m]=d}}}let i=o.discovery||{};for(let[a,u]of Object.entries(i))try{let d=je(t,u);xt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],s=t;for(;s.startsWith(o);){let i=je(s,e);if(xt(i))try{r.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=Ot(s);if(a===s)break;s=a}return r.length===0?null:r.every(i=>typeof i=="string")?r.join(`
34
+ ${i}`);let a=o(),l=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=je(d,ee);if(_t(u)){let g=JSON.parse(wt(u,"utf-8"));g.currentNode=this.name,De(u,JSON.stringify(g,null,2),"utf-8")}let c=je(d,"..",ee);if(_t(c))try{let g=JSON.parse(wt(c,"utf-8"));g.currentNode=this.name,De(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(u){I.debug(`[workflow] could not update session info: ${u.message}`)}let S=null;for(let u=0;u<=this.retries;u++)try{I.debug(`[workflow] node '${this.name}' attempt ${u}`);let c=o().config||{},g=c.agents||{},p=this.config.agent??g[this.name]??null,T={state:o()};p&&(T.preferredAgent=p);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let h=await $(i,T,A),b,v;if(typeof h=="string"?(b=h,v=null):h.structured?(b=h.raw||JSON.stringify(h.structured,null,2),v=h.structured):(b=h.raw||JSON.stringify(h,null,2),v=h.extracted||null),d)try{let f=je(d,this.name,"raw_stream_output.txt");gn(mn(f),{recursive:!0}),De(f,typeof b=="string"?b:JSON.stringify(b),"utf-8")}catch(f){I.debug(`[workflow] could not save raw output: ${f.message}`)}if(this.isZodSchema&&v){I.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let f=v;if(typeof this.onComplete=="function")try{f=await this.onComplete(o(),v)}catch(w){I.warn(`[workflow] onComplete hook failed: ${w.message}`)}return{success:!0,output:f,raw:b}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:b}),raw:b}}catch(f){throw new Error(`onComplete failed: ${f.message}`,{cause:f})}if(this.parser){let f=this.parser.parse(b);return I.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(f,null,2)}`),M.step("Output parsed"),{success:!0,output:f,raw:b}}return{success:!0,output:b,raw:b}}catch(c){S=c,u<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:S.message,raw:null}}};z();z();import{mkdirSync as bn,existsSync as V,statSync as kt,readdirSync as Pt,rmSync as En}from"node:fs";import{spawn as At}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as In}from"node:url";import{AsyncLocalStorage as Tn}from"node:async_hooks";import{AsyncLocalStorage as yn}from"node:async_hooks";var le=new yn;function te(){let n=le.getStore();return n||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,agent:null,signal:null})}function bt(n,e){let t=le.getStore()||te(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return le.run(o,e)}function Et(n,e,t){let o=le.getStore()||te(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return le.run(r,t)}var Le=new Map,Ge=new Map,It=new Map;function Tt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(n,e),Ge.set(n,"ready"),It.set(n,{...t,cachedAt:Date.now()})}function $t(n,e){Ge.set(n,"failed"),It.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(n)}function vt(n){return Ge.get(n)==="ready"?Le.get(n):null}function ue(n,e,t=process.env){let o=Number(t[n]);return Number.isFinite(o)&&o>0?Math.min(12e4,Math.max(1e3,Math.floor(o))):e}function Fe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function de(n,e){return Fe(ue(n,e),n)}function D(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var _e=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $n(){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"}};function be(n,e,t,o="timeout",r=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(r?`; the status API was unreachable on the last attempt (${r})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=o,r&&(i.subgraphTransportError=r),i}function vn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,r=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(r)&&r>0?r-i:null;if(o===null&&s===null)return null;let a=o===null?s:s===null?o:Math.min(o,s);return Math.max(1,a)}function An(n,e){let t=new AbortController,o=!1,r=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(r=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof r.unref=="function"&&r.unref()),{signal:t.signal,timedOut:()=>o,dispose(){r&&(clearTimeout(r),r=null),n&&n.removeEventListener("abort",i)}}}var Ot=new Tn,xt=Promise.resolve();async function On(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=Ot.getStore()===!0,r=null;if(!o){let s=xt;xt=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await Ot.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function xn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function kn({apiBase:n,authToken:e,body:t}){let o=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),r;try{r=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal})}catch(s){throw new N(D(s)?"begin-timeout":"network",D(s)?`begin TIMED OUT ${o.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await r.json()}catch(s){if(D(s))throw new N("begin-timeout",`begin body read TIMED OUT ${o.label}`)}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(r.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new N("begin-status",`begin returned ${r.status}`)}return i?.data||i}async function K({apiBase:n,authToken:e,payload:t}){let o=de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let r=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize ${D(r)?`TIMED OUT ${o.label}`:`failed: ${r.message}`}`)}}async function Pn(n,e){let t=H(e,".ready"),o=H(e,"graph.mjs");if(V(t)&&V(o))return;bn(e,{recursive:!0});let r=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(r,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(V(t)&&V(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let S=Math.ceil(1e4/1e3),u=Math.ceil(ue("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=At("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),g=At("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(g.stdin);let p,T,A=()=>{if(p!==void 0&&T!==void 0){if(p!==0)return d(new Error(`curl exited ${p}`));if(T!==0)return d(new Error(`tar exited ${T}`));l()}};c.on("close",$=>{p=$,A()}),g.on("close",$=>{T=$,A()}),c.on("error",d),g.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function Nn(n){let e=H(n,"graph.mjs");if(!V(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(In(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function Nt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=te(),o;try{o=xn()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await kn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:S,bundleReady:u,nodeConfigs:c}=r,g=$n();if(s&&s!==g)throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${g} vs ${s}`);if(!u||!a)throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let p=vt(n);if(!p){let m=H(_e,`${S}@${d||"0"}`);try{await Pn(a,m);try{Rn()}catch{}}catch(y){throw y.fallback&&await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{p=await Nn(m),Tt(n,p,{workflowUuid:S,version:d,runtimeTag:s,cacheDir:m})}catch(y){throw $t(n,y),await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let T=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...$?{nodeConfigs:c}:{}},b=vn(e.timeoutMs),v=An(e.signal,b),f,w;try{f=await On(A,async()=>{let y=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return bt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,h,{signal:v.signal}))}),w=f&&typeof f=="object"&&"state"in f?f.state:f}catch(m){let y=v.timedOut();throw await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-T}}),y?be(n,i,b):m}finally{v.dispose()}if(f&&typeof f=="object"&&f.stoppedExternally){let m=v.timedOut();if(await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:m?"timeout":"canceled",finalState:w,durationMs:Date.now()-T}}),m)throw be(n,i,b);let y=new Error(`Sub-graph '${n}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await K({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-T}}),{finalState:w,executionId:i}}function Mn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=kt(o)}catch{continue}if(r.isDirectory()){let i;try{i=Pt(o)}catch{continue}for(let s of i)t.push(H(o,s))}else e+=r.size}return e}function Rn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!V(_e))return{evicted:0,freedBytes:0};let e=Pt(_e),t=[],o=0;for(let a of e){let l=H(_e,a),d;try{d=kt(l)}catch{continue}let S=d.isDirectory()?Mn(l):d.size;o+=S,t.push({name:a,full:l,size:S,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!V(H(a.full,".lock")))try{En(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bn=2e3,Un=600*1e3,Dn=new Set(["completed","failed","canceled","timeout"]);var jn=()=>de("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Ln(n){let e=ue("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Fe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Gn(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function Fn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Wn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Hn(){return process.env.EXECUTION_ID||null}function Mt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function Rt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=te();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let r=Number.isFinite(e.timeoutMs)?e.timeoutMs:Un;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:f}=await Nt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),w=Mt(f,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),w}catch(f){if(f instanceof N||f?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${f.reason||"unknown"} \u2014 using HTTP`);else throw f}let i=Gn(),s=Fn(),a=Wn(),l=Hn(),d=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,S={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=jn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(S),signal:u.signal})}catch(f){if(!D(f))throw f;let w=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw w.code="SUBGRAPH_TRIGGER_TIMEOUT",w.subgraph=n,w.timedOut=!0,w.cause=f,w}if(!c.ok){let f=null,w="";try{f=await c.json(),w=f?.error||f?.message||JSON.stringify(f)}catch{w=await c.text().catch(()=>"")}if(c.status===429){let y=f?.quotaInfo||{},O=new Error(`Sub-graph '${n}' blocked by execution quota (${y.used??"?"}/${y.limit??"?"} on plan ${y.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw O.code="SUBGRAPH_QUOTA_EXCEEDED",O.status=429,O.subgraph=n,O.quotaInfo=y,O}if(c.status===400){let y=new Error(`Sub-graph '${n}' rejected input: ${w}`);throw y.code="SUBGRAPH_INVALID_INPUT",y.status=400,y.subgraph=n,y.validationErrors=f?.validationErrors||null,y.missing=f?.missing||null,y}let m=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${w}`);throw m.code="SUBGRAPH_TRIGGER_FAILED",m.status=c.status,m.subgraph=n,m}let g;try{g=await c.json()}catch(f){if(!D(f))throw f;let w=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw w.code="SUBGRAPH_TRIGGER_TIMEOUT",w.subgraph=n,w.timedOut=!0,w.cause=f,w}let p=g?.data?.jobId||g?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(g).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let T=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bn,A=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+r,h="accepted",b=0,v=null;for(;Date.now()<$;){await new Promise(O=>setTimeout(O,T)),b+=1;let f=Ln($),w;try{w=await fetch(A,{headers:{Authorization:`Bearer ${a}`},signal:f.signal})}catch(O){v=D(O)?`poll TIMED OUT ${f.label}`:O?.message||String(O),I.warn(`[sub-graph] status poll for ${p} could not reach the API (${v}), will retry`);continue}if(!w.ok){if(w.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${w.status}`)}let m;try{m=await w.json()}catch(O){v=D(O)?`poll body read TIMED OUT ${f.label}`:O?.message||String(O),I.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${v}), will retry`);continue}let y=m?.data||m?.execution||m;if(h=y?.status||h,Dn.has(h)){if(h!=="completed"){let J=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw J.subgraphJobId=p,J.subgraphStatus=h,J}let O=y?.finalState||y?.state||{},F=Mt(O,e.output);return I.info(`[sub-graph] '${n}' (${p}) completed after ${b} polls`),F}}throw be(n,p,r,h,v)}import{existsSync as Ct,readFileSync as Jn}from"node:fs";import{join as We,dirname as Bt}from"node:path";var Ie=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Bt(We(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let S=l.replace(/\.[^.]+$/,"").toLowerCase();r[S]=d}}}let s=o.discovery||{};for(let[a,l]of Object.entries(s))try{let d=We(t,l);Ct(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=We(i,e);if(Ct(s))try{r.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=Bt(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):r.every(i=>typeof i=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Mn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Ct,existsSync as De,writeFileSync as Pt,unlinkSync as Bn}from"node:fs";import{join as Z,resolve as Rt}from"node:path";import{config as jn}from"dotenv";import{zodToJsonSchema as Nt}from"zod-to-json-schema";import{z as we}from"zod";import Dn from"handlebars";function Ln({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${i} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let m=(new Error("session trace").stack||"").split(`
38
+ `):r.every(s=>typeof s=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Jn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as jt,existsSync as He,writeFileSync as Ut,unlinkSync as zn}from"node:fs";import{join as X,resolve as Lt}from"node:path";import{config as Yn}from"dotenv";import{zodToJsonSchema as Dt}from"zod-to-json-schema";import{z as Te}from"zod";import Zn from"handlebars";function qn({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${o} mkdir=${r?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let S=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${n}):
41
- ${m}`)}}function Un(){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 Fn(){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 Rt(String(e).trim())}catch{return String(e).trim()}}function Wn(){Un()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Gn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Hn(n={}){let e=at.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Jn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,s=t.sessionTimestamp,i="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Rt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,i="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).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)a=d,i="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,i="config.sessionId"):(a=Hn(e),i="generated")}s=s??Date.now();let m=e.paths?.output||fe;r=Z(n,m,st,a)}let u=!De(r);return u&&Ct(r,{recursive:!0}),(u||i!=="initialState.sessionPath")&&Ln({traceFrom:o,sessionId:a,sessionPath:r,idSource:i,mkdirFresh:u}),Gn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:s}}var Se=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,o={}){if(!(t instanceof U)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let i=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:i.workflow,retries:i.retries,onComplete:i.onComplete,execute:async d=>{let m=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof i.input=="function"?l=i.input(m):i.input&&typeof i.input=="object"?l=i.input:l={},kt(i.workflow,{input:l,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(m):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:m?._signal,parentAgent:d?.agent})}},u=new U(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof U)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof U?t:new U(r?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=s=>{t.set(s,1);for(let i of this._simpleTargets(s)){if(!i||i==="END")continue;let a=t.get(i)||0;a===1?e.add(`${s}->${i}`):a===0&&o(i)}t.set(s,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[s]of this.edges)for(let i of this._simpleTargets(s))!i||i==="END"||e.has(`${s}->${i}`)||r.set(i,(r.get(i)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,s){let i=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=i;i=()=>u(t,d,r,s)}return i()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let p=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:p,data:{nodeType:p,label:l}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(h.description=v);let A=this.nodePrompts.get(l);if(A)h.prompt=A;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(h.prompt=y,h.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString());let T=c?.config?.dispatchesWorkflow;if(typeof T=="string"&&T.trim())h.dispatchesWorkflow=T.trim();else if(Array.isArray(T)){let y=[...new Set(T.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];y.length&&(h.dispatchesWorkflow=y)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(h.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof we?.toJSONSchema=="function")try{y=we.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=Nt(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[l];f?.toolIds&&(h.tools=f.toolIds);let _=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;_&&_.length>0&&(h.skills=[..._]);let b=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;b&&b.length>0&&(h.plugins=b.map(y=>y&&typeof y=="object"?{...y}:y));let g=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;g&&g.length>0&&(h.stores=g.map(y=>y&&typeof y=="object"?{...y}:y)),Object.keys(h).length>0&&(t[l]=h)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let p of c)o.push({source:l,target:p});else if(c.conditional){let p=this.conditionalCodeMap.get(l)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},A=this.nodes.get(l),T=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!T){let _=`${l}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),o.push({source:l,target:_}),f=_}for(let _ of h){let b={source:f,target:_,data:{conditionalCode:p}};v[_]&&(b.label=v[_]),o.push(b)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Nt(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of o)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"}}),o.push({source:l,target:c})}let i=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),m=r(this.contextSchema);return{nodes:i,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:m}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),i=new Map(e.map(l=>[l.id,[]]));for(let l of t)i.has(l.source)&&s.has(l.target)&&(i.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>s.get(l)===0),m=[];for(;m.length<e.length;){let l;if(d.length>0){if(d.sort((c,p)=>o.get(c)-o.get(p)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,p)=>o.get(c)-o.get(p))[0];a.add(l),u.delete(l),m.push(r.get(l));for(let c of i.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return m}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=s.exec(o))!==null;){let d=i[2]!==void 0?i[2]:i[3];d!==void 0&&d!==""&&r.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 r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=d.exec(o))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},s=e.required||[];for(let[i,a]of Object.entries(r)){let u=t?`${t}.${i}`:i;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!s.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,s]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof s=="string"&&s.length<=80)o.push(`${r}: ${s}`);else if(Array.isArray(s)){let i=s.length,a=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${r}: ${i} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(I){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${I?.message||I}`);throw S.cause=I,S.code=I?.code||"NORMALIZE_INPUT_FAILED",S}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let s=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,i=t.cwd||process.cwd();jn({path:Z(i,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let I=Z(i,".zibby.config.js");De(I)&&(a=(await import(I)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let I=a?.agent;I?.provider?u=I.provider:I?.gemini?u="gemini":I?.claude?u="claude":I?.cursor?u="cursor":I?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let I=m.safeParse(t);if(!I.success){let S=I.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${S.join(", ")}`)}P.step("State validated against schema")}let l=Fn(),c=t.sessionPath||l;c||Wn();let{sessionPath:p,sessionTimestamp:h,sessionId:v}=Jn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${v}`);let A=await ye.loadContext(t.specPath||"",i,d);Object.keys(A).length>0&&P.step(`Context loaded: ${Object.keys(A).join(", ")}`);let T=t.outputPath;!T&&t.specPath&&(e?.calculateOutputPath?T=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ue({...t,config:a,agentType:u,outputPath:T,sessionPath:p,sessionTimestamp:h,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:b}=await Promise.resolve().then(()=>(he(),lt)),g=a.skills&&typeof a.skills=="object"?a.skills:{},y=Object.values(g).filter(I=>I&&typeof I=="object"&&typeof I.id=="string"),w=I=>{for(let S of y)if(S.id===I)return S;return b(I)},$=new Set;for(let[,I]of this.nodes)for(let S of I.config?.skills||[])$.add(S);for(let I of $){let S=w(I);if(typeof S?.middleware=="function")try{let R=await S.middleware();typeof R=="function"&&_.set(I,R)}catch{}}let{backEdges:X,joinDegree:Lt}=this._analyzeFlow(),be=new Map,Q=[],Ie=(I,S,R)=>{if(!I||I==="END")return;let D=Lt.get(I)||0;if(R&&D>1&&!X.has(`${S}->${I}`)){let ee=(be.get(I)||0)+1;if(ee<D){be.set(I,ee);return}be.set(I,0)}Q.includes(I)||Q.push(I)};this.entryPoint&&Q.push(this.entryPoint);let ae=[],We=a?.recursionLimit??100,Ut=0;try{for(;Q.length>0;){let S=Q.pop();if(!S||S==="END")continue;if(++Ut>We)throw new Error(`Workflow exceeded recursion limit (${We}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let R=Z(p,it);if(De(R)){try{Bn(R)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};let D=this.nodes.get(S);if(!D)throw new Error(`Node '${S}' not found in graph`);let ee=JSON.stringify({sessionPath:p,sessionTimestamp:h,currentNode:S,createdAt:new Date().toISOString(),config:f.get("config")}),Ft=Z(p,K);Pt(Ft,ee,"utf-8");let Ge=f.get("config")?.paths?.output||fe,Wt=Z(i,Ge,K);Ct(Z(i,Ge),{recursive:!0});try{Pt(Wt,ee,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:i,sessionPath:p,sessionId:v,outputBase:f.get("config")?.paths?.output||fe,currentNode:S})}catch{}let Gt=(this.resolvedToolsMap||{})[S]||null;f.set("_currentNodeTools",Gt);let Ht=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ht[S]||{}),P.nodeStart(S);let Je=Date.now(),ce=this.nodePrompts.get(S);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(se(),re));this._invokeAgent=x.invokeAgent}let Jt=this._invokeAgent,Ee={},zt=D.config?.skills||[];for(let x of zt){let C=w(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:S});k&&typeof k=="object"&&(Ee={...Ee,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let ze=async(x,C,k={})=>{let M=Jt(x,C,{...Ee,...k,signal:r.signal});return M.catch(()=>{}),r.signal.aborted?M:Promise.race([M,new Promise((q,L)=>{let B=()=>{setTimeout(()=>{let qe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);qe.name="AbortError",L(qe)},s)};r.signal.addEventListener("abort",B,{once:!0})})])},Yt=async(x={},C={})=>{let k=C.prompt||"";if(ce){let M=this._compiledPrompts.get(S);M||(M=Dn.compile(ce,{noEscape:!0}),this._compiledPrompts.set(S,M));try{k=M(x)}catch(q){throw console.error(`\u274C Template rendering failed for node '${S}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!k)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return ze(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:r.signal,nodeName:S})},Ye=f.getAll(),Zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of Zt)Object.prototype.hasOwnProperty.call(Ye,x)&&console.warn(`[workflow] node "${S}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let Ze={...Ye,state:f,invokeAgent:Yt,_coreInvokeAgent:ze,agent:e,nodeId:S,promptTemplate:ce,getPromptTemplate:()=>ce};try{let x=(D.config?.skills||[]).map(B=>_.get(B)).filter(Boolean),C=[...this.middleware,...x],k;k=await mt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,S,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let M=Date.now()-Je;if(ae.push({node:S,success:k.success,duration:M,timestamp:new Date().toISOString()}),!k.success){if(r.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};f.append("errors",{node:S,error:k.error});let B=(D.config?.retries||0)+1;throw P.nodeFailed(S,k.error,{duration:M}),new Error(`Node '${S}' failed after ${B} attempt(s): ${k.error}`)}f.update({[S]:k.output});let q=this._summarizeNodeOutput(S,k.output);P.nodeComplete(S,{duration:M,details:q});let L=this.edges.get(S);if(L)if(L.conditional){let B=L.routes(f.getAll());P.route(S,B),Ie(B,S,!1)}else if(Array.isArray(L))for(let B=L.length-1;B>=0;B--)Ie(L[B],S,!0);else Ie(L,S,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(S,x.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",S),x}}P.graphComplete();let I={success:!0,state:f.getAll(),executionLog:ae};return e&&typeof e.onComplete=="function"&&await e.onComplete(I),I}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(I){console.warn(`[workflow] agent.cleanup() failed: ${I.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var Ue=globalThis[Le];function zn(n,e){Ue.set(n,e)}function Mt(n){return Ue.get(n)}function Fe(n){return Ue.has(n)}zn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(se(),re))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",s=Yn(r,t),i=await o(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:n},raw:typeof i=="string"?i:i.raw}}})});function Yn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let s=[],i=new Set;for(let a of o){let u=a.split(".")[0];if(i.has(u))continue;let d=a.split(".").reduce((c,p)=>c?.[p],e);if(d===void 0)continue;let m=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
43
- ${m}`),a.includes(".")||i.add(u)}return s.length===0?n:`${n}
41
+ ${S}`)}}function Kn(){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 Vn(){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 Lt(String(e).trim())}catch{return String(e).trim()}}function Xn(){Kn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Qn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function eo(n={}){let e=ft.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function to({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Lt(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).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,s="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,s="config.sessionId"):(a=eo(e),s="generated")}i=i??Date.now();let S=e.paths?.output||Se;r=X(n,S,dt,a)}let l=!He(r);return l&&jt(r,{recursive:!0}),(l||s!=="initialState.sessionPath")&&qn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:l}),Qn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var $e=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,o={}){if(!(t instanceof W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let S=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof s.input=="function"?u=s.input(S):s.input&&typeof s.input=="object"?u=s.input:u={},Rt(s.workflow,{input:u,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(S):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:S?._signal,parentAgent:d?.agent})}},l=new W(a);return l.name=e,this.nodes.set(e,l),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:o}={}){let r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:o}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,o=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let l=e[a],d=s;s=()=>l(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let g=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:g,data:{nodeType:g,label:u}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let T=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;T&&(p.description=T);let A=this.nodePrompts.get(u);if(A)p.prompt=A;else if(typeof c.prompt=="function")try{let m=c.prompt({});typeof m=="string"&&m.trim()&&(p.prompt=m,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let $=c?.config?.dispatchesWorkflow;if(typeof $=="string"&&$.trim())p.dispatchesWorkflow=$.trim();else if(Array.isArray($)){let m=[...new Set($.filter(y=>typeof y=="string").map(y=>y.trim()).filter(Boolean))];m.length&&(p.dispatchesWorkflow=m)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let m=null;if(typeof Te?.toJSONSchema=="function")try{m=Te.toJSONSchema(c.outputSchema)}catch{}if(!m)try{m=Dt(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=m?{jsonSchema:m,variables:this._flattenJsonSchemaToVariables(m)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[u];h?.toolIds&&(p.tools=h.toolIds);let b=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;b&&b.length>0&&(p.skills=[...b]);let v=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;v&&v.length>0&&(p.plugins=v.map(m=>m&&typeof m=="object"?{...m}:m));let f=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;f&&f.length>0&&(p.stores=f.map(m=>m&&typeof m=="object"?{...m}:m));let w=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(w&&w.length>0){let m=new Set,y=[];for(let O of w){let F=typeof O=="string"?O.trim():"";!F||m.has(F)||(m.add(F),y.push(F))}y.length>0&&(p.uses=y)}Object.keys(p).length>0&&(t[u]=p)}let o=[];for(let[u,c]of this.edges)if(typeof c=="string")o.push({source:u,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:u,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(u)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),T=c.labels||{},A=this.nodes.get(u),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!A,h=u;if(!$){let b=`${u}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),o.push({source:u,target:b}),h=b}for(let b of p){let v={source:h,target:b,data:{conditionalCode:g}};T[b]&&(v.label=T[b]),o.push(v)}}let r=u=>{if(!u)return null;if(typeof Te?.toJSONSchema=="function")try{return Te.toJSONSchema(u)}catch{}try{return Dt(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let u of o)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:u,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),l=r(a||this.stateSchema),d=r(this.inputSchema),S=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:S}}_topoOrderNodes(e,t){let o=new Map(e.map((u,c)=>[u.id,c])),r=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),s=new Map(e.map(u=>[u.id,[]]));for(let u of t)s.has(u.source)&&i.has(u.target)&&(s.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(o.keys()),d=[...l].filter(u=>i.get(u)===0),S=[];for(;S.length<e.length;){let u;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(u),l.delete(u),S.push(r.get(u));for(let c of s.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return S}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.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 l=new Set;for(let d of r)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=d.exec(o))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let l=t?`${t}.${s}`:s;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,l=i.some(d=>d?.passed!==void 0);o.push(l?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(E){let _=new Error(`agent.normalizeInput() rejected the trigger input: ${E?.message||E}`);throw _.cause=E,_.code=E?.code||"NORMALIZE_INPUT_FAILED",_}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Yn({path:X(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=X(s,".zibby.config.js");He(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let E=a?.agent;E?.provider?l=E.provider:E?.gemini?l="gemini":E?.claude?l="claude":E?.cursor?l="cursor":E?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let E=S.safeParse(t);if(!E.success){let _=E.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${_.join(", ")}`)}M.step("State validated against schema")}let u=Vn(),c=t.sessionPath||u;c||Xn();let{sessionPath:g,sessionTimestamp:p,sessionId:T}=to({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});M.step(`Session ${T}`);let A=await Ie.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&M.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new ge({...t,config:a,agentType:l,outputPath:$,sessionPath:g,sessionTimestamp:p,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:v}=await Promise.resolve().then(()=>(we(),gt)),f=a.skills&&typeof a.skills=="object"?a.skills:{},w=Object.values(f).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),m=E=>{for(let _ of w)if(_.id===E)return _;return v(E)},y=new Set;for(let[,E]of this.nodes)for(let _ of E.config?.skills||[])y.add(_);for(let E of y){let _=m(E);if(typeof _?.middleware=="function")try{let C=await _.middleware();typeof C=="function"&&b.set(E,C)}catch{}}let{backEdges:O,joinDegree:F}=this._analyzeFlow(),J=new Map,ne=[],Ae=(E,_,C)=>{if(!E||E==="END")return;let L=F.get(E)||0;if(C&&L>1&&!O.has(`${_}->${E}`)){let oe=(J.get(E)||0)+1;if(oe<L){J.set(E,oe);return}J.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let pe=[],Ze=a?.recursionLimit??100,Jt=0;try{for(;ne.length>0;){let _=ne.pop();if(!_||_==="END")continue;if(++Jt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=X(g,pt);if(He(C)){try{zn(C)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),M.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};let L=this.nodes.get(_);if(!L)throw new Error(`Node '${_}' not found in graph`);let oe=JSON.stringify({sessionPath:g,sessionTimestamp:p,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),zt=X(g,ee);Ut(zt,oe,"utf-8");let qe=h.get("config")?.paths?.output||Se,Yt=X(s,qe,ee);jt(X(s,qe),{recursive:!0});try{Ut(Yt,oe,"utf-8")}catch{}let Ke=t.onPipelineProgress;if(typeof Ke=="function")try{Ke({cwd:s,sessionPath:g,sessionId:T,outputBase:h.get("config")?.paths?.output||Se,currentNode:_})}catch{}let Zt=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",Zt);let qt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",qt[_]||{}),M.nodeStart(_);let Ve=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ce(),ae));this._invokeAgent=k.invokeAgent}let Kt=this._invokeAgent,Oe={},Vt=L.config?.skills||[];for(let k of Vt){let R=m(k);if(typeof R?.invokeAgentOptions=="function")try{let x=R.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});x&&typeof x=="object"&&(Oe={...Oe,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let Xe=async(k,R,x={})=>{let B=Kt(k,R,{...Oe,...x,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((Q,G)=>{let U=()=>{setTimeout(()=>{let tt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);tt.name="AbortError",G(tt)},i)};r.signal.addEventListener("abort",U,{once:!0})})])},Xt=async(k={},R={})=>{let x=R.prompt||"";if(fe){let B=this._compiledPrompts.get(_);B||(B=Zn.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,B));try{x=B(k)}catch(Q){throw console.error(`\u274C Template rendering failed for node '${_}':`,Q.message),new Error(`Template rendering failed: ${Q.message}`,{cause:Q})}}else if(!x)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Xe(x,{state:h.getAll(),images:R.images||[]},{model:R.model||h.get("model"),workspace:h.get("workspace"),schema:R.schema,...R,signal:r.signal,nodeName:_})},Qe=h.getAll(),Qt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Qt)Object.prototype.hasOwnProperty.call(Qe,k)&&console.warn(`[workflow] node "${_}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let et={...Qe,state:h,invokeAgent:Xt,_coreInvokeAgent:Xe,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let k=(L.config?.skills||[]).map(U=>b.get(U)).filter(Boolean),R=[...this.middleware,...k],x;x=await Et(e,r.signal,async()=>R.length>0?this._composeMiddleware(R,_,async()=>L.execute(et,h),h.getAll(),h):L.execute(et,h));let B=Date.now()-Ve;if(pe.push({node:_,success:x.success,duration:B,timestamp:new Date().toISOString()}),!x.success){if(r.signal.aborted)return M.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};h.append("errors",{node:_,error:x.error});let U=(L.config?.retries||0)+1;throw M.nodeFailed(_,x.error,{duration:B}),new Error(`Node '${_}' failed after ${U} attempt(s): ${x.error}`)}h.update({[_]:x.output});let Q=this._summarizeNodeOutput(_,x.output);M.nodeComplete(_,{duration:B,details:Q});let G=this.edges.get(_);if(G)if(G.conditional){let U=G.routes(h.getAll());M.route(_,U),Ae(U,_,!1)}else if(Array.isArray(G))for(let U=G.length-1;U>=0;U--)Ae(G[U],_,!0);else Ae(G,_,!0)}catch(k){throw M.isInsideNode&&M.nodeFailed(_,k.message,{duration:Date.now()-Ve}),h.set("failed",!0),h.set("failedAt",_),k}}M.graphComplete();let E={success:!0,state:h.getAll(),executionLog:pe};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 Je=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Je]||(globalThis[Je]=new Map);var ze=globalThis[Je];function no(n,e){ze.set(n,e)}function Gt(n){return ze.get(n)}function Ye(n){return ze.has(n)}no("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ce(),ae))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",i=oo(r,t),s=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:n},raw:typeof s=="string"?s:s.raw}}})});function oo(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let i=[],s=new Set;for(let a of o){let l=a.split(".")[0];if(s.has(l))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let S=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${u}
43
+ ${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
- ${s.join(`
48
+ ${i.join(`
49
49
 
50
- `)}`}he();W();var Zn={};function jt(n,e){if(Array.isArray(e))return Bt(e);let t=Zn[n];return!t||t.length===0?null:Bt(t)}function Bt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let s=oe(r);if(!s){E.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let i of s.tools||[])e.push({name:i.name,description:i.description,input_schema:i.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let i=s.resolve();i&&(t[s.serverName]={...i,toolPrefix:r})}else{let i={};for(let a of s.envKeys||[]){let u=process.env[a];u&&(i[a]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:i,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}W();function rr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let s=new Se(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let i=new Set,a=new Map,u={};for(let c of t){let p=_e(c);a.set(c.id,{...c,resolvedType:p}),p==="decision"&&i.add(c.id)}for(let[c,p]of a){if(i.has(c))continue;let h=p.resolvedType,v=r[c]||{},A=jt(h,v.tools);A&&(u[c]=A);let T={};v.prompt&&(T.prompt=v.prompt);let f=Fe(h);if(E.debug(`[workflow] compiler: node "${c}" type="${h}" registered=${f}`),v.customCode&&!f)s.addNode(c,Dt(c,v.customCode,v),T),s.setNodeType(c,h);else if(f){let _=Mt(h);_.factory?s.addNode(c,_.create(c,{...v,resolvedTools:A}),T):s.addNode(c,_,T),s.setNodeType(c,h)}else if(v.executeCode)s.addNode(c,Dt(c,v.executeCode,v),T),s.setNodeType(c,h);else throw new j(`Unknown node type "${h}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of o)i.has(c.target)||d.add(c.target);let m=t.find(c=>!i.has(c.id)&&!d.has(c.id));if(!m)throw new j("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(m.id);let l=qn(o,"source");for(let c of o)if(!i.has(c.source))if(i.has(c.target)){let p=c.target,h=l.get(p)||[];if(h.length===0)throw new j(`Decision node "${p}" has no outgoing edges`);let v=Kn(p,h,i);s.addConditionalEdges(c.source,v)}else s.addEdge(c.source,c.target);return s}function sr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let u=_e(a);if(u==="decision"||Fe(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 o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>_e(a)==="decision").map(a=>a.id)),s=new Set;for(let a of n.edges)r.has(a.target)||s.add(a.target);let i=n.nodes.filter(a=>!r.has(a.id)&&!s.has(a.id));i.length===0?e.push("No entry point found (every node has incoming edges)"):i.length>1&&e.push(`Multiple entry points found: ${i.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(m=>m.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.some(m=>m.data?.conditionalCode||m.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function ir(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>_e(e)!=="decision").map(e=>e.id)}function _e(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function qn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Kn(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),i;try{let u=new Function(`return (${r})`)();i=d=>{let m=u(d);return s.has(m)||E.warn(`[workflow] conditional route from "${n}" returned "${m}" which is not in valid targets: ${[...s].join(", ")}`),m}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return i}function Dt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(i){throw new j(`Failed to compile customCode for node "${n}": ${i.message}`)}let r=o(async(...i)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(se(),re));return a(...i)},typeof $e<"u"?$e:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:s,execute:async i=>{try{let a=await r(i);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,rr as compileGraph,ir as extractSteps,sr as validateGraphConfig};
50
+ `)}`}we();z();var ro={};function Wt(n,e){if(Array.isArray(e))return Ft(e);let t=ro[n];return!t||t.length===0?null:Ft(t)}function Ft(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let i=ie(r);if(!i){I.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(t[i.serverName]={...s,toolPrefix:r})}else{let s={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(s[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}z();function yr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new $e(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let g=ve(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&s.add(c.id)}for(let[c,g]of a){if(s.has(c))continue;let p=g.resolvedType,T=r[c]||{},A=Wt(p,T.tools);A&&(l[c]=A);let $={};T.prompt&&($.prompt=T.prompt);let h=Ye(p);if(I.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${h}`),T.customCode&&!h)i.addNode(c,Ht(c,T.customCode,T),$),i.setNodeType(c,p);else if(h){let b=Gt(p);b.factory?i.addNode(c,b.create(c,{...T,resolvedTools:A}),$):i.addNode(c,b,$),i.setNodeType(c,p)}else if(T.executeCode)i.addNode(c,Ht(c,T.executeCode,T),$),i.setNodeType(c,p);else throw new j(`Unknown node type "${p}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let d=new Set;for(let c of o)s.has(c.target)||d.add(c.target);let S=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!S)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let u=so(o,"source");for(let c of o)if(!s.has(c.source))if(s.has(c.target)){let g=c.target,p=u.get(g)||[];if(p.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let T=io(g,p,s);i.addConditionalEdges(c.source,T)}else i.addEdge(c.source,c.target);return i}function Sr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let l=ve(a);if(l==="decision"||Ye(l))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let r=new Set(n.nodes.filter(a=>ve(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)r.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!r.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of r){let l=n.edges.filter(S=>S.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(S=>S.data?.conditionalCode||S.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function wr(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>ve(e)!=="decision").map(e=>e.id)}function ve(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function so(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function io(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let r=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${r})`)();s=d=>{let S=l(d);return i.has(S)||I.warn(`[workflow] conditional route from "${n}" returned "${S}" which is not in valid targets: ${[...i].join(", ")}`),S}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function Ht(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new j(`Failed to compile customCode for node "${n}": ${s.message}`)}let r=o(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),ae));return a(...s)},typeof xe<"u"?xe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await r(s);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,wr as extractSteps,Sr as validateGraphConfig};