@zibby/agent-workflow 2.0.14 → 2.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graph-compiler.js +19 -19
- package/dist/graph.js +18 -18
- package/dist/index.js +20 -20
- package/dist/node.js +16 -16
- package/dist/timeline.d.ts +9 -0
- package/dist/timeline.js +10 -10
- package/package.json +1 -1
package/dist/graph-compiler.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var In=Object.defineProperty;var Ue=(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 Ee=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var
|
|
1
|
+
var In=Object.defineProperty;var Ue=(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 Ee=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var ht=(n,e)=>{for(var t in e)In(n,t,{get:e[t],enumerable:!0})};var gt,An,Le,Ae,A,X=Ee(()=>{gt=()=>{},An={debug:gt,info:gt,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Le=Symbol.for("@zibby/agent-workflow.logger");globalThis[Le]||(globalThis[Le]={impl:An});Ae=globalThis[Le],A={debug:(...n)=>Ae.impl.debug?.(...n),info:(...n)=>Ae.impl.info?.(...n),warn:(...n)=>Ae.impl.warn?.(...n),error:(...n)=>Ae.impl.error?.(...n)}});var xt=Ee(()=>{});var Ot={};ht(Ot,{clearSkills:()=>Gn,getAllSkills:()=>Ln,getSkill:()=>pe,getSkillSource:()=>jn,hasSkill:()=>Un,listSkillIds:()=>Fn,registerSkill:()=>Dn});function Dn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(Q.has(o)&&!r){let i=de.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" 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).`)}}Q.set(o,Object.freeze({...n})),t===void 0?de.delete(o):de.set(o,t)}function pe(n){return Q.get(n)||null}function Un(n){return Q.has(n)}function jn(n){return de.get(n)||null}function Ln(){return new Map(Q)}function Fn(){return Array.from(Q.keys())}function Gn(){Q.clear(),de.clear()}var Ze,Ke,Q,de,$e=Ee(()=>{Ze=Symbol.for("@zibby/agent-workflow.skills"),Ke=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ze]||(globalThis[Ze]=new Map);globalThis[Ke]||(globalThis[Ke]=new Map);Q=globalThis[Ze],de=globalThis[Ke]});var fe={};ht(fe,{EFFORT_LEVELS:()=>Xe,getAgentStrategy:()=>Rt,invokeAgent:()=>zn,listStrategies:()=>Hn,registerStrategy:()=>Wn,resolveInvocationEffort:()=>Nt,resolveInvocationExtras:()=>Mt,resolveInvocationModel:()=>kt});function Wn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=ee.findIndex(t=>t.getName()===n.getName());e>=0?ee[e]=n:ee.push(n)}function Hn(){return ee.map(n=>n.getName())}function kt({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,S=(typeof r=="string"?r.trim():"")||null;return s||a||l||u||e.model||S||null}function Nt({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return r?Xe.indexOf(r)===-1?(A.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${Xe.join(", ")}`),null):r:null}function Mt({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 Rt(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=ee.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}A.debug(`[workflow] agent selection: requested=${r}`);let o=ee.find(i=>i.getName()===r);if(!o){let i=ee.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return A.debug(`[workflow] using agent: ${o.getName()}`),o}async function zn(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=Rt(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,S=kt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d=!l||l===i.name?a.effort:null,c=Nt({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:d}),f={...t,model:S,...c?{effort:c}:{},...Mt({options:t,stateView:r,context:e}),config:s},p=n,y=f.skills||[];if(y.length>0&&!t.skipPromptFragments){let h=t.connectedIntegrations;if(!h){let g=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof g=="string"&&g.trim()!==""){h={};for(let w of g.split(",").map(k=>k.trim()).filter(Boolean))h[w]=!0}}let _=g=>{let w=g&&g.requiresIntegration;return!w||!h?!0:(Array.isArray(w)?w:[w]).some(N=>h[N]===!0)},E=i.name==="assistant",$=g=>g?.inProcessOnly!==!0||E,m=y.map(g=>{let w=pe(g);if(!_(w)||!$(w))return null;let k=w?.promptFragment;return typeof k=="function"?k():k}).filter(Boolean);m.length>0&&(p+=`
|
|
2
2
|
|
|
3
3
|
${m.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let v=r._currentNodeConfig?.stores;if(Array.isArray(v)&&v.length>0&&typeof v[0]=="object"){let h=v.length<=8,_=v.map(E=>{let $=E?.id??E?.storeId??"",m=(E?.name??"").toString().trim()||$,g=E?.type?` \xB7 ${E.type}`:"",w=(E?.description||"").toString().replace(/\s+/g," ").trim(),k=`- ${m} \xB7 ${w||"(no description)"}${g} (id: ${$})`;if(h&&E?.schema&&typeof E.schema=="object"){let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let v=r._currentNodeConfig?.stores;if(Array.isArray(v)&&v.length>0&&typeof v[0]=="object"){let h=v.length<=8,_=v.map(E=>{let $=E?.id??E?.storeId??"",m=(E?.name??"").toString().trim()||$,g=E?.type?` \xB7 ${E.type}`:"",w=(E?.description||"").toString().replace(/\s+/g," ").trim(),k=`- ${m} \xB7 ${w||"(no description)"}${g} (id: ${$})`;if(h&&E?.schema&&typeof E.schema=="object"){let N=E.schema.properties&&typeof E.schema.properties=="object"?Object.keys(E.schema.properties):Object.keys(E.schema);N.length&&(k+=`
|
|
6
|
+
fields: ${N.join(", ")}`)}return k});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${_.join(`
|
|
@@ -14,33 +14,33 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${x}
|
|
17
|
-
`),A.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,f)}var
|
|
17
|
+
`),A.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,f)}var Ve,ee,Xe,he=Ee(()=>{xt();X();$e();Ve=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ve]||(globalThis[Ve]=[]);ee=globalThis[Ve];Xe=["low","medium","high","xhigh","max"]});var Tn=new Set(["__proto__","constructor","prototype"]);function je(n){if(Tn.has(n))throw new Error(`Invalid state key: "${n}"`)}var Ie=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){je(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)je(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){je(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 te from"handlebars";var Te=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};X();import{writeFileSync as
|
|
19
|
+
`)}`);return e}};X();import{writeFileSync as Qe,readFileSync as Pt,existsSync as Ct,mkdirSync as qn}from"node:fs";import{join as et,dirname as Jn}from"node:path";import R from"chalk";var vn="__WORKFLOW_GRAPH_LOG__",ue=R.gray("\u2502"),$n=R.gray("\u250C"),Fe=R.gray("\u2514"),Ge=R.green("\u25C6"),mt=R.hex("#c084fc")("\u25C6"),yt=R.hex("#2dd4bf")("\u25C6"),We=R.red("\u25C6"),St=`${ue} `,wt=2;function He(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function _t(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=St,e.col=wt,e.lineStart=!1),l===`
|
|
20
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
|
-
${
|
|
22
|
-
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
|
-
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
21
|
+
${St}`,e.col=wt))}return n(s,r,o)}}var ze=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._prevStdoutWrite=process.stdout.write,this._prevStderrWrite=process.stderr.write,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=_t(this._origStdoutWrite,e),process.stderr.write=_t(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
|
+
`),process.stdout.write=this._prevStdoutWrite||this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
|
+
`),process.stderr.write=this._prevStderrWrite||this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null,this._prevStdoutWrite=null,this._prevStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
24
|
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${vn}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${$n} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(Ge,e):process.stdout.write.bind(process.stdout)(`${ue} ${Ge} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(mt,e):process.stdout.write.bind(process.stdout)(`${ue} ${mt} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=R.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(yt,t):process.stdout.write.bind(process.stdout)(`${ue} ${yt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(We,R.red(e)):process.stdout.write.bind(process.stdout)(`${ue} ${We} ${R.red(e)}
|
|
32
|
+
`)}nodeStart(e){(this._origStdoutWrite||this._origStderrWrite)&&(console.warn(`[timeline] node '${e}' started while '${this._currentNode||"?"}' still had the stdout interceptor installed \u2014 a node ended without closing its box; unwrapping`),this._stopIntercepting()),this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${$n} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting(),this._currentNode=null;let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Ge} ${s}`);let i=r?R.dim(` ${He(r)}`):"";this._rawWrite(`${Fe} ${R.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting(),this._currentNode=null;let{duration:o}=r,i=o?R.dim(` ${He(o)}`):"";this._rawWrite(`${We} ${R.red(t)}`),this._rawWrite(`${Fe} ${R.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeStopped(e,t={}){this._stopIntercepting(),this._currentNode=null;let{duration:r}=t,o=r?R.dim(` ${He(r)}`):"";this._rawWrite(`${Fe} ${R.dim("stopped")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(R.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},C=new ze;var ve=".zibby/output",bt="sessions",ie=".session-info.json",Et=".zibby-stop";var Jr=Object.freeze(["codebase-memory","code-scan","artifact"]),It=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var xn=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),On=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),kn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),vt=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Je(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function Nn(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=vt.exec(Je(n));return e?e[1].toLowerCase():null}function Mn(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=vt.exec(Je(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function Rn(n){let e=Je(n);if(!e)return"deterministic";for(let o of kn)if(o.test(e))return"deterministic";let t=Nn(n);if(t){let o=xn[t];if(o==="transient"||o==="deterministic")return o}let r=Mn(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of On)if(o.test(e))return"transient";return"deterministic"}var Tt=2,Pn=5;function Cn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return Tt;let t=Number(e);return!Number.isFinite(t)||t<0?Tt:Math.min(Pn,Math.floor(t))}var qe=5e3,$t=3e4;function Bn(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return qe;let t=Number(e);return!Number.isFinite(t)||t<0?qe:Math.min($t,Math.floor(t))}function At(n,e=Math.random,t=qe){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min($t,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function Ye(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=Cn(e),i=Bn(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=Rn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?At(s,t,i):0,failureClass:u,index:s,of:r}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:At(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function Bt(n,e,t,r){if(!e.retry)return!1;if(r())return A.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?A.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):A.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(A.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}te.helpers.inc||te.registerHelper("inc",n=>Number(n)+1);te.helpers.json||te.registerHelper("json",n=>JSON.stringify(n,null,2));te.helpers.eq||te.registerHelper("eq",(n,e)=>n===e);var z=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 Te(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 A.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=f=>t&&typeof t.get=="function"?t.get(f):e?.[f],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){A.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let f=Ye(this.retries),p=null,y=null;for(;;){try{let h=await this.customExecute(e);if(typeof h=="object"&&h!==null&&h.success===!1)y=null,p={success:!1,error:h.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:h.raw||null};else return this.isZodSchema?(A.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(h),raw:null}):{success:!0,output:h,raw:null}}catch(h){A.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&A.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),y=h,p={success:!1,error:h.message,raw:null}}let v=y??p?.error,x=f.next(v);if(!await Bt(this.name,x,v,i))break}return p&&(p.attempts=f.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=te.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
|
|
33
33
|
|
|
34
|
-
${s}`);let l=r(),u=l.cwd||process.cwd(),S=l.sessionPath;try{if(S){let f=Xe(S,ie);if(Ct(f)){let y=JSON.parse(Pt(f,"utf-8"));y.currentNode=this.name,Ve(f,JSON.stringify(y,null,2),"utf-8")}let p=Xe(S,"..",ie);if(Ct(p))try{let y=JSON.parse(Pt(p,"utf-8"));y.currentNode=this.name,Ve(p,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(f){A.debug(`[workflow] could not update session info: ${f.message}`)}let d=qe(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let f=r().config||{},p=f.agents||{},y=this.config.agent??p[this.name]??null,v={state:r()};y&&(v.preferredAgent=y);let x={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:S,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(he(),fe))).invokeAgent);let _=await h(s,v,x),E,$;if(typeof _=="string"?(E=_,$=null):_.structured?(E=_.raw||JSON.stringify(_.structured,null,2),$=_.structured):(E=_.raw||JSON.stringify(_,null,2),$=_.extracted||null),S)try{let m=Xe(S,this.name,"raw_stream_output.txt");qn(Jn(m),{recursive:!0}),Ve(m,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(m){A.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&$){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let m=$;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),$)}catch(g){A.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:m,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(E);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),U.step("Output parsed"),{success:!0,output:m,raw:E}}return{success:!0,output:E,raw:E}}catch(f){c=f;let p=d.next(f);if(!await Bt(this.name,p,f,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};X();X();import{mkdirSync as Xn,existsSync as re,statSync as qt,readdirSync as Jt,rmSync as Qn}from"node:fs";import{spawn as Wt}from"node:child_process";import{join as V}from"node:path";import{pathToFileURL as er}from"node:url";import{AsyncLocalStorage as tr}from"node:async_hooks";import{AsyncLocalStorage as Yn}from"node:async_hooks";var ge=new Yn;function ae(){let n=ge.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 Dt(n,e){let t=ge.getStore()||ae(),r=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 ge.run(r,e)}function Ut(n,e,t){let r=ge.getStore()||ae(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return ge.run(o,t)}var Qe=new Map,et=new Map,jt=new Map;function Lt(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");Qe.set(n,e),et.set(n,"ready"),jt.set(n,{...t,cachedAt:Date.now()})}function Ft(n,e){et.set(n,"failed"),jt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Qe.delete(n)}function Gt(n){return et.get(n)==="ready"?Qe.get(n):null}function me(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function xe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ye(n,e){return xe(me(n,e),n)}function H(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function K(n,e){return e.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,r)=>{let o=()=>r(e.reason);e.addEventListener("abort",o,{once:!0}),Promise.resolve(n).then(i=>{e.removeEventListener("abort",o),t(i)},i=>{e.removeEventListener("abort",o),r(i)})})}var Oe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function nr(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var C=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 ke(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function rr(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function or(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Ht=new tr,zt=Promise.resolve();async function sr(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 r=Ht.getStore()===!0,o=null;if(!r){let s=zt;zt=new Promise(a=>{o=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 A.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Ht.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function ir(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new C("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function ar({apiBase:n,authToken:e,body:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new C(H(s)?"begin-timeout":"network",H(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(H(s))throw new C("begin-timeout",`begin body read TIMED OUT ${r.label}`)}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=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(o.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 C("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function ne({apiBase:n,authToken:e,payload:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||A.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){A.warn(`[in-process subgraph] finalize ${H(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function cr(n,e){let t=V(e,".ready"),r=V(e,"graph.mjs");if(re(t)&&re(r))return;Xn(e,{recursive:!0});let o=V(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"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(re(t)&&re(r))return;await new Promise(a=>setTimeout(a,100))}throw new C("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let S=Math.ceil(1e4/1e3),d=Math.ceil(me("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Wt("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),f=Wt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(f.stdin);let p,y,v=()=>{if(p!==void 0&&y!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};c.on("close",x=>{p=x,v()}),f.on("close",x=>{y=x,v()}),c.on("error",u),f.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new C("bundle-extract-failed",s.message)}}async function lr(n){let e=V(n,"graph.mjs");if(!re(e))throw new C("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(er(e).href)}catch(o){throw new C("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new C("entry-class-missing","no buildGraph() class export found");return r}async function Yt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ae(),r;try{r=ir()}catch(g){throw g}A.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await ar({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:S,bundleReady:d,nodeConfigs:c}=o,f=nr();if(s&&s!==f)throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new C("runtime-mismatch",`${f} vs ${s}`);if(!d||!a)throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new C("no-bundle","workflow bundle not built yet");let p=Gt(n);if(!p){let g=V(Oe,`${S}@${u||"0"}`);try{await cr(a,g);try{dr()}catch{}}catch(w){throw w.fallback&&await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{p=await lr(g),Lt(n,p,{workflowUuid:S,version:u,runtimeTag:s,cacheDir:g})}catch(w){throw Ft(n,w),await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new C("import-failed",w.message)}}let y=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,x=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...x?{nodeConfigs:c}:{}},_=rr(e.timeoutMs),E=or(e.signal,_),$,m;try{$=await sr(v,async()=>{let w=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Dt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>w.run(e.parentAgent,h,{signal:E.signal}))}),m=$&&typeof $=="object"&&"state"in $?$.state:$}catch(g){let w=E.timedOut();throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:w?"timeout":"failed",error:w?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-y}}),w?ke(n,i,_):g}finally{E.dispose()}if($&&typeof $=="object"&&$.stoppedExternally){let g=E.timedOut();if(await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"canceled",finalState:m,durationMs:Date.now()-y}}),g)throw ke(n,i,_);let w=new Error(`Sub-graph '${n}' canceled by parent abort`);throw w.code="SUBGRAPH_CANCELED",w.subgraphJobId=i,w}return await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-y}}),{finalState:m,executionId:i}}function ur(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=qt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Jt(r)}catch{continue}for(let s of i)t.push(V(r,s))}else e+=o.size}return e}function dr({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!re(Oe))return{evicted:0,freedBytes:0};let e=Jt(Oe),t=[],r=0;for(let a of e){let l=V(Oe,a),u;try{u=qt(l)}catch{continue}let S=u.isDirectory()?ur(l):u.size;r+=S,t.push({name:a,full:l,size:S,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!re(V(a.full,".lock")))try{Qn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){A.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&A.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var fr=2e3,hr=600*1e3,gr=new Set(["completed","failed","canceled","cancelled","timeout"]);var Kt=()=>ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function mr(n){let e=me("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return xe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Vt(){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 Xt(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Qt(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function en(){return process.env.EXECUTION_ID||null}function yr(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}function Zt(n,e,t,r){let o=yr(e,t);return r?{executionId:n,output:o}:o}async function tt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ae();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:hr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m,executionId:g}=await Yt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),w=Zt(g,m,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' completed in-process`),w}catch(m){if(m instanceof C||m?.fallback)A.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Vt(),s=Xt(),a=Qt(),l=en(),u=e.participantBindingId?"participant":n,S=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(u)}/trigger`,d={input:e.input||{},...l?{parentExecutionId:l}:{},...!e.async&&typeof e.output=="string"&&e.output.trim()?{resultPath:e.output.trim()}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};A.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Kt(),f;try{f=await K(fetch(S,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal}),c.signal)}catch(m){if(!H(m))throw m;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}if(!f.ok){let m=null,g="";try{m=await K(f.json(),c.signal),g=m?.error||m?.message||JSON.stringify(m)}catch{g=await K(f.text(),c.signal).catch(()=>"")}if(f.status===429){let k=m?.quotaInfo||{},M=new Error(`Sub-graph '${n}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=n,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=n,k.validationErrors=m?.validationErrors||null,k.missing=m?.missing||null,k}let w=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${g}`);throw w.code="SUBGRAPH_TRIGGER_FAILED",w.status=f.status,w.subgraph=n,w}let p;try{p=await K(f.json(),c.signal)}catch(m){if(!H(m))throw m;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}let y=p?.data?.jobId||p?.jobId;if(!y)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(p).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${y} (not waiting)`),{jobId:y,status:"accepted",workflow:n};let v=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:fr,x=`${i}/executions/${encodeURIComponent(y)}`,h=Date.now()+o,_="accepted",E=0,$=null;for(;Date.now()<h;){await new Promise(M=>setTimeout(M,v)),E+=1;let m=mr(h),g;try{g=await K(fetch(x,{headers:{Authorization:`Bearer ${a}`},signal:m.signal}),m.signal)}catch(M){$=H(M)?`poll TIMED OUT ${m.label}`:M?.message||String(M),A.warn(`[sub-graph] status poll for ${y} could not reach the API (${$}), will retry`);continue}if(!g.ok){if(g.status>=500){A.warn(`[sub-graph] status poll for ${y} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${y}: ${g.status}`)}let w;try{w=await K(g.json(),m.signal)}catch(M){$=H(M)?`poll body read TIMED OUT ${m.label}`:M?.message||String(M),A.warn(`[sub-graph] status poll for ${y} returned an unreadable body (${$}), will retry`);continue}let k=w?.data||w?.execution||w;if(_=k?.status||_,gr.has(_)){if(_!=="completed"){let I=new Error(`Sub-graph '${n}' (${y}) ended in status '${_}'`);throw I.subgraphJobId=y,I.subgraphStatus=_,I}let M=k?.finalState||k?.state||{},O=Zt(y,M,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' (${y}) completed after ${E} polls`),O}}try{let m=xe(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),g=await K(fetch(`${x}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:m.signal}),m.signal);!g.ok&&g.status!==400&&g.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${y} returned ${g.status}`)}catch(m){A.warn(`[sub-graph] best-effort cancel for ${y} failed: ${m?.message||String(m)}`)}throw ke(n,y,o,_,$)}async function tn(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return tt("participant",{...e,async:e.async!==!1,participantBindingId:n})}async function nn(n){if(!n||typeof n!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Vt(),t=Xt(),r=Qt(),o=en();if(!o){let u=new Error("Collaboration requires a running parent execution");throw u.code="PARENT_EXECUTION_REQUIRED",u}let i=`${e}/projects/${encodeURIComponent(t)}/workflows/participant/trigger`,s=Kt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:n}),signal:s.signal})}catch(u){let S=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw S.code=H(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",S.cause=u,S}let l=null;try{l=await a.json()}catch{}if(!a.ok){let u=new Error(l?.error||`Participant roster lookup rejected (${a.status})`);throw u.code=l?.code||"PARTICIPANT_ROSTER_REJECTED",u.status=a.status,u}return Array.isArray(l?.participants)?l.participants:[]}var Sr=8*6e4,wr=10*6e4,_r=2*6e4;function br(n=process.env,e=process.uptime()){let t=Number(n?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function rn(n,e,t=Number.MAX_SAFE_INTEGER){let r=Number(n);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),t):e}function Se(n,e,t={}){return{requested:!0,required:n===!0,observed:!1,status:n===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function Er(n,e,t){return{participant:n.displayName||n.id,participantId:n.id,vendor:n.vendor||null,phase:e,revision:0,contribution:t}}function on(n,e,t){return n.find(r=>Array.isArray(r.roles)&&r.roles.includes(e))||t}var Ir=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function Tr(n,e,t){let r=n;if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}if(!(r&&typeof r=="object"&&!Array.isArray(r)&&r.phase===e&&r.role===t&&r.contextRevision===0&&typeof r.summary=="string"&&Ir.every(i=>Array.isArray(r[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return r}async function sn(n={},e={}){let t=String(n.protocolId||"discuss.v1"),r=String(n.objective||"").trim(),o=String(n.context||""),i=n.required===!0,s=rn(n.timeoutMs,Sr,wr),a=rn(n.reserveMs,_r,15*6e4),l=(e.remainingWorkflowTimeMs||br)();if(!r)return Se(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return Se(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||nn,S=e.dispatchParticipant||tn,d;try{d=await u(t)}catch(I){return Se(i,I?.code||"participant_roster_unavailable",{protocolId:t,detail:I?.message||String(I)})}let c=d.filter(I=>I?.available===!1),f=d.filter(I=>I&&I.available!==!1&&I.id);if(f.length===0)return Se(i,"no_available_participants",{protocolId:t,unavailable:c});let p=Date.now(),y=p+s,v=[],x=[],h=async(I,B,F,we=[])=>{let ce=y-Date.now();if(ce<1e3){let Z=new Error("Collaboration node exhausted its authored timeout");throw Z.code="COLLABORATION_TIMEOUT",Z}let T=Number(I?.limits?.maxExecutionMinutes)*6e4,b=Number.isFinite(T)&&T>0?Math.min(ce,T):ce,D,j=null;for(let Z=0;Z<2;Z+=1){let le=Z===1?"Your previous attempt did not satisfy the JSON protocol. Return exactly one valid JSON object with every required array field and no Markdown, preface, trailing commas, or comments.":"",Be=await S(I.id,{async:!1,protocolId:t,timeoutMs:Math.min(b,Math.max(1e3,y-Date.now())),output:"contribute",input:{objective:r,protocolId:t,phase:B,role:F,contextRevision:0,sharedContext:o,priorContributions:we,...n.instruction||le?{instruction:[n.instruction,le].filter(Boolean).join(`
|
|
35
|
-
`).slice(0,4e3)}:{}}});try{
|
|
34
|
+
${s}`);let l=r(),u=l.cwd||process.cwd(),S=l.sessionPath;try{if(S){let f=et(S,ie);if(Ct(f)){let y=JSON.parse(Pt(f,"utf-8"));y.currentNode=this.name,Qe(f,JSON.stringify(y,null,2),"utf-8")}let p=et(S,"..",ie);if(Ct(p))try{let y=JSON.parse(Pt(p,"utf-8"));y.currentNode=this.name,Qe(p,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(f){A.debug(`[workflow] could not update session info: ${f.message}`)}let d=Ye(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let f=r().config||{},p=f.agents||{},y=this.config.agent??p[this.name]??null,v={state:r()};y&&(v.preferredAgent=y);let x={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:S,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(he(),fe))).invokeAgent);let _=await h(s,v,x),E,$;if(typeof _=="string"?(E=_,$=null):_.structured?(E=_.raw||JSON.stringify(_.structured,null,2),$=_.structured):(E=_.raw||JSON.stringify(_,null,2),$=_.extracted||null),S)try{let m=et(S,this.name,"raw_stream_output.txt");qn(Jn(m),{recursive:!0}),Qe(m,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(m){A.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&$){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify($,null,2)}`);let m=$;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),$)}catch(g){A.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:m,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(E);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),C.step("Output parsed"),{success:!0,output:m,raw:E}}return{success:!0,output:E,raw:E}}catch(f){c=f;let p=d.next(f);if(!await Bt(this.name,p,f,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};X();X();import{mkdirSync as Xn,existsSync as re,statSync as qt,readdirSync as Jt,rmSync as Qn}from"node:fs";import{spawn as Wt}from"node:child_process";import{join as V}from"node:path";import{pathToFileURL as er}from"node:url";import{AsyncLocalStorage as tr}from"node:async_hooks";import{AsyncLocalStorage as Yn}from"node:async_hooks";var ge=new Yn;function ae(){let n=ge.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 Dt(n,e){let t=ge.getStore()||ae(),r=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 ge.run(r,e)}function Ut(n,e,t){let r=ge.getStore()||ae(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return ge.run(o,t)}var tt=new Map,nt=new Map,jt=new Map;function Lt(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");tt.set(n,e),nt.set(n,"ready"),jt.set(n,{...t,cachedAt:Date.now()})}function Ft(n,e){nt.set(n,"failed"),jt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),tt.delete(n)}function Gt(n){return nt.get(n)==="ready"?tt.get(n):null}function me(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function xe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ye(n,e){return xe(me(n,e),n)}function H(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function K(n,e){return e.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,r)=>{let o=()=>r(e.reason);e.addEventListener("abort",o,{once:!0}),Promise.resolve(n).then(i=>{e.removeEventListener("abort",o),t(i)},i=>{e.removeEventListener("abort",o),r(i)})})}var Oe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function nr(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var B=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 ke(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function rr(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function or(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Ht=new tr,zt=Promise.resolve();async function sr(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 r=Ht.getStore()===!0,o=null;if(!r){let s=zt;zt=new Promise(a=>{o=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 A.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Ht.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function ir(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new B("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function ar({apiBase:n,authToken:e,body:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new B(H(s)?"begin-timeout":"network",H(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(H(s))throw new B("begin-timeout",`begin body read TIMED OUT ${r.label}`)}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=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(o.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 B("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function ne({apiBase:n,authToken:e,payload:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||A.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){A.warn(`[in-process subgraph] finalize ${H(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function cr(n,e){let t=V(e,".ready"),r=V(e,"graph.mjs");if(re(t)&&re(r))return;Xn(e,{recursive:!0});let o=V(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"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(re(t)&&re(r))return;await new Promise(a=>setTimeout(a,100))}throw new B("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let S=Math.ceil(1e4/1e3),d=Math.ceil(me("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Wt("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),f=Wt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(f.stdin);let p,y,v=()=>{if(p!==void 0&&y!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};c.on("close",x=>{p=x,v()}),f.on("close",x=>{y=x,v()}),c.on("error",u),f.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new B("bundle-extract-failed",s.message)}}async function lr(n){let e=V(n,"graph.mjs");if(!re(e))throw new B("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(er(e).href)}catch(o){throw new B("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new B("entry-class-missing","no buildGraph() class export found");return r}async function Yt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ae(),r;try{r=ir()}catch(g){throw g}A.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await ar({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:S,bundleReady:d,nodeConfigs:c}=o,f=nr();if(s&&s!==f)throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("runtime-mismatch",`${f} vs ${s}`);if(!d||!a)throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("no-bundle","workflow bundle not built yet");let p=Gt(n);if(!p){let g=V(Oe,`${S}@${u||"0"}`);try{await cr(a,g);try{dr()}catch{}}catch(w){throw w.fallback&&await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{p=await lr(g),Lt(n,p,{workflowUuid:S,version:u,runtimeTag:s,cacheDir:g})}catch(w){throw Ft(n,w),await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new B("import-failed",w.message)}}let y=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,x=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...x?{nodeConfigs:c}:{}},_=rr(e.timeoutMs),E=or(e.signal,_),$,m;try{$=await sr(v,async()=>{let w=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Dt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>w.run(e.parentAgent,h,{signal:E.signal}))}),m=$&&typeof $=="object"&&"state"in $?$.state:$}catch(g){let w=E.timedOut();throw await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:w?"timeout":"failed",error:w?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-y}}),w?ke(n,i,_):g}finally{E.dispose()}if($&&typeof $=="object"&&$.stoppedExternally){let g=E.timedOut();if(await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"canceled",finalState:m,durationMs:Date.now()-y}}),g)throw ke(n,i,_);let w=new Error(`Sub-graph '${n}' canceled by parent abort`);throw w.code="SUBGRAPH_CANCELED",w.subgraphJobId=i,w}return await ne({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-y}}),{finalState:m,executionId:i}}function ur(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=qt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Jt(r)}catch{continue}for(let s of i)t.push(V(r,s))}else e+=o.size}return e}function dr({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!re(Oe))return{evicted:0,freedBytes:0};let e=Jt(Oe),t=[],r=0;for(let a of e){let l=V(Oe,a),u;try{u=qt(l)}catch{continue}let S=u.isDirectory()?ur(l):u.size;r+=S,t.push({name:a,full:l,size:S,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!re(V(a.full,".lock")))try{Qn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){A.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&A.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var fr=2e3,hr=600*1e3,gr=new Set(["completed","failed","canceled","cancelled","timeout"]);var Kt=()=>ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function mr(n){let e=me("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return xe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Vt(){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 Xt(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Qt(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function en(){return process.env.EXECUTION_ID||null}function yr(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}function Zt(n,e,t,r){let o=yr(e,t);return r?{executionId:n,output:o}:o}async function rt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ae();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:hr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m,executionId:g}=await Yt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),w=Zt(g,m,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' completed in-process`),w}catch(m){if(m instanceof B||m?.fallback)A.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Vt(),s=Xt(),a=Qt(),l=en(),u=e.participantBindingId?"participant":n,S=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(u)}/trigger`,d={input:e.input||{},...l?{parentExecutionId:l}:{},...!e.async&&typeof e.output=="string"&&e.output.trim()?{resultPath:e.output.trim()}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};A.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Kt(),f;try{f=await K(fetch(S,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal}),c.signal)}catch(m){if(!H(m))throw m;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}if(!f.ok){let m=null,g="";try{m=await K(f.json(),c.signal),g=m?.error||m?.message||JSON.stringify(m)}catch{g=await K(f.text(),c.signal).catch(()=>"")}if(f.status===429){let k=m?.quotaInfo||{},N=new Error(`Sub-graph '${n}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw N.code="SUBGRAPH_QUOTA_EXCEEDED",N.status=429,N.subgraph=n,N.quotaInfo=k,N}if(f.status===400){let k=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=n,k.validationErrors=m?.validationErrors||null,k.missing=m?.missing||null,k}let w=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${g}`);throw w.code="SUBGRAPH_TRIGGER_FAILED",w.status=f.status,w.subgraph=n,w}let p;try{p=await K(f.json(),c.signal)}catch(m){if(!H(m))throw m;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}let y=p?.data?.jobId||p?.jobId;if(!y)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(p).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${y} (not waiting)`),{jobId:y,status:"accepted",workflow:n};let v=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:fr,x=`${i}/executions/${encodeURIComponent(y)}`,h=Date.now()+o,_="accepted",E=0,$=null;for(;Date.now()<h;){await new Promise(N=>setTimeout(N,v)),E+=1;let m=mr(h),g;try{g=await K(fetch(x,{headers:{Authorization:`Bearer ${a}`},signal:m.signal}),m.signal)}catch(N){$=H(N)?`poll TIMED OUT ${m.label}`:N?.message||String(N),A.warn(`[sub-graph] status poll for ${y} could not reach the API (${$}), will retry`);continue}if(!g.ok){if(g.status>=500){A.warn(`[sub-graph] status poll for ${y} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${y}: ${g.status}`)}let w;try{w=await K(g.json(),m.signal)}catch(N){$=H(N)?`poll body read TIMED OUT ${m.label}`:N?.message||String(N),A.warn(`[sub-graph] status poll for ${y} returned an unreadable body (${$}), will retry`);continue}let k=w?.data||w?.execution||w;if(_=k?.status||_,gr.has(_)){if(_!=="completed"){let I=new Error(`Sub-graph '${n}' (${y}) ended in status '${_}'`);throw I.subgraphJobId=y,I.subgraphStatus=_,I}let N=k?.finalState||k?.state||{},O=Zt(y,N,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' (${y}) completed after ${E} polls`),O}}try{let m=xe(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),g=await K(fetch(`${x}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:m.signal}),m.signal);!g.ok&&g.status!==400&&g.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${y} returned ${g.status}`)}catch(m){A.warn(`[sub-graph] best-effort cancel for ${y} failed: ${m?.message||String(m)}`)}throw ke(n,y,o,_,$)}async function tn(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return rt("participant",{...e,async:e.async!==!1,participantBindingId:n})}async function nn(n){if(!n||typeof n!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Vt(),t=Xt(),r=Qt(),o=en();if(!o){let u=new Error("Collaboration requires a running parent execution");throw u.code="PARENT_EXECUTION_REQUIRED",u}let i=`${e}/projects/${encodeURIComponent(t)}/workflows/participant/trigger`,s=Kt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:n}),signal:s.signal})}catch(u){let S=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw S.code=H(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",S.cause=u,S}let l=null;try{l=await a.json()}catch{}if(!a.ok){let u=new Error(l?.error||`Participant roster lookup rejected (${a.status})`);throw u.code=l?.code||"PARTICIPANT_ROSTER_REJECTED",u.status=a.status,u}return Array.isArray(l?.participants)?l.participants:[]}var Sr=8*6e4,wr=10*6e4,_r=2*6e4;function br(n=process.env,e=process.uptime()){let t=Number(n?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function rn(n,e,t=Number.MAX_SAFE_INTEGER){let r=Number(n);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),t):e}function Se(n,e,t={}){return{requested:!0,required:n===!0,observed:!1,status:n===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function Er(n,e,t){return{participant:n.displayName||n.id,participantId:n.id,vendor:n.vendor||null,phase:e,revision:0,contribution:t}}function on(n,e,t){return n.find(r=>Array.isArray(r.roles)&&r.roles.includes(e))||t}var Ir=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function Tr(n,e,t){let r=n;if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}if(!(r&&typeof r=="object"&&!Array.isArray(r)&&r.phase===e&&r.role===t&&r.contextRevision===0&&typeof r.summary=="string"&&Ir.every(i=>Array.isArray(r[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return r}async function sn(n={},e={}){let t=String(n.protocolId||"discuss.v1"),r=String(n.objective||"").trim(),o=String(n.context||""),i=n.required===!0,s=rn(n.timeoutMs,Sr,wr),a=rn(n.reserveMs,_r,15*6e4),l=(e.remainingWorkflowTimeMs||br)();if(!r)return Se(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return Se(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||nn,S=e.dispatchParticipant||tn,d;try{d=await u(t)}catch(I){return Se(i,I?.code||"participant_roster_unavailable",{protocolId:t,detail:I?.message||String(I)})}let c=d.filter(I=>I?.available===!1),f=d.filter(I=>I&&I.available!==!1&&I.id);if(f.length===0)return Se(i,"no_available_participants",{protocolId:t,unavailable:c});let p=Date.now(),y=p+s,v=[],x=[],h=async(I,D,G,we=[])=>{let ce=y-Date.now();if(ce<1e3){let Z=new Error("Collaboration node exhausted its authored timeout");throw Z.code="COLLABORATION_TIMEOUT",Z}let T=Number(I?.limits?.maxExecutionMinutes)*6e4,b=Number.isFinite(T)&&T>0?Math.min(ce,T):ce,U,j=null;for(let Z=0;Z<2;Z+=1){let le=Z===1?"Your previous attempt did not satisfy the JSON protocol. Return exactly one valid JSON object with every required array field and no Markdown, preface, trailing commas, or comments.":"",Be=await S(I.id,{async:!1,protocolId:t,timeoutMs:Math.min(b,Math.max(1e3,y-Date.now())),output:"contribute",input:{objective:r,protocolId:t,phase:D,role:G,contextRevision:0,sharedContext:o,priorContributions:we,...n.instruction||le?{instruction:[n.instruction,le].filter(Boolean).join(`
|
|
35
|
+
`).slice(0,4e3)}:{}}});try{U=Tr(Be,D,G),j=null;break}catch(_e){j=_e}}if(j)throw j;let Y=Er(I,D,U);return v.push(Y),Y},_=on(f,"draft",f[0]),E;try{E=await h(_,"draft","drafter")}catch(I){x.push({participantId:_.id,phase:"draft",code:I?.code||"PARTICIPANT_FAILED",detail:I?.message||String(I)});let D=Se(i,"draft_failed",{protocolId:t,unavailable:c,failures:x,durationMs:Date.now()-p});return i&&(D.status="incomplete"),D}let $=f.filter(I=>I.id!==_.id);$.length===0&&($=[_]);let m=await Promise.allSettled($.map(I=>h(I,"critique","critic",[E]))),g=[];m.forEach((I,D)=>{I.status==="fulfilled"?g.push(I.value):x.push({participantId:$[D].id,phase:"critique",code:I.reason?.code||"PARTICIPANT_FAILED",detail:I.reason?.message||String(I.reason)})});let w=on(f,"synthesize",_),k=null;try{k=await h(w,"synthesize","synthesizer",[E,...g])}catch(I){x.push({participantId:w.id,phase:"synthesize",code:I?.code||"PARTICIPANT_FAILED",detail:I?.message||String(I)})}let N=g.length>0&&k!=null,O=(k?.contribution?.decisions||[]).filter(I=>I?.status==="unresolved");return{requested:!0,required:i,observed:N,status:N?"completed":"incomplete",reason:N?null:"required_phase_incomplete",protocolId:t,contributions:v,synthesis:k?.contribution||null,disagreements:O,failures:x,unavailable:c,durationMs:Date.now()-p}}import{existsSync as an,readFileSync as Ar}from"node:fs";import{join as ot,dirname as cn}from"node:path";var Me=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=cn(ot(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let S=l.replace(/\.[^.]+$/,"").toLowerCase();o[S]=u}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let u=ot(t,l);an(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=ot(i,e);if(an(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=cn(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=Ar(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as dn,existsSync as
|
|
39
|
+
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=Ar(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as dn,existsSync as st,writeFileSync as ln,unlinkSync as vr}from"node:fs";import{join as oe,resolve as pn}from"node:path";import{config as $r}from"dotenv";import{zodToJsonSchema as un}from"zod-to-json-schema";import{z as Re}from"zod";import xr from"handlebars";function Or({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){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=${r} mkdir=${o?"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(`
|
|
40
40
|
`).slice(2,14).join(`
|
|
41
41
|
`);console.log(`[zibby:session] stack (${n}):
|
|
42
|
-
${S}`)}}function kr(){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 Mr(){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 pn(String(e).trim())}catch{return String(e).trim()}}function Nr(){kr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Rr({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 Pr(n={}){let e=It.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function Cr({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=pn(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=Pr(e),s="generated")}i=i??Date.now();let S=e.paths?.output||ve;o=oe(n,S,bt,a)}let l=!rt(o);return l&&dn(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&Or({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),Rr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Pe=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof z)&&t&&typeof t=="object"&&t.collaboration){let s=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:s.protocolId||"discuss.v1",required:s.required===!0,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(f,p="")=>typeof f=="function"?f(S):f??p,c=await sn({protocolId:s.protocolId,required:s.required,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs,objective:d(s.objective),context:d(s.context),instruction:d(s.instruction)});if(s.required===!0&&c.status!=="completed"){let f=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw f.code="COLLABORATION_REQUIRED_INCOMPLETE",f.collaborationResult=c,f}return c}},l=new z(a);return l.name=e,this.nodes.set(e,l),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}if(!(t instanceof z)&&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 u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(S):s.input&&typeof s.input=="object"?d=s.input:d={},tt(s.workflow,{input:d,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:u?.agent})}},l=new z(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof z)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof z?t:new z(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_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,r=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&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let f=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:f,data:{nodeType:f,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(p.description=y);let v=c?.config?.collaboration;v&&typeof v=="object"&&(p.collaboration={protocolId:v.protocolId||"discuss.v1",required:v.required===!0,...Number.isFinite(v.timeoutMs)?{timeoutMs:v.timeoutMs}:{},...Number.isFinite(v.reserveMs)?{reserveMs:v.reserveMs}:{}});let x=c?.config?.collaborationAsync;x&&typeof x=="object"&&(p.collaborationAsync={protocolId:x.protocolId||"discuss.v1"});let h=this.nodePrompts.get(d);if(h)p.prompt=h;else if(typeof c.prompt=="function")try{let O=c.prompt({});typeof O=="string"&&O.trim()&&(p.prompt=O,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 O=[...new Set(_.filter(I=>typeof I=="string").map(I=>I.trim()).filter(Boolean))];O.length&&(p.dispatchesWorkflow=O)}let E=c?.config?.minimumReadyChildren;if(E!=null){if(!Number.isInteger(E)||E<=0)throw new Error(`Node '${d}' minimumReadyChildren must be a positive integer`);let O=typeof p.dispatchesWorkflow=="string"?1:Array.isArray(p.dispatchesWorkflow)?p.dispatchesWorkflow.length:0;if(E>O)throw new Error(`Node '${d}' minimumReadyChildren (${E}) exceeds its declared dispatch roster (${O})`);p.minimumReadyChildren=E}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 O=null;if(typeof Re?.toJSONSchema=="function")try{O=Re.toJSONSchema(c.outputSchema)}catch{}if(!O)try{O=un(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=O?{jsonSchema:O,variables:this._flattenJsonSchemaToVariables(O)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(p.tools=$.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(p.skills=[...m]);let g=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;g&&g.length>0&&(p.optionalSkills=[...g]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(p.plugins=w.map(O=>O&&typeof O=="object"?{...O}:O));let k=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;k&&k.length>0&&(p.stores=k.map(O=>O&&typeof O=="object"?{...O}:O));let M=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(M&&M.length>0){let O=new Set,I=[];for(let B of M){let F=typeof B=="string"?B.trim():"";!F||O.has(F)||(O.add(F),I.push(F))}I.length>0&&(p.uses=I)}Object.keys(p).length>0&&(t[d]=p)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(Array.isArray(c))for(let f of c)r.push({source:d,target:f});else if(c.conditional){let f=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},v=this.nodes.get(d),x=v?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!v,h=d;if(!x){let _=`${d}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),r.push({source:d,target:_}),h=_}for(let _ of p){let E={source:h,target:_,data:{conditionalCode:f}};y[_]&&(E.label=y[_]),r.push(E)}}let o=d=>{if(!d)return null;if(typeof Re?.toJSONSchema=="function")try{return Re.toJSONSchema(d)}catch{}try{return un(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of r)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),S=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:S}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>i.get(d)===0),S=[];for(;S.length<e.length;){let d;if(u.length>0){if(u.sort((c,f)=>r.get(c)-r.get(f)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,f)=>r.get(c)-r.get(f))[0];a.add(d),l.delete(d),S.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return S}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=u.exec(r))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(T){let b=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw b.cause=T,b.code=T?.code||"NORMALIZE_INPUT_FAILED",b}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();$r({path:oe(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=oe(s,".zibby.config.js");rt(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let T=S.safeParse(t);if(!T.success){let b=T.error.issues.map(D=>`${D.path.join(".")}: ${D.message}`);throw console.error("\u274C Initial state validation failed:"),b.forEach(D=>console.error(` - ${D}`)),new Error(`State validation failed: ${b.join(", ")}`)}U.step("State validated against schema")}let d=Mr(),c=t.sessionPath||d;c||Nr();let{sessionPath:f,sessionTimestamp:p,sessionId:y}=Cr({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});U.step(`Session ${y}`);let v=await Ne.loadContext(t.specPath||"",s,u);Object.keys(v).length>0&&U.step(`Context loaded: ${Object.keys(v).join(", ")}`);let x=t.outputPath;!x&&t.specPath&&(e?.calculateOutputPath?x=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new Ie({...t,config:a,agentType:l,outputPath:x,sessionPath:f,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>($e(),Ot)),$=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values($).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),g=T=>{for(let b of m)if(b.id===T)return b;return E(T)},w=new Set;for(let[,T]of this.nodes)for(let b of T.config?.skills||[])w.add(b);for(let T of w){let b=g(T);if(typeof b?.middleware=="function")try{let D=await b.middleware();typeof D=="function"&&_.set(T,D)}catch{}}let{backEdges:k,joinDegree:M}=this._analyzeFlow(),O=new Map,I=[],B=(T,b,D)=>{if(!T||T==="END")return;let j=M.get(T)||0;if(D&&j>1&&!k.has(`${b}->${T}`)){let Y=(O.get(T)||0)+1;if(Y<j){O.set(T,Y);return}O.set(T,0)}I.includes(T)||I.push(T)};this.entryPoint&&I.push(this.entryPoint);let F=[],we=a?.recursionLimit??100,ce=0;try{for(;I.length>0;){let b=I.pop();if(!b||b==="END")continue;if(++ce>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 D=oe(f,Et);if(rt(D)){try{vr(D)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
43
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
42
|
+
${S}`)}}function kr(){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 Nr(){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 pn(String(e).trim())}catch{return String(e).trim()}}function Mr(){kr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Rr({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 Pr(n={}){let e=It.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function Cr({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=pn(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=Pr(e),s="generated")}i=i??Date.now();let S=e.paths?.output||ve;o=oe(n,S,bt,a)}let l=!st(o);return l&&dn(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&Or({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),Rr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Pe=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof z)&&t&&typeof t=="object"&&t.collaboration){let s=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:s.protocolId||"discuss.v1",required:s.required===!0,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(f,p="")=>typeof f=="function"?f(S):f??p,c=await sn({protocolId:s.protocolId,required:s.required,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs,objective:d(s.objective),context:d(s.context),instruction:d(s.instruction)});if(s.required===!0&&c.status!=="completed"){let f=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw f.code="COLLABORATION_REQUIRED_INCOMPLETE",f.collaborationResult=c,f}return c}},l=new z(a);return l.name=e,this.nodes.set(e,l),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}if(!(t instanceof z)&&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 u=>{let S=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(S):s.input&&typeof s.input=="object"?d=s.input:d={},rt(s.workflow,{input:d,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:u?.agent})}},l=new z(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof z)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof z?t:new z(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_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,r=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&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let f=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:f,data:{nodeType:f,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(p.description=y);let v=c?.config?.collaboration;v&&typeof v=="object"&&(p.collaboration={protocolId:v.protocolId||"discuss.v1",required:v.required===!0,...Number.isFinite(v.timeoutMs)?{timeoutMs:v.timeoutMs}:{},...Number.isFinite(v.reserveMs)?{reserveMs:v.reserveMs}:{}});let x=c?.config?.collaborationAsync;x&&typeof x=="object"&&(p.collaborationAsync={protocolId:x.protocolId||"discuss.v1"});let h=this.nodePrompts.get(d);if(h)p.prompt=h;else if(typeof c.prompt=="function")try{let O=c.prompt({});typeof O=="string"&&O.trim()&&(p.prompt=O,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 O=[...new Set(_.filter(I=>typeof I=="string").map(I=>I.trim()).filter(Boolean))];O.length&&(p.dispatchesWorkflow=O)}let E=c?.config?.minimumReadyChildren;if(E!=null){if(!Number.isInteger(E)||E<=0)throw new Error(`Node '${d}' minimumReadyChildren must be a positive integer`);let O=typeof p.dispatchesWorkflow=="string"?1:Array.isArray(p.dispatchesWorkflow)?p.dispatchesWorkflow.length:0;if(E>O)throw new Error(`Node '${d}' minimumReadyChildren (${E}) exceeds its declared dispatch roster (${O})`);p.minimumReadyChildren=E}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 O=null;if(typeof Re?.toJSONSchema=="function")try{O=Re.toJSONSchema(c.outputSchema)}catch{}if(!O)try{O=un(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=O?{jsonSchema:O,variables:this._flattenJsonSchemaToVariables(O)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(p.tools=$.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(p.skills=[...m]);let g=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;g&&g.length>0&&(p.optionalSkills=[...g]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(p.plugins=w.map(O=>O&&typeof O=="object"?{...O}:O));let k=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;k&&k.length>0&&(p.stores=k.map(O=>O&&typeof O=="object"?{...O}:O));let N=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(N&&N.length>0){let O=new Set,I=[];for(let D of N){let G=typeof D=="string"?D.trim():"";!G||O.has(G)||(O.add(G),I.push(G))}I.length>0&&(p.uses=I)}Object.keys(p).length>0&&(t[d]=p)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(Array.isArray(c))for(let f of c)r.push({source:d,target:f});else if(c.conditional){let f=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},v=this.nodes.get(d),x=v?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!v,h=d;if(!x){let _=`${d}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),r.push({source:d,target:_}),h=_}for(let _ of p){let E={source:h,target:_,data:{conditionalCode:f}};y[_]&&(E.label=y[_]),r.push(E)}}let o=d=>{if(!d)return null;if(typeof Re?.toJSONSchema=="function")try{return Re.toJSONSchema(d)}catch{}try{return un(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of r)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),S=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:S}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>i.get(d)===0),S=[];for(;S.length<e.length;){let d;if(u.length>0){if(u.sort((c,f)=>r.get(c)-r.get(f)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,f)=>r.get(c)-r.get(f))[0];a.add(d),l.delete(d),S.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return S}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,S;for(;(S=u.exec(r))!==null;)l.add(S[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(T){let b=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw b.cause=T,b.code=T?.code||"NORMALIZE_INPUT_FAILED",b}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();$r({path:oe(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=oe(s,".zibby.config.js");st(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},S=this._runtimeSchema();if(S){let T=S.safeParse(t);if(!T.success){let b=T.error.issues.map(U=>`${U.path.join(".")}: ${U.message}`);throw console.error("\u274C Initial state validation failed:"),b.forEach(U=>console.error(` - ${U}`)),new Error(`State validation failed: ${b.join(", ")}`)}C.step("State validated against schema")}let d=Nr(),c=t.sessionPath||d;c||Mr();let{sessionPath:f,sessionTimestamp:p,sessionId:y}=Cr({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});C.step(`Session ${y}`);let v=await Me.loadContext(t.specPath||"",s,u);Object.keys(v).length>0&&C.step(`Context loaded: ${Object.keys(v).join(", ")}`);let x=t.outputPath;!x&&t.specPath&&(e?.calculateOutputPath?x=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new Ie({...t,config:a,agentType:l,outputPath:x,sessionPath:f,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>($e(),Ot)),$=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values($).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),g=T=>{for(let b of m)if(b.id===T)return b;return E(T)},w=new Set;for(let[,T]of this.nodes)for(let b of T.config?.skills||[])w.add(b);for(let T of w){let b=g(T);if(typeof b?.middleware=="function")try{let U=await b.middleware();typeof U=="function"&&_.set(T,U)}catch{}}let{backEdges:k,joinDegree:N}=this._analyzeFlow(),O=new Map,I=[],D=(T,b,U)=>{if(!T||T==="END")return;let j=N.get(T)||0;if(U&&j>1&&!k.has(`${b}->${T}`)){let Y=(O.get(T)||0)+1;if(Y<j){O.set(T,Y);return}O.set(T,0)}I.includes(T)||I.push(T)};this.entryPoint&&I.push(this.entryPoint);let G=[],we=a?.recursionLimit??100,ce=0;try{for(;I.length>0;){let b=I.pop();if(!b||b==="END")continue;if(++ce>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 U=oe(f,Et);if(st(U)){try{vr(U)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
43
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),C.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:G,stoppedExternally:!0};let j=this.nodes.get(b);if(!j)throw new Error(`Node '${b}' not found in graph`);let Y=JSON.stringify({sessionPath:f,sessionTimestamp:p,currentNode:b,createdAt:new Date().toISOString(),config:h.get("config")}),Z=oe(f,ie);ln(Z,Y,"utf-8");let le=h.get("config")?.paths?.output||ve,Be=oe(s,le,ie);dn(oe(s,le),{recursive:!0});try{ln(Be,Y,"utf-8")}catch{}let _e=t.onPipelineProgress;if(typeof _e=="function")try{_e({cwd:s,sessionPath:f,sessionId:y,outputBase:h.get("config")?.paths?.output||ve,currentNode:b})}catch{}let yn=(this.resolvedToolsMap||{})[b]||null;h.set("_currentNodeTools",yn);let Sn=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Sn[b]||{}),C.nodeStart(b);let lt=Date.now(),be=this.nodePrompts.get(b);if(!this._invokeAgent){let P=await Promise.resolve().then(()=>(he(),fe));this._invokeAgent=P.invokeAgent}let wn=this._invokeAgent,De={},_n=j.config?.skills||[];for(let P of _n){let L=g(P);if(typeof L?.invokeAgentOptions=="function")try{let M=L.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:b});M&&typeof M=="object"&&(De={...De,...M})}catch(M){console.warn(`[graph] skill '${P}' invokeAgentOptions threw: ${M.message}`)}}let ut=async(P,L,M={})=>{let F=wn(P,L,{...De,...M,signal:o.signal});return F.catch(()=>{}),o.signal.aborted?F:Promise.race([F,new Promise((se,J)=>{let W=()=>{setTimeout(()=>{let ft=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);ft.name="AbortError",J(ft)},i)};o.signal.addEventListener("abort",W,{once:!0})})])},bn=async(P={},L={})=>{let M=L.prompt||"";if(be){let F=this._compiledPrompts.get(b);F||(F=xr.compile(be,{noEscape:!0}),this._compiledPrompts.set(b,F));try{M=F(P)}catch(se){throw console.error(`\u274C Template rendering failed for node '${b}':`,se.message),new Error(`Template rendering failed: ${se.message}`,{cause:se})}}else if(!M)throw new Error(`No prompt template configured for node '${b}' and no prompt provided in options`);return ut(M,{state:h.getAll(),images:L.images||[]},{model:L.model||h.get("model"),workspace:h.get("workspace"),schema:L.schema,...L,signal:o.signal,nodeName:b})},dt=h.getAll(),En=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let P of En)Object.prototype.hasOwnProperty.call(dt,P)&&console.warn(`[workflow] node "${b}": state key "${P}" is shadowed by the engine context prop; read it via context.state.get('${P}')`);let pt={...dt,state:h,invokeAgent:bn,_coreInvokeAgent:ut,agent:e,nodeId:b,promptTemplate:be,getPromptTemplate:()=>be};try{let P=(j.config?.skills||[]).map(W=>_.get(W)).filter(Boolean),L=[...this.middleware,...P],M;M=await Ut(e,o.signal,async()=>L.length>0?this._composeMiddleware(L,b,async()=>j.execute(pt,h),h.getAll(),h):j.execute(pt,h));let F=Date.now()-lt;if(G.push({node:b,success:M.success,duration:F,timestamp:new Date().toISOString()}),!M.success){if(o.signal.aborted)return C.nodeStopped(b,{duration:F}),C.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:G,stoppedExternally:!0};h.append("errors",{node:b,error:M.error});let W=Number.isInteger(M.attempts)&&M.attempts>0?M.attempts:(j.config?.retries||0)+1;throw C.nodeFailed(b,M.error,{duration:F}),new Error(`Node '${b}' failed after ${W} attempt(s): ${M.error}`)}h.update({[b]:M.output});let se=this._summarizeNodeOutput(b,M.output);C.nodeComplete(b,{duration:F,details:se});let J=this.edges.get(b);if(J)if(J.conditional){let W=J.routes(h.getAll());C.route(b,W),D(W,b,!1)}else if(Array.isArray(J))for(let W=J.length-1;W>=0;W--)D(J[W],b,!0);else D(J,b,!0)}catch(P){throw C.isInsideNode&&C.nodeFailed(b,P.message,{duration:Date.now()-lt}),h.set("failed",!0),h.set("failedAt",b),P}}C.graphComplete();let T={success:!0,state:h.getAll(),executionLog:G};return e&&typeof e.onComplete=="function"&&await e.onComplete(T),T}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(T){console.warn(`[workflow] agent.cleanup() failed: ${T.message}`)}}}};var it=Symbol.for("@zibby/agent-workflow.nodes");globalThis[it]||(globalThis[it]=new Map);var at=globalThis[it];function Br(n,e){at.set(n,e)}function fn(n){return at.get(n)}function ct(n){return at.has(n)}Br("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(he(),fe))).invokeAgent);let o=e.extraPromptInstructions||"Execute the task based on the current state.",i=Dr(o,t),s=await r(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 Dr(n,e){let t=/@([\w.]+)/g,r=new Set,o;for(;(o=t.exec(n))!==null;)r.add(o[1]);if(r.size===0)return n;let i=[],s=new Set;for(let a of r){let l=a.split(".")[0];if(s.has(l))continue;let u=a.split(".").reduce((c,f)=>c?.[f],e);if(u===void 0)continue;let S=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
|
|
44
44
|
${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
|
|
45
45
|
|
|
46
46
|
---
|
|
@@ -48,4 +48,4 @@ ${S}`),a.includes(".")||s.add(l)}return i.length===0?n:`${n}
|
|
|
48
48
|
|
|
49
49
|
${i.join(`
|
|
50
50
|
|
|
51
|
-
`)}`}$e();X();var Ur={};function gn(n,e){if(Array.isArray(e))return hn(e);let t=Ur[n];return!t||t.length===0?null:hn(t)}function hn(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let o of n){let i=pe(o);if(!i){A.warn(`[workflow] unknown skill "${o}" \u2014 skipping`);continue}r.push(o);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:o})}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:o}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}X();function ns(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n;if(!Array.isArray(t)||t.length===0)throw new q("Graph must have at least one node");if(!Array.isArray(r))throw new q("Graph edges must be an array");let i=new Pe(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let f=Ce(c);a.set(c.id,{...c,resolvedType:f}),f==="decision"&&s.add(c.id)}for(let[c,f]of a){if(s.has(c))continue;let p=f.resolvedType,y=o[c]||{},v=gn(p,y.tools);v&&(l[c]=v);let x={};y.prompt&&(x.prompt=y.prompt);let h=
|
|
51
|
+
`)}`}$e();X();var Ur={};function gn(n,e){if(Array.isArray(e))return hn(e);let t=Ur[n];return!t||t.length===0?null:hn(t)}function hn(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let o of n){let i=pe(o);if(!i){A.warn(`[workflow] unknown skill "${o}" \u2014 skipping`);continue}r.push(o);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:o})}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:o}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}X();function ns(n,e={}){let{nodes:t,edges:r,nodeConfigs:o={}}=n;if(!Array.isArray(t)||t.length===0)throw new q("Graph must have at least one node");if(!Array.isArray(r))throw new q("Graph edges must be an array");let i=new Pe(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,l={};for(let c of t){let f=Ce(c);a.set(c.id,{...c,resolvedType:f}),f==="decision"&&s.add(c.id)}for(let[c,f]of a){if(s.has(c))continue;let p=f.resolvedType,y=o[c]||{},v=gn(p,y.tools);v&&(l[c]=v);let x={};y.prompt&&(x.prompt=y.prompt);let h=ct(p);if(A.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${h}`),y.customCode&&!h)i.addNode(c,mn(c,y.customCode,y),x),i.setNodeType(c,p);else if(h){let _=fn(p);_.factory?i.addNode(c,_.create(c,{...y,resolvedTools:v}),x):i.addNode(c,_,x),i.setNodeType(c,p)}else if(y.executeCode)i.addNode(c,mn(c,y.executeCode,y),x),i.setNodeType(c,p);else throw new q(`Unknown node type "${p}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of r)s.has(c.target)||u.add(c.target);let S=t.find(c=>!s.has(c.id)&&!u.has(c.id));if(!S)throw new q("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(S.id);let d=jr(r,"source");for(let c of r)if(!s.has(c.source))if(s.has(c.target)){let f=c.target,p=d.get(f)||[];if(p.length===0)throw new q(`Decision node "${f}" has no outgoing edges`);let y=Lr(f,p,s);i.addConditionalEdges(c.source,y)}else i.addEdge(c.source,c.target);return i}function rs(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=Ce(a);if(l==="decision"||ct(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let o=new Set(n.nodes.filter(a=>Ce(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)o.has(a.target)||i.add(a.target);let s=n.nodes.filter(a=>!o.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 o){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 os(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>Ce(e)!=="decision").map(e=>e.id)}function Ce(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function jr(n,e){let t=new Map;for(let r of n){let o=r[e];t.has(o)||t.set(o,[]),t.get(o).push(r)}return t}function Lr(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new q(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let o=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),s;try{let l=new Function(`return (${o})`)();s=u=>{let S=l(u);return i.has(S)||A.warn(`[workflow] conditional route from "${n}" returned "${S}" which is not in valid targets: ${[...i].join(", ")}`),S}}catch(a){throw new q(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return s}function mn(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new q(`Failed to compile customCode for node "${n}": ${s.message}`)}let o=r(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(he(),fe));return a(...s)},typeof Ue<"u"?Ue: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 o(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 q=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{q as CompilationError,ns as compileGraph,os as extractSteps,rs as validateGraphConfig};
|