@zibby/agent-workflow 2.0.13 → 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/README.md +14 -0
- package/dist/collaboration.js +2 -2
- package/dist/graph-compiler.js +20 -20
- package/dist/graph.js +19 -19
- package/dist/index.js +28 -28
- package/dist/node.js +16 -16
- package/dist/sub-graph-executor.d.ts +7 -1
- package/dist/sub-graph-executor.js +1 -1
- package/dist/timeline.d.ts +9 -0
- package/dist/timeline.js +10 -10
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
var pr=Object.defineProperty;var Se=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var
|
|
1
|
+
var pr=Object.defineProperty;var Se=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var at=(r,e)=>{for(var t in e)pr(r,t,{get:e[t],enumerable:!0})};var ct,hr,Pe,be,A,ce=Se(()=>{ct=()=>{},hr={debug:ct,info:ct,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},Pe=Symbol.for("@zibby/agent-workflow.logger");globalThis[Pe]||(globalThis[Pe]={impl:hr});be=globalThis[Pe],A={debug:(...r)=>be.impl.debug?.(...r),info:(...r)=>be.impl.info?.(...r),warn:(...r)=>be.impl.warn?.(...r),error:(...r)=>be.impl.error?.(...r)}});var bt=Se(()=>{});var Et={};at(Et,{clearSkills:()=>xr,getAllSkills:()=>Mr,getSkill:()=>We,getSkillSource:()=>Or,hasSkill:()=>$r,listSkillIds:()=>Rr,registerSkill:()=>vr});function vr(r,e={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,o=r.id;if(V.has(o)&&!n){let i=ue.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).`)}}V.set(o,Object.freeze({...r})),t===void 0?ue.delete(o):ue.set(o,t)}function We(r){return V.get(r)||null}function $r(r){return V.has(r)}function Or(r){return ue.get(r)||null}function Mr(){return new Map(V)}function Rr(){return Array.from(V.keys())}function xr(){V.clear(),ue.clear()}var Fe,Ge,V,ue,He=Se(()=>{Fe=Symbol.for("@zibby/agent-workflow.skills"),Ge=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Fe]||(globalThis[Fe]=new Map);globalThis[Ge]||(globalThis[Ge]=new Map);V=globalThis[Fe],ue=globalThis[Ge]});var qe={};at(qe,{EFFORT_LEVELS:()=>Je,getAgentStrategy:()=>vt,invokeAgent:()=>Nr,listStrategies:()=>kr,registerStrategy:()=>Pr,resolveInvocationEffort:()=>Tt,resolveInvocationExtras:()=>At,resolveInvocationModel:()=>It});function Pr(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=X.findIndex(t=>t.getName()===r.getName());e>=0?X[e]=r:X.push(r)}function kr(){return X.map(r=>r.getName())}function It({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:o}={}){let i=r.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=r.agent?.[t]?.model||null,I=(typeof n=="string"?n.trim():"")||null;return s||a||l||u||e.model||I||null}function Tt({options:r={},envEffort:e,nodeConfigEffort:t}={}){let n=[t,r.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return n?Je.indexOf(n)===-1?(A.warn(`[workflow] ignoring unknown effort "${n}" \u2014 expected one of ${Je.join(", ")}`),null):n:null}function At({options:r={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||r.workspace,schema:r.schema||t.schema,images:r.images||t.images||[],skills:r.skills||t.skills||[],extraMcpServers:r.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:r.plugins||t.plugins||[]}}function vt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=X.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=${n}`);let o=X.find(i=>i.getName()===n);if(!o){let i=X.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!o.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return A.debug(`[workflow] using agent: ${o.getName()}`),o}async function Nr(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:n},i=vt(o),s=n.config||t.config||{},a=n._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,I=It({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d=!l||l===i.name?a.effort:null,c=Tt({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:d}),h={...t,model:I,...c?{effort:c}:{},...At({options:t,stateView:n,context:e}),config:s},p=r,_=h.skills||[];if(_.length>0&&!t.skipPromptFragments){let m=t.connectedIntegrations;if(!m){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){m={};for(let y of f.split(",").map(M=>M.trim()).filter(Boolean))m[y]=!0}}let b=f=>{let y=f&&f.requiresIntegration;return!y||!m?!0:(Array.isArray(y)?y:[y]).some(R=>m[R]===!0)},w=i.name==="assistant",v=f=>f?.inProcessOnly!==!0||w,g=_.map(f=>{let y=We(f);if(!b(y)||!v(y))return null;let M=y?.promptFragment;return typeof M=="function"?M():M}).filter(Boolean);g.length>0&&(p+=`
|
|
2
2
|
|
|
3
3
|
${g.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let $=n._currentNodeConfig?.stores;if(Array.isArray($)&&$.length>0&&typeof $[0]=="object"){let m=$.length<=8,b=$.map(
|
|
5
|
+
`)}`)}let $=n._currentNodeConfig?.stores;if(Array.isArray($)&&$.length>0&&typeof $[0]=="object"){let m=$.length<=8,b=$.map(w=>{let v=w?.id??w?.storeId??"",g=(w?.name??"").toString().trim()||v,f=w?.type?` \xB7 ${w.type}`:"",y=(w?.description||"").toString().replace(/\s+/g," ").trim(),M=`- ${g} \xB7 ${y||"(no description)"}${f} (id: ${v})`;if(m&&w?.schema&&typeof w.schema=="object"){let R=w.schema.properties&&typeof w.schema.properties=="object"?Object.keys(w.schema.properties):Object.keys(w.schema);R.length&&(M+=`
|
|
6
6
|
fields: ${R.join(", ")}`)}return M});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${b.join(`
|
|
10
|
-
`)}`}let
|
|
10
|
+
`)}`}let x=n._currentNodeConfig?.extraPromptInstructions?.trim();return x&&(p+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),A.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,h)}var
|
|
16
|
+
${x}
|
|
17
|
+
`),A.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,h)}var ze,X,Je,Ye=Se(()=>{bt();ce();He();ze=Symbol.for("@zibby/agent-workflow.strategies");globalThis[ze]||(globalThis[ze]=[]);X=globalThis[ze];Je=["low","medium","high","xhigh","max"]});var fr=new Set(["__proto__","constructor","prototype"]);function xe(r){if(fr.has(r))throw new Error(`Invalid state key: "${r}"`)}var _e=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){xe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)xe(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){xe(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import Q from"handlebars";var we=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 n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of n)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[n,o]of Object.entries(this.schema)){if(o.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&o.type){let i=typeof e[n];i!==o.type&&t.push(`Field '${n}' expected ${o.type}, got ${i}`)}if(o.validate&&n in e){let i=o.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};ce();import{writeFileSync as
|
|
19
|
+
`)}`);return e}};ce();import{writeFileSync as Ze,readFileSync as $t,existsSync as Ot,mkdirSync as Br}from"node:fs";import{join as Ke,dirname as Cr}from"node:path";import k from"chalk";var gr="__WORKFLOW_GRAPH_LOG__",le=k.gray("\u2502"),mr=k.gray("\u250C"),ke=k.gray("\u2514"),Ne=k.green("\u25C6"),lt=k.hex("#c084fc")("\u25C6"),ut=k.hex("#2dd4bf")("\u25C6"),Be=k.red("\u25C6"),dt=`${le} `,pt=2;function Ce(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function ft(r,e){return(t,n,o)=>{if(typeof t!="string")return r(t,n,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=dt,e.col=pt,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
|
+
${dt}`,e.col=pt))}return r(s,n,o)}}var Ue=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=ft(this._origStdoutWrite,e),process.stderr.write=ft(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=`${gr}${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(`${mr} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:o}=t;if(o)for(let s of o)this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(Ne,e):process.stdout.write.bind(process.stdout)(`${le} ${Ne} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(lt,e):process.stdout.write.bind(process.stdout)(`${le} ${lt} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=k.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ut,t):process.stdout.write.bind(process.stdout)(`${le} ${ut} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Be,k.red(e)):process.stdout.write.bind(process.stdout)(`${le} ${Be} ${k.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(`${mr} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting(),this._currentNode=null;let{duration:n,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Ne} ${s}`);let i=n?k.dim(` ${Ce(n)}`):"";this._rawWrite(`${ke} ${k.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting(),this._currentNode=null;let{duration:o}=n,i=o?k.dim(` ${Ce(o)}`):"";this._rawWrite(`${Be} ${k.red(t)}`),this._rawWrite(`${ke} ${k.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeStopped(e,t={}){this._stopIntercepting(),this._currentNode=null;let{duration:n}=t,o=n?k.dim(` ${Ce(n)}`):"";this._rawWrite(`${ke} ${k.dim("stopped")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(k.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},B=new Ue;var Ee=".zibby/output",ht="sessions",oe=".session-info.json",gt=".zibby-stop";var Pn=Object.freeze(["codebase-memory","code-scan","artifact"]),mt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var yr=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"}),Sr=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]),_r=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),_t=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function je(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r!="object")return String(r);let e=r;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(n=>typeof n=="string"||typeof n=="number").join(" | ")}function wr(r){if(r&&typeof r=="object"){let t=r.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=_t.exec(je(r));return e?e[1].toLowerCase():null}function br(r){if(r&&typeof r=="object"){let n=Number(r.providerErrorStatus);if(Number.isInteger(n)&&n>=100&&n<=599)return n}let e=_t.exec(je(r)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function Er(r){let e=je(r);if(!e)return"deterministic";for(let o of _r)if(o.test(e))return"deterministic";let t=wr(r);if(t){let o=yr[t];if(o==="transient"||o==="deterministic")return o}let n=br(r);if(n===429||n>=500&&n<=599)return"transient";for(let o of Sr)if(o.test(e))return"transient";return"deterministic"}var yt=2,Ir=5;function Tr(r=process.env){let e=r?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return yt;let t=Number(e);return!Number.isFinite(t)||t<0?yt:Math.min(Ir,Math.floor(t))}var De=5e3,wt=3e4;function Ar(r=process.env){let e=r?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return De;let t=Number(e);return!Number.isFinite(t)||t<0?De:Math.min(wt,Math.floor(t))}function St(r,e=Math.random,t=De){if(!(t>0))return 0;let n=Math.max(1,Math.floor(Number(r)||1)),o=Math.min(wt,t*2**(n-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function Le(r,{env:e=process.env,rand:t=Math.random}={}){let n=Math.max(0,Math.floor(Number(r)||0)),o=Tr(e),i=Ar(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=Er(l);return s<n?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?St(s,t,i):0,failureClass:u,index:s,of:n}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:St(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function Mt(r,e,t,n){if(!e.retry)return!1;if(n())return A.info(`[workflow] node '${r}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?A.warn(`[workflow] node '${r}': 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 '${r}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),n())?(A.info(`[workflow] node '${r}': run aborted during backoff \u2014 not retrying`),!1):!0}Q.helpers.inc||Q.registerHelper("inc",r=>Number(r)+1);Q.helpers.json||Q.registerHelper("json",r=>JSON.stringify(r,null,2));Q.helpers.eq||Q.registerHelper("eq",(r,e)=>r===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 we(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 n=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=h=>t&&typeof t.get=="function"?t.get(h):e?.[h],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){A.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let h=Le(this.retries),p=null,_=null;for(;;){try{let m=await this.customExecute(e);if(typeof m=="object"&&m!==null&&m.success===!1)_=null,p={success:!1,error:m.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:m.raw||null};else return this.isZodSchema?(A.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(m),raw:null}):{success:!0,output:m,raw:null}}catch(m){A.error(`[workflow] node '${this.name}' failed: ${m.message}`),m.name==="ZodError"&&A.error(`Schema errors: ${JSON.stringify(m.issues||m.errors,null,2)}`),_=m,p={success:!1,error:m.message,raw:null}}let $=_??p?.error,x=h.next($);if(!await Mt(this.name,x,$,i))break}return p&&(p.attempts=h.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=Q.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
|
|
33
33
|
|
|
34
|
-
${s}`);let l=n(),u=l.cwd||process.cwd(),I=l.sessionPath;try{if(I){let h=Ye(I,oe);if(Ot(h)){let w=JSON.parse($t(h,"utf-8"));w.currentNode=this.name,qe(h,JSON.stringify(w,null,2),"utf-8")}let p=Ye(I,"..",oe);if(Ot(p))try{let w=JSON.parse($t(p,"utf-8"));w.currentNode=this.name,qe(p,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(h){A.debug(`[workflow] could not update session info: ${h.message}`)}let d=De(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let h=n().config||{},p=h.agents||{},w=this.config.agent??p[this.name]??null,$={state:n()};w&&($.preferredAgent=w);let P={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:I,config:h,nodeName:this.name,timeout:this.config?.timeout||3e5},m=e?._coreInvokeAgent;m||(m=(await Promise.resolve().then(()=>(Je(),ze))).invokeAgent);let b=await m(s,$,P),_,v;if(typeof b=="string"?(_=b,v=null):b.structured?(_=b.raw||JSON.stringify(b.structured,null,2),v=b.structured):(_=b.raw||JSON.stringify(b,null,2),v=b.extracted||null),I)try{let g=Ye(I,this.name,"raw_stream_output.txt");Br(Cr(g),{recursive:!0}),qe(g,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(g){A.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&v){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let g=v;if(typeof this.onComplete=="function")try{g=await this.onComplete(n(),v)}catch(f){A.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:g,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:_}),raw:_}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(_);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),D.step("Output parsed"),{success:!0,output:g,raw:_}}return{success:!0,output:_,raw:_}}catch(h){c=h;let p=d.next(h);if(!await Mt(this.name,p,h,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};ce();ce();import{mkdirSync as Fr,existsSync as te,statSync as jt,readdirSync as Lt,rmSync as Gr}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as K}from"node:path";import{pathToFileURL as Wr}from"node:url";import{AsyncLocalStorage as Hr}from"node:async_hooks";import{AsyncLocalStorage as Ur}from"node:async_hooks";var de=new Ur;function se(){let r=de.getStore();return r||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 Rt(r,e){let t=de.getStore()||se(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return de.run(n,e)}function Pt(r,e,t){let n=de.getStore()||se(),o=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return de.run(o,t)}var Ze=new Map,Ke=new Map,kt=new Map;function xt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Ze.set(r,e),Ke.set(r,"ready"),kt.set(r,{...t,cachedAt:Date.now()})}function Nt(r,e){Ke.set(r,"failed"),kt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Ze.delete(r)}function Bt(r){return Ke.get(r)==="ready"?Ze.get(r):null}function pe(r,e,t=process.env){let n=Number(t[r]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):e}function Ie(r,e){return{signal:AbortSignal.timeout(r),label:`after ${r}ms (${e})`}}function fe(r,e){return Ie(pe(r,e),r)}function H(r){return r?.name==="TimeoutError"||r?.name==="AbortError"}function Z(r,e){return e.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,n)=>{let o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),Promise.resolve(r).then(i=>{e.removeEventListener("abort",o),t(i)},i=>{e.removeEventListener("abort",o),n(i)})})}var Te=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function zr(){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 Ae(r,e,t,n="timeout",o=null){let i=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=n,o&&(i.subgraphTransportError=o),i}function Jr(r,e=process.env,t=process.uptime()){let n=Number.isFinite(r)?Number(r):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(n===null&&s===null)return null;let a=n===null?s:s===null?n:Math.min(n,s);return Math.max(1,a)}function qr(r,e){let t=new AbortController,n=!1,o=null,i=()=>{t.abort(r?.reason)};return r&&(r.aborted?i():r.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{n=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),r&&r.removeEventListener("abort",i)}}}var Ut=new Hr,Dt=Promise.resolve();async function Yr(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let n=Ut.getStore()===!0,o=null;if(!n){let s=Dt;Dt=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)${n?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Zr(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!n||!o)throw new B("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:o}}async function Kr({apiBase:r,authToken:e,body:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.signal})}catch(s){throw new B(H(s)?"begin-timeout":"network",H(s)?`begin TIMED OUT ${n.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 ${n.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 ee({apiBase:r,authToken:e,payload:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.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 ${n.label}`:`failed: ${o.message}`}`)}}async function Vr(r,e){let t=K(e,".ready"),n=K(e,"graph.mjs");if(te(t)&&te(n))return;Fr(e,{recursive:!0});let o=K(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(te(t)&&te(n))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 I=Math.ceil(1e4/1e3),d=Math.ceil(pe("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ct("curl",["-fsSL","--connect-timeout",String(I),"--max-time",String(d),r],{stdio:["ignore","pipe","inherit"]}),h=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(h.stdin);let p,w,$=()=>{if(p!==void 0&&w!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(w!==0)return u(new Error(`tar exited ${w}`));l()}};c.on("close",P=>{p=P,$()}),h.on("close",P=>{w=P,$()}),c.on("error",u),h.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 Xr(r){let e=K(r,"graph.mjs");if(!te(e))throw new B("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(Wr(e).href)}catch(o){throw new B("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new B("entry-class-missing","no buildGraph() class export found");return n}async function Ft(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=se(),n;try{n=Zr()}catch(f){throw f}A.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let o=await Kr({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:I,bundleReady:d,nodeConfigs:c}=o,h=zr();if(s&&s!==h)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new B("runtime-mismatch",`${h} vs ${s}`);if(!d||!a)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new B("no-bundle","workflow bundle not built yet");let p=Bt(r);if(!p){let f=K(Te,`${I}@${u||"0"}`);try{await Vr(a,f);try{en()}catch{}}catch(y){throw y.fallback&&await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{p=await Xr(f),xt(r,p,{workflowUuid:I,version:u,runtimeTag:s,cacheDir:f})}catch(y){throw Nt(r,y),await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new B("import-failed",y.message)}}let w=Date.now(),$=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,P=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},...P?{nodeConfigs:c}:{}},b=Jr(e.timeoutMs),_=qr(e.signal,b),v,g;try{v=await Yr($,async()=>{let y=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,m,{signal:_.signal}))}),g=v&&typeof v=="object"&&"state"in v?v.state:v}catch(f){let y=_.timedOut();throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-w}}),y?Ae(r,i,b):f}finally{_.dispose()}if(v&&typeof v=="object"&&v.stoppedExternally){let f=_.timedOut();if(await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:g,durationMs:Date.now()-w}}),f)throw Ae(r,i,b);let y=new Error(`Sub-graph '${r}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-w}}),{finalState:g,executionId:i}}function Qr(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),o;try{o=jt(n)}catch{continue}if(o.isDirectory()){let i;try{i=Lt(n)}catch{continue}for(let s of i)t.push(K(n,s))}else e+=o.size}return e}function en({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!te(Te))return{evicted:0,freedBytes:0};let e=Lt(Te),t=[],n=0;for(let a of e){let l=K(Te,a),u;try{u=jt(l)}catch{continue}let I=u.isDirectory()?Qr(l):u.size;n+=I,t.push({name:a,full:l,size:I,mtimeMs:u.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(r*.7),i=0,s=0;for(let a of t){if(n-i<=o)break;if(!te(K(a.full,".lock")))try{Gr(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:n-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var rn=2e3,nn=600*1e3,on=new Set(["completed","failed","canceled","cancelled","timeout"]);var Wt=()=>fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function sn(r){let e=pe("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,r-Date.now()));return Ie(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ht(){let r=process.env.PROGRESS_API_URL;if(!r)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 r.replace(/\/executions\/?$/,"")}function zt(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function Jt(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function qt(){return process.env.EXECUTION_ID||null}function Gt(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}async function Ve(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=se();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:nn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g}=await Ft(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),f=Gt(g,e.output);return A.info(`[sub-graph] '${r}' completed in-process`),f}catch(g){if(g instanceof B||g?.fallback)A.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let i=Ht(),s=zt(),a=Jt(),l=qt(),u=e.participantBindingId?"participant":r,I=`${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 '${r}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Wt(),h;try{h=await Z(fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal}),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}if(!h.ok){let g=null,f="";try{g=await Z(h.json(),c.signal),f=g?.error||g?.message||JSON.stringify(g)}catch{f=await Z(h.text(),c.signal).catch(()=>"")}if(h.status===429){let M=g?.quotaInfo||{},R=new Error(`Sub-graph '${r}' blocked by execution quota (${M.used??"?"}/${M.limit??"?"} on plan ${M.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=r,R.quotaInfo=M,R}if(h.status===400){let M=new Error(`Sub-graph '${r}' rejected input: ${f}`);throw M.code="SUBGRAPH_INVALID_INPUT",M.status=400,M.subgraph=r,M.validationErrors=g?.validationErrors||null,M.missing=g?.missing||null,M}let y=new Error(`Sub-graph '${r}' trigger rejected (${h.status}): ${f}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=h.status,y.subgraph=r,y}let p;try{p=await Z(h.json(),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' 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 f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}let w=p?.data?.jobId||p?.jobId;if(!w)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(p).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${w} (not waiting)`),{jobId:w,status:"accepted",workflow:r};let $=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:rn,P=`${i}/executions/${encodeURIComponent(w)}`,m=Date.now()+o,b="accepted",_=0,v=null;for(;Date.now()<m;){await new Promise(R=>setTimeout(R,$)),_+=1;let g=sn(m),f;try{f=await Z(fetch(P,{headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal)}catch(R){v=H(R)?`poll TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${w} could not reach the API (${v}), will retry`);continue}if(!f.ok){if(f.status>=500){A.warn(`[sub-graph] status poll for ${w} returned ${f.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${w}: ${f.status}`)}let y;try{y=await Z(f.json(),g.signal)}catch(R){v=H(R)?`poll body read TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${w} returned an unreadable body (${v}), will retry`);continue}let M=y?.data||y?.execution||y;if(b=M?.status||b,on.has(b)){if(b!=="completed"){let E=new Error(`Sub-graph '${r}' (${w}) ended in status '${b}'`);throw E.subgraphJobId=w,E.subgraphStatus=b,E}let R=M?.finalState||M?.state||{},O=Gt(R,e.output);return A.info(`[sub-graph] '${r}' (${w}) completed after ${_} polls`),O}}try{let g=Ie(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),f=await Z(fetch(`${P}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal);!f.ok&&f.status!==400&&f.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${w} returned ${f.status}`)}catch(g){A.warn(`[sub-graph] best-effort cancel for ${w} failed: ${g?.message||String(g)}`)}throw Ae(r,w,o,b,v)}async function Yt(r,e={}){if(!r||typeof r!="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 Ve("participant",{...e,async:e.async!==!1,participantBindingId:r})}async function Zt(r){if(!r||typeof r!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Ht(),t=zt(),n=Jt(),o=qt();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=Wt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:r}),signal:s.signal})}catch(u){let I=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw I.code=H(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",I.cause=u,I}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 an=8*6e4,cn=10*6e4,ln=2*6e4;function un(r=process.env,e=process.uptime()){let t=Number(r?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function Kt(r,e,t=Number.MAX_SAFE_INTEGER){let n=Number(r);return Number.isFinite(n)&&n>0?Math.min(Math.floor(n),t):e}function he(r,e,t={}){return{requested:!0,required:r===!0,observed:!1,status:r===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function dn(r,e,t){return{participant:r.displayName||r.id,participantId:r.id,vendor:r.vendor||null,phase:e,revision:0,contribution:t}}function Vt(r,e,t){return r.find(n=>Array.isArray(n.roles)&&n.roles.includes(e))||t}var pn=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function fn(r,e,t){let n=r;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.phase===e&&n.role===t&&n.contextRevision===0&&typeof n.summary=="string"&&pn.every(i=>Array.isArray(n[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return n}async function Xt(r={},e={}){let t=String(r.protocolId||"discuss.v1"),n=String(r.objective||"").trim(),o=String(r.context||""),i=r.required===!0,s=Kt(r.timeoutMs,an,cn),a=Kt(r.reserveMs,ln,15*6e4),l=(e.remainingWorkflowTimeMs||un)();if(!n)return he(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return he(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||Zt,I=e.dispatchParticipant||Yt,d;try{d=await u(t)}catch(E){return he(i,E?.code||"participant_roster_unavailable",{protocolId:t,detail:E?.message||String(E)})}let c=d.filter(E=>E?.available===!1),h=d.filter(E=>E&&E.available!==!1&&E.id);if(h.length===0)return he(i,"no_available_participants",{protocolId:t,unavailable:c});let p=Date.now(),w=p+s,$=[],P=[],m=async(E,C,F,ge=[])=>{let ie=w-Date.now();if(ie<1e3){let Y=new Error("Collaboration node exhausted its authored timeout");throw Y.code="COLLABORATION_TIMEOUT",Y}let T=Number(E?.limits?.maxExecutionMinutes)*6e4,S=Number.isFinite(T)&&T>0?Math.min(ie,T):ie,U,j=null;for(let Y=0;Y<2;Y+=1){let ae=Y===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.":"",Me=await I(E.id,{async:!1,protocolId:t,timeoutMs:Math.min(S,Math.max(1e3,w-Date.now())),output:"contribute",input:{objective:n,protocolId:t,phase:C,role:F,contextRevision:0,sharedContext:o,priorContributions:ge,...r.instruction||ae?{instruction:[r.instruction,ae].filter(Boolean).join(`
|
|
35
|
-
`).slice(0,4e3)}:{}}});try{
|
|
34
|
+
${s}`);let l=n(),u=l.cwd||process.cwd(),I=l.sessionPath;try{if(I){let h=Ke(I,oe);if(Ot(h)){let _=JSON.parse($t(h,"utf-8"));_.currentNode=this.name,Ze(h,JSON.stringify(_,null,2),"utf-8")}let p=Ke(I,"..",oe);if(Ot(p))try{let _=JSON.parse($t(p,"utf-8"));_.currentNode=this.name,Ze(p,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(h){A.debug(`[workflow] could not update session info: ${h.message}`)}let d=Le(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let h=n().config||{},p=h.agents||{},_=this.config.agent??p[this.name]??null,$={state:n()};_&&($.preferredAgent=_);let x={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:I,config:h,nodeName:this.name,timeout:this.config?.timeout||3e5},m=e?._coreInvokeAgent;m||(m=(await Promise.resolve().then(()=>(Ye(),qe))).invokeAgent);let b=await m(s,$,x),w,v;if(typeof b=="string"?(w=b,v=null):b.structured?(w=b.raw||JSON.stringify(b.structured,null,2),v=b.structured):(w=b.raw||JSON.stringify(b,null,2),v=b.extracted||null),I)try{let g=Ke(I,this.name,"raw_stream_output.txt");Br(Cr(g),{recursive:!0}),Ze(g,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(g){A.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&v){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let g=v;if(typeof this.onComplete=="function")try{g=await this.onComplete(n(),v)}catch(f){A.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:g,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:w}),raw:w}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(w);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),B.step("Output parsed"),{success:!0,output:g,raw:w}}return{success:!0,output:w,raw:w}}catch(h){c=h;let p=d.next(h);if(!await Mt(this.name,p,h,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};ce();ce();import{mkdirSync as Fr,existsSync as te,statSync as jt,readdirSync as Lt,rmSync as Gr}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as K}from"node:path";import{pathToFileURL as Wr}from"node:url";import{AsyncLocalStorage as Hr}from"node:async_hooks";import{AsyncLocalStorage as Ur}from"node:async_hooks";var de=new Ur;function se(){let r=de.getStore();return r||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 Rt(r,e){let t=de.getStore()||se(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return de.run(n,e)}function xt(r,e,t){let n=de.getStore()||se(),o=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return de.run(o,t)}var Ve=new Map,Xe=new Map,Pt=new Map;function kt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Ve.set(r,e),Xe.set(r,"ready"),Pt.set(r,{...t,cachedAt:Date.now()})}function Nt(r,e){Xe.set(r,"failed"),Pt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Ve.delete(r)}function Bt(r){return Xe.get(r)==="ready"?Ve.get(r):null}function pe(r,e,t=process.env){let n=Number(t[r]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):e}function Ie(r,e){return{signal:AbortSignal.timeout(r),label:`after ${r}ms (${e})`}}function fe(r,e){return Ie(pe(r,e),r)}function H(r){return r?.name==="TimeoutError"||r?.name==="AbortError"}function Z(r,e){return e.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,n)=>{let o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),Promise.resolve(r).then(i=>{e.removeEventListener("abort",o),t(i)},i=>{e.removeEventListener("abort",o),n(i)})})}var Te=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function zr(){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 Ae(r,e,t,n="timeout",o=null){let i=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=n,o&&(i.subgraphTransportError=o),i}function Jr(r,e=process.env,t=process.uptime()){let n=Number.isFinite(r)?Number(r):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(n===null&&s===null)return null;let a=n===null?s:s===null?n:Math.min(n,s);return Math.max(1,a)}function qr(r,e){let t=new AbortController,n=!1,o=null,i=()=>{t.abort(r?.reason)};return r&&(r.aborted?i():r.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{n=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),r&&r.removeEventListener("abort",i)}}}var Ut=new Hr,Dt=Promise.resolve();async function Yr(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let n=Ut.getStore()===!0,o=null;if(!n){let s=Dt;Dt=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)${n?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Zr(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!n||!o)throw new C("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:o}}async function Kr({apiBase:r,authToken:e,body:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.signal})}catch(s){throw new C(H(s)?"begin-timeout":"network",H(s)?`begin TIMED OUT ${n.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 ${n.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 ee({apiBase:r,authToken:e,payload:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.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 ${n.label}`:`failed: ${o.message}`}`)}}async function Vr(r,e){let t=K(e,".ready"),n=K(e,"graph.mjs");if(te(t)&&te(n))return;Fr(e,{recursive:!0});let o=K(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(te(t)&&te(n))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 I=Math.ceil(1e4/1e3),d=Math.ceil(pe("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ct("curl",["-fsSL","--connect-timeout",String(I),"--max-time",String(d),r],{stdio:["ignore","pipe","inherit"]}),h=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(h.stdin);let p,_,$=()=>{if(p!==void 0&&_!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(_!==0)return u(new Error(`tar exited ${_}`));l()}};c.on("close",x=>{p=x,$()}),h.on("close",x=>{_=x,$()}),c.on("error",u),h.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 Xr(r){let e=K(r,"graph.mjs");if(!te(e))throw new C("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(Wr(e).href)}catch(o){throw new C("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new C("entry-class-missing","no buildGraph() class export found");return n}async function Ft(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=se(),n;try{n=Zr()}catch(f){throw f}A.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let o=await Kr({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:I,bundleReady:d,nodeConfigs:c}=o,h=zr();if(s&&s!==h)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new C("runtime-mismatch",`${h} vs ${s}`);if(!d||!a)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new C("no-bundle","workflow bundle not built yet");let p=Bt(r);if(!p){let f=K(Te,`${I}@${u||"0"}`);try{await Vr(a,f);try{en()}catch{}}catch(y){throw y.fallback&&await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{p=await Xr(f),kt(r,p,{workflowUuid:I,version:u,runtimeTag:s,cacheDir:f})}catch(y){throw Nt(r,y),await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new C("import-failed",y.message)}}let _=Date.now(),$=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,m={...e.input||{},...x?{nodeConfigs:c}:{}},b=Jr(e.timeoutMs),w=qr(e.signal,b),v,g;try{v=await Yr($,async()=>{let y=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,m,{signal:w.signal}))}),g=v&&typeof v=="object"&&"state"in v?v.state:v}catch(f){let y=w.timedOut();throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-_}}),y?Ae(r,i,b):f}finally{w.dispose()}if(v&&typeof v=="object"&&v.stoppedExternally){let f=w.timedOut();if(await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:g,durationMs:Date.now()-_}}),f)throw Ae(r,i,b);let y=new Error(`Sub-graph '${r}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-_}}),{finalState:g,executionId:i}}function Qr(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),o;try{o=jt(n)}catch{continue}if(o.isDirectory()){let i;try{i=Lt(n)}catch{continue}for(let s of i)t.push(K(n,s))}else e+=o.size}return e}function en({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!te(Te))return{evicted:0,freedBytes:0};let e=Lt(Te),t=[],n=0;for(let a of e){let l=K(Te,a),u;try{u=jt(l)}catch{continue}let I=u.isDirectory()?Qr(l):u.size;n+=I,t.push({name:a,full:l,size:I,mtimeMs:u.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(r*.7),i=0,s=0;for(let a of t){if(n-i<=o)break;if(!te(K(a.full,".lock")))try{Gr(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:n-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var rn=2e3,nn=600*1e3,on=new Set(["completed","failed","canceled","cancelled","timeout"]);var Wt=()=>fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function sn(r){let e=pe("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,r-Date.now()));return Ie(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ht(){let r=process.env.PROGRESS_API_URL;if(!r)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 r.replace(/\/executions\/?$/,"")}function zt(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function Jt(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function qt(){return process.env.EXECUTION_ID||null}function an(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}function Gt(r,e,t,n){let o=an(e,t);return n?{executionId:r,output:o}:o}async function Qe(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=se();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:nn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g,executionId:f}=await Ft(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),y=Gt(f,g,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${r}' completed in-process`),y}catch(g){if(g instanceof C||g?.fallback)A.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let i=Ht(),s=zt(),a=Jt(),l=qt(),u=e.participantBindingId?"participant":r,I=`${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 '${r}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Wt(),h;try{h=await Z(fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal}),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}if(!h.ok){let g=null,f="";try{g=await Z(h.json(),c.signal),f=g?.error||g?.message||JSON.stringify(g)}catch{f=await Z(h.text(),c.signal).catch(()=>"")}if(h.status===429){let M=g?.quotaInfo||{},R=new Error(`Sub-graph '${r}' blocked by execution quota (${M.used??"?"}/${M.limit??"?"} on plan ${M.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=r,R.quotaInfo=M,R}if(h.status===400){let M=new Error(`Sub-graph '${r}' rejected input: ${f}`);throw M.code="SUBGRAPH_INVALID_INPUT",M.status=400,M.subgraph=r,M.validationErrors=g?.validationErrors||null,M.missing=g?.missing||null,M}let y=new Error(`Sub-graph '${r}' trigger rejected (${h.status}): ${f}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=h.status,y.subgraph=r,y}let p;try{p=await Z(h.json(),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' 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 f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}let _=p?.data?.jobId||p?.jobId;if(!_)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(p).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${_} (not waiting)`),{jobId:_,status:"accepted",workflow:r};let $=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:rn,x=`${i}/executions/${encodeURIComponent(_)}`,m=Date.now()+o,b="accepted",w=0,v=null;for(;Date.now()<m;){await new Promise(R=>setTimeout(R,$)),w+=1;let g=sn(m),f;try{f=await Z(fetch(x,{headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal)}catch(R){v=H(R)?`poll TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${_} could not reach the API (${v}), will retry`);continue}if(!f.ok){if(f.status>=500){A.warn(`[sub-graph] status poll for ${_} returned ${f.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${_}: ${f.status}`)}let y;try{y=await Z(f.json(),g.signal)}catch(R){v=H(R)?`poll body read TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${_} returned an unreadable body (${v}), will retry`);continue}let M=y?.data||y?.execution||y;if(b=M?.status||b,on.has(b)){if(b!=="completed"){let E=new Error(`Sub-graph '${r}' (${_}) ended in status '${b}'`);throw E.subgraphJobId=_,E.subgraphStatus=b,E}let R=M?.finalState||M?.state||{},O=Gt(_,R,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${r}' (${_}) completed after ${w} polls`),O}}try{let g=Ie(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),f=await Z(fetch(`${x}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal);!f.ok&&f.status!==400&&f.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${_} returned ${f.status}`)}catch(g){A.warn(`[sub-graph] best-effort cancel for ${_} failed: ${g?.message||String(g)}`)}throw Ae(r,_,o,b,v)}async function Yt(r,e={}){if(!r||typeof r!="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 Qe("participant",{...e,async:e.async!==!1,participantBindingId:r})}async function Zt(r){if(!r||typeof r!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Ht(),t=zt(),n=Jt(),o=qt();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=Wt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:r}),signal:s.signal})}catch(u){let I=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw I.code=H(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",I.cause=u,I}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 cn=8*6e4,ln=10*6e4,un=2*6e4;function dn(r=process.env,e=process.uptime()){let t=Number(r?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function Kt(r,e,t=Number.MAX_SAFE_INTEGER){let n=Number(r);return Number.isFinite(n)&&n>0?Math.min(Math.floor(n),t):e}function he(r,e,t={}){return{requested:!0,required:r===!0,observed:!1,status:r===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function pn(r,e,t){return{participant:r.displayName||r.id,participantId:r.id,vendor:r.vendor||null,phase:e,revision:0,contribution:t}}function Vt(r,e,t){return r.find(n=>Array.isArray(n.roles)&&n.roles.includes(e))||t}var fn=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function hn(r,e,t){let n=r;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.phase===e&&n.role===t&&n.contextRevision===0&&typeof n.summary=="string"&&fn.every(i=>Array.isArray(n[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return n}async function Xt(r={},e={}){let t=String(r.protocolId||"discuss.v1"),n=String(r.objective||"").trim(),o=String(r.context||""),i=r.required===!0,s=Kt(r.timeoutMs,cn,ln),a=Kt(r.reserveMs,un,15*6e4),l=(e.remainingWorkflowTimeMs||dn)();if(!n)return he(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return he(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||Zt,I=e.dispatchParticipant||Yt,d;try{d=await u(t)}catch(E){return he(i,E?.code||"participant_roster_unavailable",{protocolId:t,detail:E?.message||String(E)})}let c=d.filter(E=>E?.available===!1),h=d.filter(E=>E&&E.available!==!1&&E.id);if(h.length===0)return he(i,"no_available_participants",{protocolId:t,unavailable:c});let p=Date.now(),_=p+s,$=[],x=[],m=async(E,U,G,ge=[])=>{let ie=_-Date.now();if(ie<1e3){let Y=new Error("Collaboration node exhausted its authored timeout");throw Y.code="COLLABORATION_TIMEOUT",Y}let T=Number(E?.limits?.maxExecutionMinutes)*6e4,S=Number.isFinite(T)&&T>0?Math.min(ie,T):ie,D,j=null;for(let Y=0;Y<2;Y+=1){let ae=Y===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.":"",Me=await I(E.id,{async:!1,protocolId:t,timeoutMs:Math.min(S,Math.max(1e3,_-Date.now())),output:"contribute",input:{objective:n,protocolId:t,phase:U,role:G,contextRevision:0,sharedContext:o,priorContributions:ge,...r.instruction||ae?{instruction:[r.instruction,ae].filter(Boolean).join(`
|
|
35
|
+
`).slice(0,4e3)}:{}}});try{D=hn(Me,U,G),j=null;break}catch(me){j=me}}if(j)throw j;let q=pn(E,U,D);return $.push(q),q},b=Vt(h,"draft",h[0]),w;try{w=await m(b,"draft","drafter")}catch(E){x.push({participantId:b.id,phase:"draft",code:E?.code||"PARTICIPANT_FAILED",detail:E?.message||String(E)});let U=he(i,"draft_failed",{protocolId:t,unavailable:c,failures:x,durationMs:Date.now()-p});return i&&(U.status="incomplete"),U}let v=h.filter(E=>E.id!==b.id);v.length===0&&(v=[b]);let g=await Promise.allSettled(v.map(E=>m(E,"critique","critic",[w]))),f=[];g.forEach((E,U)=>{E.status==="fulfilled"?f.push(E.value):x.push({participantId:v[U].id,phase:"critique",code:E.reason?.code||"PARTICIPANT_FAILED",detail:E.reason?.message||String(E.reason)})});let y=Vt(h,"synthesize",b),M=null;try{M=await m(y,"synthesize","synthesizer",[w,...f])}catch(E){x.push({participantId:y.id,phase:"synthesize",code:E?.code||"PARTICIPANT_FAILED",detail:E?.message||String(E)})}let R=f.length>0&&M!=null,O=(M?.contribution?.decisions||[]).filter(E=>E?.status==="unresolved");return{requested:!0,required:i,observed:R,status:R?"completed":"incomplete",reason:R?null:"required_phase_incomplete",protocolId:t,contributions:$,synthesis:M?.contribution||null,disagreements:O,failures:x,unavailable:c,durationMs:Date.now()-p}}import{existsSync as Qt,readFileSync as gn}from"node:fs";import{join as et,dirname as er}from"node:path";var $e=class{static async loadContext(e,t,n={}){let o={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=er(et(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let I=l.replace(/\.[^.]+$/,"").toLowerCase();o[I]=u}}}let s=n.discovery||{};for(let[a,l]of Object.entries(s))try{let u=et(t,l);Qt(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,n){let o=[],i=t;for(;i.startsWith(n);){let s=et(i,e);if(Qt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=er(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=
|
|
39
|
+
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=gn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),o=await import(n(e).href);return o.default||o}return t}};import{mkdirSync as or,existsSync as tt,writeFileSync as tr,unlinkSync as mn}from"node:fs";import{join as re,resolve as sr}from"node:path";import{config as yn}from"dotenv";import{zodToJsonSchema as rr}from"zod-to-json-schema";import{z as Oe}from"zod";import Sn from"handlebars";function _n({traceFrom:r,sessionId:e,sessionPath:t,idSource:n,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=${r} pid=${process.pid} ppid=${s} sessionId=${e} source=${n} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let I=(new Error("session trace").stack||"").split(`
|
|
40
40
|
`).slice(2,14).join(`
|
|
41
41
|
`);console.log(`[zibby:session] stack (${r}):
|
|
42
|
-
${I}`)}}function _n(){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 wn(){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 sr(String(e).trim())}catch{return String(e).trim()}}function bn(){_n()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function En({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function In(r={}){let e=mt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,o=r.paths?.sessionPrefix;return o?`${o}_${n}`:n}function Tn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=sr(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=In(e),s="generated")}i=i??Date.now();let I=e.paths?.output||Ee;o=re(r,I,ht,a)}let l=!Qe(o);return l&&or(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&Sn({traceFrom:n,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),En({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var nr=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,n={}){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 I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(h,p="")=>typeof h=="function"?h(I):h??p,c=await Xt({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 h=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw h.code="COLLABORATION_REQUIRED_INCOMPLETE",h.collaborationResult=c,h}return c}},l=new z(a);return l.name=e,this.nodes.set(e,l),Object.keys(n).length>0&&this.nodeOptions.set(e,n),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 I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(I):s.input&&typeof s.input=="object"?d=s.input:d={},Ve(s.workflow,{input:d,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(I):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:I?._signal,parentAgent:u?.agent})}},l=new z(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),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),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.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:n}={}){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:n}),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,n=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&&n(s)}t.set(i,2)};this.entryPoint&&n(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,n,o,i){let s=n;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 h=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:h,data:{nodeType:h,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(p.description=w);let $=c?.config?.collaboration;$&&typeof $=="object"&&(p.collaboration={protocolId:$.protocolId||"discuss.v1",required:$.required===!0,...Number.isFinite($.timeoutMs)?{timeoutMs:$.timeoutMs}:{},...Number.isFinite($.reserveMs)?{reserveMs:$.reserveMs}:{}});let P=c?.config?.collaborationAsync;P&&typeof P=="object"&&(p.collaborationAsync={protocolId:P.protocolId||"discuss.v1"});let m=this.nodePrompts.get(d);if(m)p.prompt=m;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 b=c?.config?.dispatchesWorkflow;if(typeof b=="string"&&b.trim())p.dispatchesWorkflow=b.trim();else if(Array.isArray(b)){let O=[...new Set(b.filter(E=>typeof E=="string").map(E=>E.trim()).filter(Boolean))];O.length&&(p.dispatchesWorkflow=O)}let _=c?.config?.minimumReadyChildren;if(_!=null){if(!Number.isInteger(_)||_<=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(_>O)throw new Error(`Node '${d}' minimumReadyChildren (${_}) exceeds its declared dispatch roster (${O})`);p.minimumReadyChildren=_}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 Oe?.toJSONSchema=="function")try{O=Oe.toJSONSchema(c.outputSchema)}catch{}if(!O)try{O=rr(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=O?{jsonSchema:O,variables:this._flattenJsonSchemaToVariables(O)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let v=(this.resolvedToolsMap||{})[d];v?.toolIds&&(p.tools=v.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(p.skills=[...g]);let f=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;f&&f.length>0&&(p.optionalSkills=[...f]);let y=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;y&&y.length>0&&(p.plugins=y.map(O=>O&&typeof O=="object"?{...O}:O));let M=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;M&&M.length>0&&(p.stores=M.map(O=>O&&typeof O=="object"?{...O}:O));let R=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(R&&R.length>0){let O=new Set,E=[];for(let C of R){let F=typeof C=="string"?C.trim():"";!F||O.has(F)||(O.add(F),E.push(F))}E.length>0&&(p.uses=E)}Object.keys(p).length>0&&(t[d]=p)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let h of c)n.push({source:d,target:h});else if(c.conditional){let h=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},$=this.nodes.get(d),P=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,m=d;if(!P){let b=`${d}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),n.push({source:d,target:b}),m=b}for(let b of p){let _={source:m,target:b,data:{conditionalCode:h}};w[b]&&(_.label=w[b]),n.push(_)}}let o=d=>{if(!d)return null;if(typeof Oe?.toJSONSchema=="function")try{return Oe.toJSONSchema(d)}catch{}try{return rr(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)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"}}),n.push({source:d,target:c})}let s=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),I=o(this.contextSchema);return{nodes:s,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:I}}_topoOrderNodes(e,t){let n=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(n.keys()),u=[...l].filter(d=>i.get(d)===0),I=[];for(;I.length<e.length;){let d;if(u.length>0){if(u.sort((c,h)=>n.get(c)-n.get(h)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,h)=>n.get(c)-n.get(h))[0];a.add(d),l.delete(d),I.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 I}_inferConditionalTargets(e,t){let n=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(n))!==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,I;for(;(I=u.exec(n))!==null;)l.add(I[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");n=e.definitions[o]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.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)n.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);n.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){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 S=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw S.cause=T,S.code=T?.code||"NORMALIZE_INPUT_FAILED",S}let o=new AbortController;n.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();mn({path:re(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=re(s,".zibby.config.js");Qe(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||{},I=this._runtimeSchema();if(I){let T=I.safeParse(t);if(!T.success){let S=T.error.issues.map(U=>`${U.path.join(".")}: ${U.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(U=>console.error(` - ${U}`)),new Error(`State validation failed: ${S.join(", ")}`)}D.step("State validated against schema")}let d=wn(),c=t.sessionPath||d;c||bn();let{sessionPath:h,sessionTimestamp:p,sessionId:w}=Tn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});D.step(`Session ${w}`);let $=await $e.loadContext(t.specPath||"",s,u);Object.keys($).length>0&&D.step(`Context loaded: ${Object.keys($).join(", ")}`);let P=t.outputPath;!P&&t.specPath&&(e?.calculateOutputPath?P=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new _e({...t,config:a,agentType:l,outputPath:P,sessionPath:h,sessionTimestamp:p,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(Ge(),Et)),v=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(v).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),f=T=>{for(let S of g)if(S.id===T)return S;return _(T)},y=new Set;for(let[,T]of this.nodes)for(let S of T.config?.skills||[])y.add(S);for(let T of y){let S=f(T);if(typeof S?.middleware=="function")try{let U=await S.middleware();typeof U=="function"&&b.set(T,U)}catch{}}let{backEdges:M,joinDegree:R}=this._analyzeFlow(),O=new Map,E=[],C=(T,S,U)=>{if(!T||T==="END")return;let j=R.get(T)||0;if(U&&j>1&&!M.has(`${S}->${T}`)){let q=(O.get(T)||0)+1;if(q<j){O.set(T,q);return}O.set(T,0)}E.includes(T)||E.push(T)};this.entryPoint&&E.push(this.entryPoint);let F=[],ge=a?.recursionLimit??100,ie=0;try{for(;E.length>0;){let S=E.pop();if(!S||S==="END")continue;if(++ie>ge)throw new Error(`Workflow exceeded recursion limit (${ge}) \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=re(h,gt);if(Qe(U)){try{gn(U)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
43
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
42
|
+
${I}`)}}function wn(){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 bn(){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 sr(String(e).trim())}catch{return String(e).trim()}}function En(){wn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function In({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Tn(r={}){let e=mt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,o=r.paths?.sessionPrefix;return o?`${o}_${n}`:n}function An({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=sr(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=Tn(e),s="generated")}i=i??Date.now();let I=e.paths?.output||Ee;o=re(r,I,ht,a)}let l=!tt(o);return l&&or(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&_n({traceFrom:n,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),In({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var nr=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,n={}){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 I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(h,p="")=>typeof h=="function"?h(I):h??p,c=await Xt({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 h=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw h.code="COLLABORATION_REQUIRED_INCOMPLETE",h.collaborationResult=c,h}return c}},l=new z(a);return l.name=e,this.nodes.set(e,l),Object.keys(n).length>0&&this.nodeOptions.set(e,n),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 I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(I):s.input&&typeof s.input=="object"?d=s.input:d={},Qe(s.workflow,{input:d,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(I):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:I?._signal,parentAgent:u?.agent})}},l=new z(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),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),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.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:n}={}){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:n}),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,n=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&&n(s)}t.set(i,2)};this.entryPoint&&n(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,n,o,i){let s=n;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 h=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:h,data:{nodeType:h,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(p.description=_);let $=c?.config?.collaboration;$&&typeof $=="object"&&(p.collaboration={protocolId:$.protocolId||"discuss.v1",required:$.required===!0,...Number.isFinite($.timeoutMs)?{timeoutMs:$.timeoutMs}:{},...Number.isFinite($.reserveMs)?{reserveMs:$.reserveMs}:{}});let x=c?.config?.collaborationAsync;x&&typeof x=="object"&&(p.collaborationAsync={protocolId:x.protocolId||"discuss.v1"});let m=this.nodePrompts.get(d);if(m)p.prompt=m;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 b=c?.config?.dispatchesWorkflow;if(typeof b=="string"&&b.trim())p.dispatchesWorkflow=b.trim();else if(Array.isArray(b)){let O=[...new Set(b.filter(E=>typeof E=="string").map(E=>E.trim()).filter(Boolean))];O.length&&(p.dispatchesWorkflow=O)}let w=c?.config?.minimumReadyChildren;if(w!=null){if(!Number.isInteger(w)||w<=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(w>O)throw new Error(`Node '${d}' minimumReadyChildren (${w}) exceeds its declared dispatch roster (${O})`);p.minimumReadyChildren=w}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 Oe?.toJSONSchema=="function")try{O=Oe.toJSONSchema(c.outputSchema)}catch{}if(!O)try{O=rr(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=O?{jsonSchema:O,variables:this._flattenJsonSchemaToVariables(O)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let v=(this.resolvedToolsMap||{})[d];v?.toolIds&&(p.tools=v.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(p.skills=[...g]);let f=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;f&&f.length>0&&(p.optionalSkills=[...f]);let y=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;y&&y.length>0&&(p.plugins=y.map(O=>O&&typeof O=="object"?{...O}:O));let M=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;M&&M.length>0&&(p.stores=M.map(O=>O&&typeof O=="object"?{...O}:O));let R=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(R&&R.length>0){let O=new Set,E=[];for(let U of R){let G=typeof U=="string"?U.trim():"";!G||O.has(G)||(O.add(G),E.push(G))}E.length>0&&(p.uses=E)}Object.keys(p).length>0&&(t[d]=p)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let h of c)n.push({source:d,target:h});else if(c.conditional){let h=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},$=this.nodes.get(d),x=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,m=d;if(!x){let b=`${d}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),n.push({source:d,target:b}),m=b}for(let b of p){let w={source:m,target:b,data:{conditionalCode:h}};_[b]&&(w.label=_[b]),n.push(w)}}let o=d=>{if(!d)return null;if(typeof Oe?.toJSONSchema=="function")try{return Oe.toJSONSchema(d)}catch{}try{return rr(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)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"}}),n.push({source:d,target:c})}let s=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),I=o(this.contextSchema);return{nodes:s,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:I}}_topoOrderNodes(e,t){let n=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(n.keys()),u=[...l].filter(d=>i.get(d)===0),I=[];for(;I.length<e.length;){let d;if(u.length>0){if(u.sort((c,h)=>n.get(c)-n.get(h)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,h)=>n.get(c)-n.get(h))[0];a.add(d),l.delete(d),I.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 I}_inferConditionalTargets(e,t){let n=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(n))!==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,I;for(;(I=u.exec(n))!==null;)l.add(I[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");n=e.definitions[o]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.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)n.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);n.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){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 S=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw S.cause=T,S.code=T?.code||"NORMALIZE_INPUT_FAILED",S}let o=new AbortController;n.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();yn({path:re(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=re(s,".zibby.config.js");tt(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||{},I=this._runtimeSchema();if(I){let T=I.safeParse(t);if(!T.success){let S=T.error.issues.map(D=>`${D.path.join(".")}: ${D.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(D=>console.error(` - ${D}`)),new Error(`State validation failed: ${S.join(", ")}`)}B.step("State validated against schema")}let d=bn(),c=t.sessionPath||d;c||En();let{sessionPath:h,sessionTimestamp:p,sessionId:_}=An({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});B.step(`Session ${_}`);let $=await $e.loadContext(t.specPath||"",s,u);Object.keys($).length>0&&B.step(`Context loaded: ${Object.keys($).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 m=new _e({...t,config:a,agentType:l,outputPath:x,sessionPath:h,sessionTimestamp:p,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(He(),Et)),v=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(v).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),f=T=>{for(let S of g)if(S.id===T)return S;return w(T)},y=new Set;for(let[,T]of this.nodes)for(let S of T.config?.skills||[])y.add(S);for(let T of y){let S=f(T);if(typeof S?.middleware=="function")try{let D=await S.middleware();typeof D=="function"&&b.set(T,D)}catch{}}let{backEdges:M,joinDegree:R}=this._analyzeFlow(),O=new Map,E=[],U=(T,S,D)=>{if(!T||T==="END")return;let j=R.get(T)||0;if(D&&j>1&&!M.has(`${S}->${T}`)){let q=(O.get(T)||0)+1;if(q<j){O.set(T,q);return}O.set(T,0)}E.includes(T)||E.push(T)};this.entryPoint&&E.push(this.entryPoint);let G=[],ge=a?.recursionLimit??100,ie=0;try{for(;E.length>0;){let S=E.pop();if(!S||S==="END")continue;if(++ie>ge)throw new Error(`Workflow exceeded recursion limit (${ge}) \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=re(h,gt);if(tt(D)){try{mn(D)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
43
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),B.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:G,stoppedExternally:!0};let j=this.nodes.get(S);if(!j)throw new Error(`Node '${S}' not found in graph`);let q=JSON.stringify({sessionPath:h,sessionTimestamp:p,currentNode:S,createdAt:new Date().toISOString(),config:m.get("config")}),Y=re(h,oe);tr(Y,q,"utf-8");let ae=m.get("config")?.paths?.output||Ee,Me=re(s,ae,oe);or(re(s,ae),{recursive:!0});try{tr(Me,q,"utf-8")}catch{}let me=t.onPipelineProgress;if(typeof me=="function")try{me({cwd:s,sessionPath:h,sessionId:_,outputBase:m.get("config")?.paths?.output||Ee,currentNode:S})}catch{}let ir=(this.resolvedToolsMap||{})[S]||null;m.set("_currentNodeTools",ir);let ar=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",ar[S]||{}),B.nodeStart(S);let rt=Date.now(),ye=this.nodePrompts.get(S);if(!this._invokeAgent){let N=await Promise.resolve().then(()=>(Ye(),qe));this._invokeAgent=N.invokeAgent}let cr=this._invokeAgent,Re={},lr=j.config?.skills||[];for(let N of lr){let L=f(N);if(typeof L?.invokeAgentOptions=="function")try{let P=L.invokeAgentOptions(m.getAll(),{agentType:m.get("agentType"),nodeName:S});P&&typeof P=="object"&&(Re={...Re,...P})}catch(P){console.warn(`[graph] skill '${N}' invokeAgentOptions threw: ${P.message}`)}}let nt=async(N,L,P={})=>{let F=cr(N,L,{...Re,...P,signal:o.signal});return F.catch(()=>{}),o.signal.aborted?F:Promise.race([F,new Promise((ne,J)=>{let W=()=>{setTimeout(()=>{let it=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);it.name="AbortError",J(it)},i)};o.signal.addEventListener("abort",W,{once:!0})})])},ur=async(N={},L={})=>{let P=L.prompt||"";if(ye){let F=this._compiledPrompts.get(S);F||(F=Sn.compile(ye,{noEscape:!0}),this._compiledPrompts.set(S,F));try{P=F(N)}catch(ne){throw console.error(`\u274C Template rendering failed for node '${S}':`,ne.message),new Error(`Template rendering failed: ${ne.message}`,{cause:ne})}}else if(!P)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return nt(P,{state:m.getAll(),images:L.images||[]},{model:L.model||m.get("model"),workspace:m.get("workspace"),schema:L.schema,...L,signal:o.signal,nodeName:S})},ot=m.getAll(),dr=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let N of dr)Object.prototype.hasOwnProperty.call(ot,N)&&console.warn(`[workflow] node "${S}": state key "${N}" is shadowed by the engine context prop; read it via context.state.get('${N}')`);let st={...ot,state:m,invokeAgent:ur,_coreInvokeAgent:nt,agent:e,nodeId:S,promptTemplate:ye,getPromptTemplate:()=>ye};try{let N=(j.config?.skills||[]).map(W=>b.get(W)).filter(Boolean),L=[...this.middleware,...N],P;P=await xt(e,o.signal,async()=>L.length>0?this._composeMiddleware(L,S,async()=>j.execute(st,m),m.getAll(),m):j.execute(st,m));let F=Date.now()-rt;if(G.push({node:S,success:P.success,duration:F,timestamp:new Date().toISOString()}),!P.success){if(o.signal.aborted)return B.nodeStopped(S,{duration:F}),B.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:G,stoppedExternally:!0};m.append("errors",{node:S,error:P.error});let W=Number.isInteger(P.attempts)&&P.attempts>0?P.attempts:(j.config?.retries||0)+1;throw B.nodeFailed(S,P.error,{duration:F}),new Error(`Node '${S}' failed after ${W} attempt(s): ${P.error}`)}m.update({[S]:P.output});let ne=this._summarizeNodeOutput(S,P.output);B.nodeComplete(S,{duration:F,details:ne});let J=this.edges.get(S);if(J)if(J.conditional){let W=J.routes(m.getAll());B.route(S,W),U(W,S,!1)}else if(Array.isArray(J))for(let W=J.length-1;W>=0;W--)U(J[W],S,!0);else U(J,S,!0)}catch(N){throw B.isInsideNode&&B.nodeFailed(S,N.message,{duration:Date.now()-rt}),m.set("failed",!0),m.set("failedAt",S),N}}B.graphComplete();let T={success:!0,state:m.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}`)}}}};export{nr as WorkflowGraph,En as clearInheritedSessionEnvForFreshRun,Tn as generateWorkflowSessionId,bn as readPinnedSessionPathFromEnv,An as resolveWorkflowSession,wn as shouldTrustInheritedSessionEnv,In as syncProcessEnvToSession};
|