@zibby/agent-workflow 2.0.13 → 2.0.14
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 +12 -12
- package/dist/graph.js +10 -10
- package/dist/index.js +21 -21
- package/dist/sub-graph-executor.d.ts +7 -1
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var tr=Object.defineProperty;var Je=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var
|
|
1
|
+
var tr=Object.defineProperty;var Je=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var xe=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Pt=(n,e)=>{for(var t in e)tr(n,t,{get:e[t],enumerable:!0})};function or(n){ge.impl={...Bt,...n}}var Ct,Bt,Ye,ge,A,Z=xe(()=>{Ct=()=>{},Bt={debug:Ct,info:Ct,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ye=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ye]||(globalThis[Ye]={impl:Bt});ge=globalThis[Ye];A={debug:(...n)=>ge.impl.debug?.(...n),info:(...n)=>ge.impl.info?.(...n),warn:(...n)=>ge.impl.warn?.(...n),error:(...n)=>ge.impl.error?.(...n)}});var st,it=xe(()=>{st=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var sn={};Pt(sn,{clearSkills:()=>on,getAllSkills:()=>nn,getSkill:()=>ae,getSkillSource:()=>tn,hasSkill:()=>en,listSkillIds:()=>rn,registerSkill:()=>Qt});function Qt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,s=n.id;if(ee.has(s)&&!r){let i=we.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" 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).`)}}ee.set(s,Object.freeze({...n})),t===void 0?we.delete(s):we.set(s,t)}function ae(n){return ee.get(n)||null}function en(n){return ee.has(n)}function tn(n){return we.get(n)||null}function nn(){return new Map(ee)}function rn(){return Array.from(ee.keys())}function on(){ee.clear(),we.clear()}var at,ct,ee,we,Se=xe(()=>{at=Symbol.for("@zibby/agent-workflow.skills"),ct=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[at]||(globalThis[at]=new Map);globalThis[ct]||(globalThis[ct]=new Map);ee=globalThis[at],we=globalThis[ct]});var _e={};Pt(_e,{EFFORT_LEVELS:()=>Pe,getAgentStrategy:()=>ft,invokeAgent:()=>ln,listStrategies:()=>cn,registerStrategy:()=>an,resolveInvocationEffort:()=>dt,resolveInvocationExtras:()=>pt,resolveInvocationModel:()=>ut});function an(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=te.findIndex(t=>t.getName()===n.getName());e>=0?te[e]=n:te.push(n)}function cn(){return te.map(n=>n.getName())}function ut({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:s}={}){let i=n.models||{},o=typeof s=="string"&&s.trim()?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,m=(typeof r=="string"?r.trim():"")||null;return o||a||l||u||e.model||m||null}function dt({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(s=>typeof s=="string"?s.trim().toLowerCase():"").find(Boolean);return r?Pe.indexOf(r)===-1?(A.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${Pe.join(", ")}`),null):r:null}function pt({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function ft(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=te.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}A.debug(`[workflow] agent selection: requested=${r}`);let s=te.find(i=>i.getName()===r);if(!s){let i=te.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return A.debug(`[workflow] using agent: ${s.getName()}`),s}async function ln(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},i=ft(s),o=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,m=ut({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),p=!l||l===i.name?a.effort:null,c=dt({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:p}),f={...t,model:m,...c?{effort:c}:{},...pt({options:t,stateView:r,context:e}),config:o},d=n,y=f.skills||[];if(y.length>0&&!t.skipPromptFragments){let h=t.connectedIntegrations;if(!h){let g=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof g=="string"&&g.trim()!==""){h={};for(let S of g.split(",").map(x=>x.trim()).filter(Boolean))h[S]=!0}}let _=g=>{let S=g&&g.requiresIntegration;return!S||!h?!0:(Array.isArray(S)?S:[S]).some(O=>h[O]===!0)},E=i.name==="assistant",k=g=>g?.inProcessOnly!==!0||E,w=y.map(g=>{let S=ae(g);if(!_(S)||!k(S))return null;let x=S?.promptFragment;return typeof x=="function"?x():x}).filter(Boolean);w.length>0&&(d+=`
|
|
2
2
|
|
|
3
3
|
${w.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let T=r._currentNodeConfig?.stores;if(Array.isArray(T)&&T.length>0&&typeof T[0]=="object"){let h=T.length<=8,
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let T=r._currentNodeConfig?.stores;if(Array.isArray(T)&&T.length>0&&typeof T[0]=="object"){let h=T.length<=8,_=T.map(E=>{let k=E?.id??E?.storeId??"",w=(E?.name??"").toString().trim()||k,g=E?.type?` \xB7 ${E.type}`:"",S=(E?.description||"").toString().replace(/\s+/g," ").trim(),x=`- ${w} \xB7 ${S||"(no description)"}${g} (id: ${k})`;if(h&&E?.schema&&typeof E.schema=="object"){let O=E.schema.properties&&typeof E.schema.properties=="object"?Object.keys(E.schema.properties):Object.keys(E.schema);O.length&&(x+=`
|
|
6
|
+
fields: ${O.join(", ")}`)}return x});d+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
9
|
+
${_.join(`
|
|
10
10
|
`)}`}let $=r._currentNodeConfig?.extraPromptInstructions?.trim();return $&&(d+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
@@ -14,11 +14,11 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${$}
|
|
17
|
-
`),A.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,f)}var lt,te,Pe,ce=
|
|
17
|
+
`),A.debug(`[workflow] prompt length: ${d.length} chars`),i.invoke(d,f)}var lt,te,Pe,ce=xe(()=>{it();Z();Se();lt=Symbol.for("@zibby/agent-workflow.strategies");globalThis[lt]||(globalThis[lt]=[]);te=globalThis[lt];Pe=["low","medium","high","xhigh","max"]});var nr=new Set(["__proto__","constructor","prototype"]);function qe(n){if(nr.has(n))throw new Error(`Invalid state key: "${n}"`)}var fe=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){qe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)qe(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){qe(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 ne from"handlebars";var he=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of r)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&s.type){let i=typeof e[r];i!==s.type&&t.push(`Field '${r}' expected ${s.type}, got ${i}`)}if(s.validate&&r in e){let i=s.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
19
|
`)}`);return e}},rr={string:(n=!0)=>({type:"string",required:n}),number:(n=!0)=>({type:"number",required:n}),boolean:(n=!0)=>({type:"boolean",required:n}),array:(n=!0)=>({type:"object",required:n,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(n,e=!0)=>({type:"string",required:e,validate:t=>n.includes(t)?null:`must be one of: ${n.join(", ")}`})};Z();import{writeFileSync as ht,readFileSync as un,existsSync as dn,mkdirSync as fr}from"node:fs";import{join as gt,dirname as hr}from"node:path";import P from"chalk";var Ht="__WORKFLOW_GRAPH_LOG__",me=P.gray("\u2502"),sr=P.gray("\u250C"),Dt=P.gray("\u2514"),Ke=P.green("\u25C6"),jt=P.hex("#c084fc")("\u25C6"),Lt=P.hex("#2dd4bf")("\u25C6"),Ze=P.red("\u25C6"),Ut=`${me} `,Ft=2;function Gt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Wt(n,e){return(t,r,s)=>{if(typeof t!="string")return n(t,r,s);let i=process.stdout.columns||120,o="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(o+=Ut,e.col=Ft,e.lineStart=!1),l===`
|
|
20
20
|
`?(o+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,o+=l):e.inEsc?(o+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,o+=l,e.col>=i&&(o+=`
|
|
21
|
-
${Ut}`,e.col=Ft))}return n(o,r,s)}}var
|
|
21
|
+
${Ut}`,e.col=Ft))}return n(o,r,s)}}var Oe=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Wt(this._origStdoutWrite,e),process.stderr.write=Wt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
24
|
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Ht}${JSON.stringify(e)}
|
|
@@ -29,18 +29,18 @@ ${Ut}`,e.col=Ft))}return n(o,r,s)}}var xe=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(jt,e):process.stdout.write.bind(process.stdout)(`${me} ${jt} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=P.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Lt,t):process.stdout.write.bind(process.stdout)(`${me} ${Lt} ${t}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ze,P.red(e)):process.stdout.write.bind(process.stdout)(`${me} ${Ze} ${P.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${sr} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let o of s)this._rawWrite(`${Ke} ${o}`);let i=r?P.dim(` ${Gt(r)}`):"";this._rawWrite(`${Dt} ${P.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?P.dim(` ${Gt(s)}`):"";this._rawWrite(`${Ze} ${P.red(t)}`),this._rawWrite(`${Dt} ${P.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(P.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},C=new
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${sr} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let o of s)this._rawWrite(`${Ke} ${o}`);let i=r?P.dim(` ${Gt(r)}`):"";this._rawWrite(`${Dt} ${P.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?P.dim(` ${Gt(s)}`):"";this._rawWrite(`${Ze} ${P.red(t)}`),this._rawWrite(`${Dt} ${P.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(P.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},C=new Oe;var ye=".zibby/output",Ve="sessions",Q=".session-info.json",Xe=".zibby-stop",ir="result.json",ar="raw_stream_output.txt",cr="events.json",lr=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var zt=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"}),Jt=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]),ur=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),qt=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function dr({kind:n,status:e,text:t}){let r=typeof n=="string"&&n.trim()?n.trim():"unclassified",s=Number(e),i=Number.isInteger(s)&&s>=100&&s<=599?` http ${s}`:"",a=(typeof t=="string"?t.trim():"")||"the provider reported a failure but gave no message";return`provider error [${r}${i}]: ${a}`}function nt(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function Yt(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=qt.exec(nt(n));return e?e[1].toLowerCase():null}function Kt(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=qt.exec(nt(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function rt(n){let e=nt(n);if(!e)return"deterministic";for(let s of ur)if(s.test(e))return"deterministic";let t=Yt(n);if(t){let s=zt[t];if(s==="transient"||s==="deterministic")return s}let r=Kt(n);if(r===429||r>=500&&r<=599)return"transient";for(let s of Jt)if(s.test(e))return"transient";return"deterministic"}function pr(n){return rt(n)==="transient"}var et=2,Zt=5;function Vt(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return et;let t=Number(e);return!Number.isFinite(t)||t<0?et:Math.min(Zt,Math.floor(t))}var Re=5e3,ot=3e4;function Xt(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Re;let t=Number(e);return!Number.isFinite(t)||t<0?Re:Math.min(ot,Math.floor(t))}function tt(n,e=Math.random,t=Re){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),s=Math.min(ot,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(s*i))}function Me(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),s=Vt(e),i=Xt(e),o=0,a=0;return{get attemptsMade(){return 1+o+a},get transientUsed(){return a},get transientMax(){return s},next(l){let u=rt(l);return o<r?(o+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?tt(o,t,i):0,failureClass:u,index:o,of:r}):u==="transient"&&a<s?(a+=1,{retry:!0,paidBy:"transient",delayMs:tt(a,t,i),failureClass:u,index:a,of:s}):{retry:!1,delayMs:0,failureClass:u}}}}async function pn(n,e,t,r){if(!e.retry)return!1;if(r())return A.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let s=t?.message??String(t??"");return e.paidBy==="transient"?A.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${s}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):A.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(A.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}ne.helpers.inc||ne.registerHelper("inc",n=>Number(n)+1);ne.helpers.json||ne.registerHelper("json",n=>JSON.stringify(n,null,2));ne.helpers.eq||ne.registerHelper("eq",(n,e)=>n===e);var H=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 he(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return A.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=f=>t&&typeof t.get=="function"?t.get(f):e?.[f],i=()=>s("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){A.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let f=Me(this.retries),d=null,y=null;for(;;){try{let h=await this.customExecute(e);if(typeof h=="object"&&h!==null&&h.success===!1)y=null,d={success:!1,error:h.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:h.raw||null};else return this.isZodSchema?(A.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(h),raw:null}):{success:!0,output:h,raw:null}}catch(h){A.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&A.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),y=h,d={success:!1,error:h.message,raw:null}}let T=y??d?.error,$=f.next(T);if(!await pn(this.name,$,T,i))break}return d&&(d.attempts=f.attemptsMade),d}let o;typeof this.prompt=="function"?o=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=ne.compile(this.prompt,{noEscape:!0})),o=this._compiledPrompt(r())):o=this.prompt;let a=s("_skillHints");a&&(o=`${a}
|
|
33
33
|
|
|
34
|
-
${o}`);let l=r(),u=l.cwd||process.cwd(),m=l.sessionPath;try{if(m){let f=gt(m,Q);if(dn(f)){let y=JSON.parse(un(f,"utf-8"));y.currentNode=this.name,ht(f,JSON.stringify(y,null,2),"utf-8")}let d=gt(m,"..",Q);if(dn(d))try{let y=JSON.parse(un(d,"utf-8"));y.currentNode=this.name,ht(d,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(f){A.debug(`[workflow] could not update session info: ${f.message}`)}let p=Me(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${p.attemptsMade-1}`);let f=r().config||{},d=f.agents||{},y=this.config.agent??d[this.name]??null,T={state:r()};y&&(T.preferredAgent=y);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:m,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(ce(),_e))).invokeAgent);let S=await h(o,T,$),E,k;if(typeof S=="string"?(E=S,k=null):S.structured?(E=S.raw||JSON.stringify(S.structured,null,2),k=S.structured):(E=S.raw||JSON.stringify(S,null,2),k=S.extracted||null),m)try{let w=gt(m,this.name,"raw_stream_output.txt");fr(hr(w),{recursive:!0}),ht(w,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(w){A.debug(`[workflow] could not save raw output: ${w.message}`)}if(this.isZodSchema&&k){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(k,null,2)}`);let w=k;if(typeof this.onComplete=="function")try{w=await this.onComplete(r(),k)}catch(g){A.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:w,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(w){throw new Error(`onComplete failed: ${w.message}`,{cause:w})}if(this.parser){let w=this.parser.parse(E);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(w,null,2)}`),C.step("Output parsed"),{success:!0,output:w,raw:E}}return{success:!0,output:E,raw:E}}catch(f){c=f;let d=p.next(f);if(!await pn(this.name,d,f,i))break}return{success:!1,error:c.message,raw:null,attempts:p.attemptsMade}}};Z();Z();import{mkdirSync as Sr,existsSync as oe,statSync as En,readdirSync as Tn,rmSync as _r}from"node:fs";import{spawn as Sn}from"node:child_process";import{join as X}from"node:path";import{pathToFileURL as br}from"node:url";import{AsyncLocalStorage as Er}from"node:async_hooks";import{AsyncLocalStorage as gr}from"node:async_hooks";var be=new gr;function le(){let n=be.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function fn(n,e){let t=be.getStore()||le(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return be.run(r,e)}function hn(n,e,t){let r=be.getStore()||le(),s=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return be.run(s,t)}var mt=new Map,yt=new Map,gn=new Map;function mn(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");mt.set(n,e),yt.set(n,"ready"),gn.set(n,{...t,cachedAt:Date.now()})}function yn(n,e){yt.set(n,"failed"),gn.set(n,{error:e?.message||String(e),failedAt:Date.now()}),mt.delete(n)}function wn(n){return yt.get(n)==="ready"?mt.get(n):null}function Ee(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Ce(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function Te(n,e){return Ce(Ee(n,e),n)}function z(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function V(n,e){return e.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,r)=>{let s=()=>r(e.reason);e.addEventListener("abort",s,{once:!0}),Promise.resolve(n).then(i=>{e.removeEventListener("abort",s),t(i)},i=>{e.removeEventListener("abort",s),r(i)})})}var Be=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Tr(){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 De(n,e,t,r="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,s&&(i.subgraphTransportError=s),i}function Ir(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,o=Number.isFinite(s)&&s>0?s-i:null;if(r===null&&o===null)return null;let a=r===null?o:o===null?r:Math.min(r,o);return Math.max(1,a)}function vr(n,e){let t=new AbortController,r=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>r,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var _n=new Er,bn=Promise.resolve();async function Ar(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let r=_n.getStore()===!0,s=null;if(!r){let o=bn;bn=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return A.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await _n.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function $r(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new B("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function kr({apiBase:n,authToken:e,body:t}){let r=Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(o){throw new B(z(o)?"begin-timeout":"network",z(o)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${o.message}`)}let i=null;try{i=await s.json()}catch(o){if(z(o))throw new B("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!s.ok){if(s.status===404){let o=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(s.status===429){let o=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(s.status===400&&i?.validationErrors){let o=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=i.validationErrors,o.missing=i.missing,o}throw new B("begin-status",`begin returned ${s.status}`)}return i?.data||i}async function re({apiBase:n,authToken:e,payload:t}){let r=Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});s.ok||A.warn(`[in-process subgraph] finalize returned ${s.status} for ${t.childExecutionId}`)}catch(s){A.warn(`[in-process subgraph] finalize ${z(s)?`TIMED OUT ${r.label}`:`failed: ${s.message}`}`)}}async function Nr(n,e){let t=X(e,".ready"),r=X(e,"graph.mjs");if(oe(t)&&oe(r))return;Sr(e,{recursive:!0});let s=X(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),l=o(s,"wx");a(l),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(oe(t)&&oe(r))return;await new Promise(a=>setTimeout(a,100))}throw new B("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let m=Math.ceil(1e4/1e3),p=Math.ceil(Ee("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Sn("curl",["-fsSL","--connect-timeout",String(m),"--max-time",String(p),n],{stdio:["ignore","pipe","inherit"]}),f=Sn("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(f.stdin);let d,y,T=()=>{if(d!==void 0&&y!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};c.on("close",$=>{d=$,T()}),f.on("close",$=>{y=$,T()}),c.on("error",u),f.on("error",u)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new B("bundle-extract-failed",o.message)}}async function Or(n){let e=X(n,"graph.mjs");if(!oe(e))throw new B("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(br(e).href)}catch(s){throw new B("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new B("entry-class-missing","no buildGraph() class export found");return r}async function In(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),r;try{r=$r()}catch(g){throw g}A.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await kr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:m,bundleReady:p,nodeConfigs:c}=s,f=Tr();if(o&&o!==f)throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("runtime-mismatch",`${f} vs ${o}`);if(!p||!a)throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("no-bundle","workflow bundle not built yet");let d=wn(n);if(!d){let g=X(Be,`${m}@${u||"0"}`);try{await Nr(a,g);try{Rr()}catch{}}catch(_){throw _.fallback&&await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{d=await Or(g),mn(n,d,{workflowUuid:m,version:u,runtimeTag:o,cacheDir:g})}catch(_){throw yn(n,_),await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new B("import-failed",_.message)}}let y=Date.now(),T=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...$?{nodeConfigs:c}:{}},S=Ir(e.timeoutMs),E=vr(e.signal,S),k,w;try{k=await Ar(T,async()=>{let _=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return fn({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,h,{signal:E.signal}))}),w=k&&typeof k=="object"&&"state"in k?k.state:k}catch(g){let _=E.timedOut();throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:_?"timeout":"failed",error:_?{message:`aborted at the declared ${Math.round(S/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-y}}),_?De(n,i,S):g}finally{E.dispose()}if(k&&typeof k=="object"&&k.stoppedExternally){let g=E.timedOut();if(await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"canceled",finalState:w,durationMs:Date.now()-y}}),g)throw De(n,i,S);let _=new Error(`Sub-graph '${n}' canceled by parent abort`);throw _.code="SUBGRAPH_CANCELED",_.subgraphJobId=i,_}return await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-y}}),{finalState:w,executionId:i}}function xr(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),s;try{s=En(r)}catch{continue}if(s.isDirectory()){let i;try{i=Tn(r)}catch{continue}for(let o of i)t.push(X(r,o))}else e+=s.size}return e}function Rr({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!oe(Be))return{evicted:0,freedBytes:0};let e=Tn(Be),t=[],r=0;for(let a of e){let l=X(Be,a),u;try{u=En(l)}catch{continue}let m=u.isDirectory()?xr(l):u.size;r+=m,t.push({name:a,full:l,size:m,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,o=0;for(let a of t){if(r-i<=s)break;if(!oe(X(a.full,".lock")))try{_r(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(l){A.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return o>0&&A.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:r-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Pr=2e3,Cr=600*1e3,Br=new Set(["completed","failed","canceled","cancelled","timeout"]);var An=()=>Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Dr(n){let e=Ee("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ce(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function $n(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function kn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Nn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function On(){return process.env.EXECUTION_ID||null}function vn(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Le(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:Cr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w}=await In(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),g=vn(w,e.output);return A.info(`[sub-graph] '${n}' completed in-process`),g}catch(w){if(w instanceof B||w?.fallback)A.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let i=$n(),o=kn(),a=Nn(),l=On(),u=e.participantBindingId?"participant":n,m=`${i}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(u)}/trigger`,p={input:e.input||{},...l?{parentExecutionId:l}:{},...!e.async&&typeof e.output=="string"&&e.output.trim()?{resultPath:e.output.trim()}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};A.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=An(),f;try{f=await V(fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(p),signal:c.signal}),c.signal)}catch(w){if(!z(w))throw w;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=w,g}if(!f.ok){let w=null,g="";try{w=await V(f.json(),c.signal),g=w?.error||w?.message||JSON.stringify(w)}catch{g=await V(f.text(),c.signal).catch(()=>"")}if(f.status===429){let O=w?.quotaInfo||{},x=new Error(`Sub-graph '${n}' blocked by execution quota (${O.used??"?"}/${O.limit??"?"} on plan ${O.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw x.code="SUBGRAPH_QUOTA_EXCEEDED",x.status=429,x.subgraph=n,x.quotaInfo=O,x}if(f.status===400){let O=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw O.code="SUBGRAPH_INVALID_INPUT",O.status=400,O.subgraph=n,O.validationErrors=w?.validationErrors||null,O.missing=w?.missing||null,O}let _=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${g}`);throw _.code="SUBGRAPH_TRIGGER_FAILED",_.status=f.status,_.subgraph=n,_}let d;try{d=await V(f.json(),c.signal)}catch(w){if(!z(w))throw w;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=w,g}let y=d?.data?.jobId||d?.jobId;if(!y)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${y} (not waiting)`),{jobId:y,status:"accepted",workflow:n};let T=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Pr,$=`${i}/executions/${encodeURIComponent(y)}`,h=Date.now()+s,S="accepted",E=0,k=null;for(;Date.now()<h;){await new Promise(x=>setTimeout(x,T)),E+=1;let w=Dr(h),g;try{g=await V(fetch($,{headers:{Authorization:`Bearer ${a}`},signal:w.signal}),w.signal)}catch(x){k=z(x)?`poll TIMED OUT ${w.label}`:x?.message||String(x),A.warn(`[sub-graph] status poll for ${y} could not reach the API (${k}), will retry`);continue}if(!g.ok){if(g.status>=500){A.warn(`[sub-graph] status poll for ${y} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${y}: ${g.status}`)}let _;try{_=await V(g.json(),w.signal)}catch(x){k=z(x)?`poll body read TIMED OUT ${w.label}`:x?.message||String(x),A.warn(`[sub-graph] status poll for ${y} returned an unreadable body (${k}), will retry`);continue}let O=_?.data||_?.execution||_;if(S=O?.status||S,Br.has(S)){if(S!=="completed"){let I=new Error(`Sub-graph '${n}' (${y}) ended in status '${S}'`);throw I.subgraphJobId=y,I.subgraphStatus=S,I}let x=O?.finalState||O?.state||{},N=vn(x,e.output);return A.info(`[sub-graph] '${n}' (${y}) completed after ${E} polls`),N}}try{let w=Ce(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),g=await V(fetch(`${$}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:w.signal}),w.signal);!g.ok&&g.status!==400&&g.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${y} returned ${g.status}`)}catch(w){A.warn(`[sub-graph] best-effort cancel for ${y} failed: ${w?.message||String(w)}`)}throw De(n,y,s,S,k)}async function wt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return Le("participant",{...e,async:e.async!==!1,participantBindingId:n})}async function St(n){if(!n||typeof n!="string")throw new Error("listParticipants: protocolId (string) is required");let e=$n(),t=kn(),r=Nn(),s=On();if(!s){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`,o=An(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:s,protocolId:n}),signal:o.signal})}catch(u){let m=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw m.code=z(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",m.cause=u,m}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 jr=8*6e4,Lr=10*6e4,Ur=2*6e4;function Mn(n=process.env,e=process.uptime()){let t=Number(n?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function xn(n,e,t=Number.MAX_SAFE_INTEGER){let r=Number(n);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),t):e}function Ie(n,e,t={}){return{requested:!0,required:n===!0,observed:!1,status:n===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function Fr(n,e,t){return{participant:n.displayName||n.id,participantId:n.id,vendor:n.vendor||null,phase:e,revision:0,contribution:t}}function Rn(n,e,t){return n.find(r=>Array.isArray(r.roles)&&r.roles.includes(e))||t}var Gr=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function Wr(n,e,t){let r=n;if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}if(!(r&&typeof r=="object"&&!Array.isArray(r)&&r.phase===e&&r.role===t&&r.contextRevision===0&&typeof r.summary=="string"&&Gr.every(i=>Array.isArray(r[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return r}async function _t(n={},e={}){let t=String(n.protocolId||"discuss.v1"),r=String(n.objective||"").trim(),s=String(n.context||""),i=n.required===!0,o=xn(n.timeoutMs,jr,Lr),a=xn(n.reserveMs,Ur,15*6e4),l=(e.remainingWorkflowTimeMs||Mn)();if(!r)return Ie(i,"objective_missing",{protocolId:t});if(l!=null&&l<o+a)return Ie(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:o+a});let u=e.listParticipants||St,m=e.dispatchParticipant||wt,p;try{p=await u(t)}catch(I){return Ie(i,I?.code||"participant_roster_unavailable",{protocolId:t,detail:I?.message||String(I)})}let c=p.filter(I=>I?.available===!1),f=p.filter(I=>I&&I.available!==!1&&I.id);if(f.length===0)return Ie(i,"no_available_participants",{protocolId:t,unavailable:c});let d=Date.now(),y=d+o,T=[],$=[],h=async(I,D,F,$e=[])=>{let de=y-Date.now();if(de<1e3){let K=new Error("Collaboration node exhausted its authored timeout");throw K.code="COLLABORATION_TIMEOUT",K}let v=Number(I?.limits?.maxExecutionMinutes)*6e4,b=Number.isFinite(v)&&v>0?Math.min(de,v):de,j,L=null;for(let K=0;K<2;K+=1){let pe=K===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.":"",He=await m(I.id,{async:!1,protocolId:t,timeoutMs:Math.min(b,Math.max(1e3,y-Date.now())),output:"contribute",input:{objective:r,protocolId:t,phase:D,role:F,contextRevision:0,sharedContext:s,priorContributions:$e,...n.instruction||pe?{instruction:[n.instruction,pe].filter(Boolean).join(`
|
|
35
|
-
`).slice(0,4e3)}:{}}});try{j=
|
|
34
|
+
${o}`);let l=r(),u=l.cwd||process.cwd(),m=l.sessionPath;try{if(m){let f=gt(m,Q);if(dn(f)){let y=JSON.parse(un(f,"utf-8"));y.currentNode=this.name,ht(f,JSON.stringify(y,null,2),"utf-8")}let d=gt(m,"..",Q);if(dn(d))try{let y=JSON.parse(un(d,"utf-8"));y.currentNode=this.name,ht(d,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(f){A.debug(`[workflow] could not update session info: ${f.message}`)}let p=Me(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${p.attemptsMade-1}`);let f=r().config||{},d=f.agents||{},y=this.config.agent??d[this.name]??null,T={state:r()};y&&(T.preferredAgent=y);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:m,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(ce(),_e))).invokeAgent);let _=await h(o,T,$),E,k;if(typeof _=="string"?(E=_,k=null):_.structured?(E=_.raw||JSON.stringify(_.structured,null,2),k=_.structured):(E=_.raw||JSON.stringify(_,null,2),k=_.extracted||null),m)try{let w=gt(m,this.name,"raw_stream_output.txt");fr(hr(w),{recursive:!0}),ht(w,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(w){A.debug(`[workflow] could not save raw output: ${w.message}`)}if(this.isZodSchema&&k){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(k,null,2)}`);let w=k;if(typeof this.onComplete=="function")try{w=await this.onComplete(r(),k)}catch(g){A.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:w,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:E}),raw:E}}catch(w){throw new Error(`onComplete failed: ${w.message}`,{cause:w})}if(this.parser){let w=this.parser.parse(E);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(w,null,2)}`),C.step("Output parsed"),{success:!0,output:w,raw:E}}return{success:!0,output:E,raw:E}}catch(f){c=f;let d=p.next(f);if(!await pn(this.name,d,f,i))break}return{success:!1,error:c.message,raw:null,attempts:p.attemptsMade}}};Z();Z();import{mkdirSync as Sr,existsSync as oe,statSync as En,readdirSync as Tn,rmSync as _r}from"node:fs";import{spawn as Sn}from"node:child_process";import{join as X}from"node:path";import{pathToFileURL as br}from"node:url";import{AsyncLocalStorage as Er}from"node:async_hooks";import{AsyncLocalStorage as gr}from"node:async_hooks";var be=new gr;function le(){let n=be.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function fn(n,e){let t=be.getStore()||le(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return be.run(r,e)}function hn(n,e,t){let r=be.getStore()||le(),s=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return be.run(s,t)}var mt=new Map,yt=new Map,gn=new Map;function mn(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");mt.set(n,e),yt.set(n,"ready"),gn.set(n,{...t,cachedAt:Date.now()})}function yn(n,e){yt.set(n,"failed"),gn.set(n,{error:e?.message||String(e),failedAt:Date.now()}),mt.delete(n)}function wn(n){return yt.get(n)==="ready"?mt.get(n):null}function Ee(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Ce(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function Te(n,e){return Ce(Ee(n,e),n)}function z(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}function V(n,e){return e.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,r)=>{let s=()=>r(e.reason);e.addEventListener("abort",s,{once:!0}),Promise.resolve(n).then(i=>{e.removeEventListener("abort",s),t(i)},i=>{e.removeEventListener("abort",s),r(i)})})}var Be=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Tr(){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 De(n,e,t,r="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,s&&(i.subgraphTransportError=s),i}function Ir(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,o=Number.isFinite(s)&&s>0?s-i:null;if(r===null&&o===null)return null;let a=r===null?o:o===null?r:Math.min(r,o);return Math.max(1,a)}function vr(n,e){let t=new AbortController,r=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>r,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var _n=new Er,bn=Promise.resolve();async function Ar(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let r=_n.getStore()===!0,s=null;if(!r){let o=bn;bn=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return A.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await _n.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function $r(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new B("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function kr({apiBase:n,authToken:e,body:t}){let r=Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(o){throw new B(z(o)?"begin-timeout":"network",z(o)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${o.message}`)}let i=null;try{i=await s.json()}catch(o){if(z(o))throw new B("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!s.ok){if(s.status===404){let o=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(s.status===429){let o=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(s.status===400&&i?.validationErrors){let o=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=i.validationErrors,o.missing=i.missing,o}throw new B("begin-status",`begin returned ${s.status}`)}return i?.data||i}async function re({apiBase:n,authToken:e,payload:t}){let r=Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});s.ok||A.warn(`[in-process subgraph] finalize returned ${s.status} for ${t.childExecutionId}`)}catch(s){A.warn(`[in-process subgraph] finalize ${z(s)?`TIMED OUT ${r.label}`:`failed: ${s.message}`}`)}}async function Nr(n,e){let t=X(e,".ready"),r=X(e,"graph.mjs");if(oe(t)&&oe(r))return;Sr(e,{recursive:!0});let s=X(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),l=o(s,"wx");a(l),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(oe(t)&&oe(r))return;await new Promise(a=>setTimeout(a,100))}throw new B("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let m=Math.ceil(1e4/1e3),p=Math.ceil(Ee("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Sn("curl",["-fsSL","--connect-timeout",String(m),"--max-time",String(p),n],{stdio:["ignore","pipe","inherit"]}),f=Sn("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(f.stdin);let d,y,T=()=>{if(d!==void 0&&y!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};c.on("close",$=>{d=$,T()}),f.on("close",$=>{y=$,T()}),c.on("error",u),f.on("error",u)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new B("bundle-extract-failed",o.message)}}async function xr(n){let e=X(n,"graph.mjs");if(!oe(e))throw new B("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(br(e).href)}catch(s){throw new B("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new B("entry-class-missing","no buildGraph() class export found");return r}async function In(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),r;try{r=$r()}catch(g){throw g}A.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await kr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:m,bundleReady:p,nodeConfigs:c}=s,f=Tr();if(o&&o!==f)throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("runtime-mismatch",`${f} vs ${o}`);if(!p||!a)throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new B("no-bundle","workflow bundle not built yet");let d=wn(n);if(!d){let g=X(Be,`${m}@${u||"0"}`);try{await Nr(a,g);try{Rr()}catch{}}catch(S){throw S.fallback&&await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{d=await xr(g),mn(n,d,{workflowUuid:m,version:u,runtimeTag:o,cacheDir:g})}catch(S){throw yn(n,S),await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new B("import-failed",S.message)}}let y=Date.now(),T=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...$?{nodeConfigs:c}:{}},_=Ir(e.timeoutMs),E=vr(e.signal,_),k,w;try{k=await Ar(T,async()=>{let S=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return fn({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>S.run(e.parentAgent,h,{signal:E.signal}))}),w=k&&typeof k=="object"&&"state"in k?k.state:k}catch(g){let S=E.timedOut();throw await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:S?"timeout":"failed",error:S?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-y}}),S?De(n,i,_):g}finally{E.dispose()}if(k&&typeof k=="object"&&k.stoppedExternally){let g=E.timedOut();if(await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"canceled",finalState:w,durationMs:Date.now()-y}}),g)throw De(n,i,_);let S=new Error(`Sub-graph '${n}' canceled by parent abort`);throw S.code="SUBGRAPH_CANCELED",S.subgraphJobId=i,S}return await re({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-y}}),{finalState:w,executionId:i}}function Or(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),s;try{s=En(r)}catch{continue}if(s.isDirectory()){let i;try{i=Tn(r)}catch{continue}for(let o of i)t.push(X(r,o))}else e+=s.size}return e}function Rr({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!oe(Be))return{evicted:0,freedBytes:0};let e=Tn(Be),t=[],r=0;for(let a of e){let l=X(Be,a),u;try{u=En(l)}catch{continue}let m=u.isDirectory()?Or(l):u.size;r+=m,t.push({name:a,full:l,size:m,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,o=0;for(let a of t){if(r-i<=s)break;if(!oe(X(a.full,".lock")))try{_r(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(l){A.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return o>0&&A.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:r-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Pr=2e3,Cr=600*1e3,Br=new Set(["completed","failed","canceled","cancelled","timeout"]);var An=()=>Te("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Dr(n){let e=Ee("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ce(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function $n(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function kn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Nn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function xn(){return process.env.EXECUTION_ID||null}function jr(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}function vn(n,e,t,r){let s=jr(e,t);return r?{executionId:n,output:s}:s}async function Le(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:Cr;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w,executionId:g}=await In(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),S=vn(g,w,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' completed in-process`),S}catch(w){if(w instanceof B||w?.fallback)A.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let i=$n(),o=kn(),a=Nn(),l=xn(),u=e.participantBindingId?"participant":n,m=`${i}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(u)}/trigger`,p={input:e.input||{},...l?{parentExecutionId:l}:{},...!e.async&&typeof e.output=="string"&&e.output.trim()?{resultPath:e.output.trim()}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};A.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=An(),f;try{f=await V(fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(p),signal:c.signal}),c.signal)}catch(w){if(!z(w))throw w;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=w,g}if(!f.ok){let w=null,g="";try{w=await V(f.json(),c.signal),g=w?.error||w?.message||JSON.stringify(w)}catch{g=await V(f.text(),c.signal).catch(()=>"")}if(f.status===429){let x=w?.quotaInfo||{},O=new Error(`Sub-graph '${n}' blocked by execution quota (${x.used??"?"}/${x.limit??"?"} on plan ${x.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw O.code="SUBGRAPH_QUOTA_EXCEEDED",O.status=429,O.subgraph=n,O.quotaInfo=x,O}if(f.status===400){let x=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw x.code="SUBGRAPH_INVALID_INPUT",x.status=400,x.subgraph=n,x.validationErrors=w?.validationErrors||null,x.missing=w?.missing||null,x}let S=new Error(`Sub-graph '${n}' trigger rejected (${f.status}): ${g}`);throw S.code="SUBGRAPH_TRIGGER_FAILED",S.status=f.status,S.subgraph=n,S}let d;try{d=await V(f.json(),c.signal)}catch(w){if(!z(w))throw w;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=w,g}let y=d?.data?.jobId||d?.jobId;if(!y)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${y} (not waiting)`),{jobId:y,status:"accepted",workflow:n};let T=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Pr,$=`${i}/executions/${encodeURIComponent(y)}`,h=Date.now()+s,_="accepted",E=0,k=null;for(;Date.now()<h;){await new Promise(O=>setTimeout(O,T)),E+=1;let w=Dr(h),g;try{g=await V(fetch($,{headers:{Authorization:`Bearer ${a}`},signal:w.signal}),w.signal)}catch(O){k=z(O)?`poll TIMED OUT ${w.label}`:O?.message||String(O),A.warn(`[sub-graph] status poll for ${y} could not reach the API (${k}), will retry`);continue}if(!g.ok){if(g.status>=500){A.warn(`[sub-graph] status poll for ${y} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${y}: ${g.status}`)}let S;try{S=await V(g.json(),w.signal)}catch(O){k=z(O)?`poll body read TIMED OUT ${w.label}`:O?.message||String(O),A.warn(`[sub-graph] status poll for ${y} returned an unreadable body (${k}), will retry`);continue}let x=S?.data||S?.execution||S;if(_=x?.status||_,Br.has(_)){if(_!=="completed"){let I=new Error(`Sub-graph '${n}' (${y}) ended in status '${_}'`);throw I.subgraphJobId=y,I.subgraphStatus=_,I}let O=x?.finalState||x?.state||{},N=vn(y,O,e.output,e.includeExecutionMetadata===!0);return A.info(`[sub-graph] '${n}' (${y}) completed after ${E} polls`),N}}try{let w=Ce(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),g=await V(fetch(`${$}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:w.signal}),w.signal);!g.ok&&g.status!==400&&g.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${y} returned ${g.status}`)}catch(w){A.warn(`[sub-graph] best-effort cancel for ${y} failed: ${w?.message||String(w)}`)}throw De(n,y,s,_,k)}async function wt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return Le("participant",{...e,async:e.async!==!1,participantBindingId:n})}async function St(n){if(!n||typeof n!="string")throw new Error("listParticipants: protocolId (string) is required");let e=$n(),t=kn(),r=Nn(),s=xn();if(!s){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`,o=An(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:s,protocolId:n}),signal:o.signal})}catch(u){let m=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw m.code=z(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",m.cause=u,m}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 Lr=8*6e4,Ur=10*6e4,Fr=2*6e4;function Mn(n=process.env,e=process.uptime()){let t=Number(n?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function On(n,e,t=Number.MAX_SAFE_INTEGER){let r=Number(n);return Number.isFinite(r)&&r>0?Math.min(Math.floor(r),t):e}function Ie(n,e,t={}){return{requested:!0,required:n===!0,observed:!1,status:n===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function Gr(n,e,t){return{participant:n.displayName||n.id,participantId:n.id,vendor:n.vendor||null,phase:e,revision:0,contribution:t}}function Rn(n,e,t){return n.find(r=>Array.isArray(r.roles)&&r.roles.includes(e))||t}var Wr=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function Hr(n,e,t){let r=n;if(typeof r=="string")try{r=JSON.parse(r)}catch{r=null}if(!(r&&typeof r=="object"&&!Array.isArray(r)&&r.phase===e&&r.role===t&&r.contextRevision===0&&typeof r.summary=="string"&&Wr.every(i=>Array.isArray(r[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return r}async function _t(n={},e={}){let t=String(n.protocolId||"discuss.v1"),r=String(n.objective||"").trim(),s=String(n.context||""),i=n.required===!0,o=On(n.timeoutMs,Lr,Ur),a=On(n.reserveMs,Fr,15*6e4),l=(e.remainingWorkflowTimeMs||Mn)();if(!r)return Ie(i,"objective_missing",{protocolId:t});if(l!=null&&l<o+a)return Ie(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:o+a});let u=e.listParticipants||St,m=e.dispatchParticipant||wt,p;try{p=await u(t)}catch(I){return Ie(i,I?.code||"participant_roster_unavailable",{protocolId:t,detail:I?.message||String(I)})}let c=p.filter(I=>I?.available===!1),f=p.filter(I=>I&&I.available!==!1&&I.id);if(f.length===0)return Ie(i,"no_available_participants",{protocolId:t,unavailable:c});let d=Date.now(),y=d+o,T=[],$=[],h=async(I,D,F,$e=[])=>{let de=y-Date.now();if(de<1e3){let K=new Error("Collaboration node exhausted its authored timeout");throw K.code="COLLABORATION_TIMEOUT",K}let v=Number(I?.limits?.maxExecutionMinutes)*6e4,b=Number.isFinite(v)&&v>0?Math.min(de,v):de,j,L=null;for(let K=0;K<2;K+=1){let pe=K===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.":"",He=await m(I.id,{async:!1,protocolId:t,timeoutMs:Math.min(b,Math.max(1e3,y-Date.now())),output:"contribute",input:{objective:r,protocolId:t,phase:D,role:F,contextRevision:0,sharedContext:s,priorContributions:$e,...n.instruction||pe?{instruction:[n.instruction,pe].filter(Boolean).join(`
|
|
35
|
+
`).slice(0,4e3)}:{}}});try{j=Hr(He,D,F),L=null;break}catch(ke){L=ke}}if(L)throw L;let Y=Gr(I,D,j);return T.push(Y),Y},_=Rn(f,"draft",f[0]),E;try{E=await h(_,"draft","drafter")}catch(I){$.push({participantId:_.id,phase:"draft",code:I?.code||"PARTICIPANT_FAILED",detail:I?.message||String(I)});let D=Ie(i,"draft_failed",{protocolId:t,unavailable:c,failures:$,durationMs:Date.now()-d});return i&&(D.status="incomplete"),D}let k=f.filter(I=>I.id!==_.id);k.length===0&&(k=[_]);let w=await Promise.allSettled(k.map(I=>h(I,"critique","critic",[E]))),g=[];w.forEach((I,D)=>{I.status==="fulfilled"?g.push(I.value):$.push({participantId:k[D].id,phase:"critique",code:I.reason?.code||"PARTICIPANT_FAILED",detail:I.reason?.message||String(I.reason)})});let S=Rn(f,"synthesize",_),x=null;try{x=await h(S,"synthesize","synthesizer",[E,...g])}catch(I){$.push({participantId:S.id,phase:"synthesize",code:I?.code||"PARTICIPANT_FAILED",detail:I?.message||String(I)})}let O=g.length>0&&x!=null,N=(x?.contribution?.decisions||[]).filter(I=>I?.status==="unresolved");return{requested:!0,required:i,observed:O,status:O?"completed":"incomplete",reason:O?null:"required_phase_incomplete",protocolId:t,contributions:T,synthesis:x?.contribution||null,disagreements:N,failures:$,unavailable:c,durationMs:Date.now()-d}}import{existsSync as Pn,readFileSync as zr}from"node:fs";import{join as bt,dirname as Cn}from"node:path";var ve=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Cn(bt(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let m=l.replace(/\.[^.]+$/,"").toLowerCase();s[m]=u}}}let o=r.discovery||{};for(let[a,l]of Object.entries(o))try{let u=bt(t,l);Pn(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let o=bt(i,e);if(Pn(o))try{s.unshift(await this.loadFile(o))}catch(l){console.warn(`[workflow] could not load ${e} from ${o}: ${l.message}`)}let a=Cn(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
`):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=
|
|
39
|
+
`):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=zr(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(e).href);return s.default||s}return t}};import{mkdirSync as jn,existsSync as Et,writeFileSync as Bn,unlinkSync as Jr}from"node:fs";import{join as se,resolve as Ln}from"node:path";import{config as qr}from"dotenv";import{zodToJsonSchema as Dn}from"zod-to-json-schema";import{z as Ue}from"zod";import Yr from"handlebars";function Kr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let o=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${o} sessionId=${e} source=${r} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let m=(new Error("session trace").stack||"").split(`
|
|
40
40
|
`).slice(2,14).join(`
|
|
41
41
|
`);console.log(`[zibby:session] stack (${n}):
|
|
42
|
-
${m}`)}}function Un(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Fn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ln(String(e).trim())}catch{return String(e).trim()}}function Gn(){Un()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Wn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Hn(n={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${r}`:r}function zn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Ln(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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,o="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,o="config.sessionId"):(a=Hn(e),o="generated")}i=i??Date.now();let m=e.paths?.output||ye;s=se(n,m,Ve,a)}let l=!Et(s);return l&&jn(s,{recursive:!0}),(l||o!=="initialState.sessionPath")&&Yr({traceFrom:r,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:l}),Wn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ue=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof H)&&t&&typeof t=="object"&&t.collaboration){let o=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:o.protocolId||"discuss.v1",required:o.required===!0,timeoutMs:o.timeoutMs,reserveMs:o.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let m=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p=(f,d="")=>typeof f=="function"?f(m):f??d,c=await _t({protocolId:o.protocolId,required:o.required,timeoutMs:o.timeoutMs,reserveMs:o.reserveMs,objective:p(o.objective),context:p(o.context),instruction:p(o.instruction)});if(o.required===!0&&c.status!=="completed"){let f=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw f.code="COLLABORATION_REQUIRED_INCOMPLETE",f.collaborationResult=c,f}return c}},l=new H(a);return l.name=e,this.nodes.set(e,l),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}if(!(t instanceof H)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async u=>{let m=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p;return typeof o.input=="function"?p=o.input(m):o.input&&typeof o.input=="object"?p=o.input:p={},Le(o.workflow,{input:p,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:u?.agent})}},l=new H(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=!(t instanceof H)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof H?t:new H(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,r=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&r(o)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,s,i){let o=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=o;o=()=>l(t,u,s,i)}return o()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let f=this.nodeTypeMap.get(p)||(c?.config?._isRouter===!0?"decision":p);e.push({id:p,type:f,data:{nodeType:f,label:p}});let d={};c._isCustomCode&&typeof c.execute=="function"&&(d.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(d.description=y);let T=c?.config?.collaboration;T&&typeof T=="object"&&(d.collaboration={protocolId:T.protocolId||"discuss.v1",required:T.required===!0,...Number.isFinite(T.timeoutMs)?{timeoutMs:T.timeoutMs}:{},...Number.isFinite(T.reserveMs)?{reserveMs:T.reserveMs}:{}});let $=c?.config?.collaborationAsync;$&&typeof $=="object"&&(d.collaborationAsync={protocolId:$.protocolId||"discuss.v1"});let h=this.nodePrompts.get(p);if(h)d.prompt=h;else if(typeof c.prompt=="function")try{let N=c.prompt({});typeof N=="string"&&N.trim()&&(d.prompt=N,d.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(d.executeCode=c.customExecute.toString());let S=c?.config?.dispatchesWorkflow;if(typeof S=="string"&&S.trim())d.dispatchesWorkflow=S.trim();else if(Array.isArray(S)){let N=[...new Set(S.filter(I=>typeof I=="string").map(I=>I.trim()).filter(Boolean))];N.length&&(d.dispatchesWorkflow=N)}let E=c?.config?.minimumReadyChildren;if(E!=null){if(!Number.isInteger(E)||E<=0)throw new Error(`Node '${p}' minimumReadyChildren must be a positive integer`);let N=typeof d.dispatchesWorkflow=="string"?1:Array.isArray(d.dispatchesWorkflow)?d.dispatchesWorkflow.length:0;if(E>N)throw new Error(`Node '${p}' minimumReadyChildren (${E}) exceeds its declared dispatch roster (${N})`);d.minimumReadyChildren=E}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(d.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let N=null;if(typeof Ue?.toJSONSchema=="function")try{N=Ue.toJSONSchema(c.outputSchema)}catch{}if(!N)try{N=Dn(c.outputSchema,{target:"openApi3"})}catch{}d.outputSchema=N?{jsonSchema:N,variables:this._flattenJsonSchemaToVariables(N)}:{schema:c.outputSchema}}else d.outputSchema={schema:c.outputSchema};let k=(this.resolvedToolsMap||{})[p];k?.toolIds&&(d.tools=k.toolIds);let w=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;w&&w.length>0&&(d.skills=[...w]);let g=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;g&&g.length>0&&(d.optionalSkills=[...g]);let _=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;_&&_.length>0&&(d.plugins=_.map(N=>N&&typeof N=="object"?{...N}:N));let O=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;O&&O.length>0&&(d.stores=O.map(N=>N&&typeof N=="object"?{...N}:N));let x=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(x&&x.length>0){let N=new Set,I=[];for(let D of x){let F=typeof D=="string"?D.trim():"";!F||N.has(F)||(N.add(F),I.push(F))}I.length>0&&(d.uses=I)}Object.keys(d).length>0&&(t[p]=d)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(Array.isArray(c))for(let f of c)r.push({source:p,target:f});else if(c.conditional){let f=this.conditionalCodeMap.get(p)||c.routes.toString(),d=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},T=this.nodes.get(p),$=T?.config?._isRouter===!0||this.nodeTypeMap.get(p)==="decision"||!T,h=p;if(!$){let S=`${p}__branch`;e.push({id:S,type:"decision",data:{nodeType:"decision",label:S}}),r.push({source:p,target:S}),h=S}for(let S of d){let E={source:h,target:S,data:{conditionalCode:f}};y[S]&&(E.label=y[S]),r.push(E)}}let s=p=>{if(!p)return null;if(typeof Ue?.toJSONSchema=="function")try{return Ue.toJSONSchema(p)}catch{}try{return Dn(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let p of r)if(p.target==="END"){i+=1;let c=`END__${i}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let o=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:m}}_topoOrderNodes(e,t){let r=new Map(e.map((p,c)=>[p.id,c])),s=new Map(e.map(p=>[p.id,p])),i=new Map(e.map(p=>[p.id,0])),o=new Map(e.map(p=>[p.id,[]]));for(let p of t)o.has(p.source)&&i.has(p.target)&&(o.get(p.source).push(p.target),i.set(p.target,i.get(p.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(p=>i.get(p)===0),m=[];for(;m.length<e.length;){let p;if(u.length>0){if(u.sort((c,f)=>r.get(c)-r.get(f)),p=u.shift(),a.has(p))continue}else p=[...l].sort((c,f)=>r.get(c)-r.get(f))[0];a.add(p),l.delete(p),m.push(s.get(p));for(let c of o.get(p)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return m}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(r))!==null;){let u=o[2]!==void 0?o[2]:o[3];u!==void 0&&u!==""&&s.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 s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=u.exec(r))!==null;)l.add(m[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let l=t?`${t}.${o}`:o;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(v){let b=new Error(`agent.normalizeInput() rejected the trigger input: ${v?.message||v}`);throw b.cause=v,b.code=v?.code||"NORMALIZE_INPUT_FAILED",b}let s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();Jr({path:se(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let v=se(o,".zibby.config.js");Et(v)&&(a=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let v=a?.agent;v?.provider?l=v.provider:v?.gemini?l="gemini":v?.claude?l="claude":v?.cursor?l="cursor":v?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let v=m.safeParse(t);if(!v.success){let b=v.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),b.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${b.join(", ")}`)}C.step("State validated against schema")}let p=Fn(),c=t.sessionPath||p;c||Gn();let{sessionPath:f,sessionTimestamp:d,sessionId:y}=zn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});C.step(`Session ${y}`);let T=await ve.loadContext(t.specPath||"",o,u);Object.keys(T).length>0&&C.step(`Context loaded: ${Object.keys(T).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new fe({...t,config:a,agentType:l,outputPath:$,sessionPath:f,sessionTimestamp:d,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),S=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(Se(),sn)),k=a.skills&&typeof a.skills=="object"?a.skills:{},w=Object.values(k).filter(v=>v&&typeof v=="object"&&typeof v.id=="string"),g=v=>{for(let b of w)if(b.id===v)return b;return E(v)},_=new Set;for(let[,v]of this.nodes)for(let b of v.config?.skills||[])_.add(b);for(let v of _){let b=g(v);if(typeof b?.middleware=="function")try{let j=await b.middleware();typeof j=="function"&&S.set(v,j)}catch{}}let{backEdges:O,joinDegree:x}=this._analyzeFlow(),N=new Map,I=[],D=(v,b,j)=>{if(!v||v==="END")return;let L=x.get(v)||0;if(j&&L>1&&!O.has(`${b}->${v}`)){let Y=(N.get(v)||0)+1;if(Y<L){N.set(v,Y);return}N.set(v,0)}I.includes(v)||I.push(v)};this.entryPoint&&I.push(this.entryPoint);let F=[],$e=a?.recursionLimit??100,de=0;try{for(;I.length>0;){let b=I.pop();if(!b||b==="END")continue;if(++de>$e)throw new Error(`Workflow exceeded recursion limit (${$e}) \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 j=se(f,Xe);if(Et(j)){try{zr(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
43
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),C.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:F,stoppedExternally:!0};let L=this.nodes.get(b);if(!L)throw new Error(`Node '${b}' not found in graph`);let Y=JSON.stringify({sessionPath:f,sessionTimestamp:d,currentNode:b,createdAt:new Date().toISOString(),config:h.get("config")}),K=se(f,Q);Bn(K,Y,"utf-8");let pe=h.get("config")?.paths?.output||ye,He=se(o,pe,Q);jn(se(o,pe),{recursive:!0});try{Bn(He,Y,"utf-8")}catch{}let ke=t.onPipelineProgress;if(typeof ke=="function")try{ke({cwd:o,sessionPath:f,sessionId:y,outputBase:h.get("config")?.paths?.output||ye,currentNode:b})}catch{}let Kn=(this.resolvedToolsMap||{})[b]||null;h.set("_currentNodeTools",Kn);let Zn=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Zn[b]||{}),C.nodeStart(b);let Nt=Date.now(),Ne=this.nodePrompts.get(b);if(!this._invokeAgent){let M=await Promise.resolve().then(()=>(ce(),_e));this._invokeAgent=M.invokeAgent}let Vn=this._invokeAgent,ze={},Xn=L.config?.skills||[];for(let M of Xn){let U=g(M);if(typeof U?.invokeAgentOptions=="function")try{let R=U.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:b});R&&typeof R=="object"&&(ze={...ze,...R})}catch(R){console.warn(`[graph] skill '${M}' invokeAgentOptions threw: ${R.message}`)}}let
|
|
42
|
+
${m}`)}}function Un(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Fn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ln(String(e).trim())}catch{return String(e).trim()}}function Gn(){Un()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Wn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Hn(n={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${r}`:r}function zn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Ln(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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,o="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,o="config.sessionId"):(a=Hn(e),o="generated")}i=i??Date.now();let m=e.paths?.output||ye;s=se(n,m,Ve,a)}let l=!Et(s);return l&&jn(s,{recursive:!0}),(l||o!=="initialState.sessionPath")&&Kr({traceFrom:r,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:l}),Wn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ue=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof H)&&t&&typeof t=="object"&&t.collaboration){let o=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:o.protocolId||"discuss.v1",required:o.required===!0,timeoutMs:o.timeoutMs,reserveMs:o.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let m=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p=(f,d="")=>typeof f=="function"?f(m):f??d,c=await _t({protocolId:o.protocolId,required:o.required,timeoutMs:o.timeoutMs,reserveMs:o.reserveMs,objective:p(o.objective),context:p(o.context),instruction:p(o.instruction)});if(o.required===!0&&c.status!=="completed"){let f=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw f.code="COLLABORATION_REQUIRED_INCOMPLETE",f.collaborationResult=c,f}return c}},l=new H(a);return l.name=e,this.nodes.set(e,l),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}if(!(t instanceof H)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async u=>{let m=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p;return typeof o.input=="function"?p=o.input(m):o.input&&typeof o.input=="object"?p=o.input:p={},Le(o.workflow,{input:p,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:u?.agent})}},l=new H(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=!(t instanceof H)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof H?t:new H(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,r=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&r(o)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,s,i){let o=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=o;o=()=>l(t,u,s,i)}return o()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let f=this.nodeTypeMap.get(p)||(c?.config?._isRouter===!0?"decision":p);e.push({id:p,type:f,data:{nodeType:f,label:p}});let d={};c._isCustomCode&&typeof c.execute=="function"&&(d.customCode=c.execute.toString());let y=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;y&&(d.description=y);let T=c?.config?.collaboration;T&&typeof T=="object"&&(d.collaboration={protocolId:T.protocolId||"discuss.v1",required:T.required===!0,...Number.isFinite(T.timeoutMs)?{timeoutMs:T.timeoutMs}:{},...Number.isFinite(T.reserveMs)?{reserveMs:T.reserveMs}:{}});let $=c?.config?.collaborationAsync;$&&typeof $=="object"&&(d.collaborationAsync={protocolId:$.protocolId||"discuss.v1"});let h=this.nodePrompts.get(p);if(h)d.prompt=h;else if(typeof c.prompt=="function")try{let N=c.prompt({});typeof N=="string"&&N.trim()&&(d.prompt=N,d.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(d.executeCode=c.customExecute.toString());let _=c?.config?.dispatchesWorkflow;if(typeof _=="string"&&_.trim())d.dispatchesWorkflow=_.trim();else if(Array.isArray(_)){let N=[...new Set(_.filter(I=>typeof I=="string").map(I=>I.trim()).filter(Boolean))];N.length&&(d.dispatchesWorkflow=N)}let E=c?.config?.minimumReadyChildren;if(E!=null){if(!Number.isInteger(E)||E<=0)throw new Error(`Node '${p}' minimumReadyChildren must be a positive integer`);let N=typeof d.dispatchesWorkflow=="string"?1:Array.isArray(d.dispatchesWorkflow)?d.dispatchesWorkflow.length:0;if(E>N)throw new Error(`Node '${p}' minimumReadyChildren (${E}) exceeds its declared dispatch roster (${N})`);d.minimumReadyChildren=E}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(d.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let N=null;if(typeof Ue?.toJSONSchema=="function")try{N=Ue.toJSONSchema(c.outputSchema)}catch{}if(!N)try{N=Dn(c.outputSchema,{target:"openApi3"})}catch{}d.outputSchema=N?{jsonSchema:N,variables:this._flattenJsonSchemaToVariables(N)}:{schema:c.outputSchema}}else d.outputSchema={schema:c.outputSchema};let k=(this.resolvedToolsMap||{})[p];k?.toolIds&&(d.tools=k.toolIds);let w=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;w&&w.length>0&&(d.skills=[...w]);let g=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;g&&g.length>0&&(d.optionalSkills=[...g]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(d.plugins=S.map(N=>N&&typeof N=="object"?{...N}:N));let x=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;x&&x.length>0&&(d.stores=x.map(N=>N&&typeof N=="object"?{...N}:N));let O=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(O&&O.length>0){let N=new Set,I=[];for(let D of O){let F=typeof D=="string"?D.trim():"";!F||N.has(F)||(N.add(F),I.push(F))}I.length>0&&(d.uses=I)}Object.keys(d).length>0&&(t[p]=d)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(Array.isArray(c))for(let f of c)r.push({source:p,target:f});else if(c.conditional){let f=this.conditionalCodeMap.get(p)||c.routes.toString(),d=this._inferConditionalTargets(c.routes,c.labels),y=c.labels||{},T=this.nodes.get(p),$=T?.config?._isRouter===!0||this.nodeTypeMap.get(p)==="decision"||!T,h=p;if(!$){let _=`${p}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),r.push({source:p,target:_}),h=_}for(let _ of d){let E={source:h,target:_,data:{conditionalCode:f}};y[_]&&(E.label=y[_]),r.push(E)}}let s=p=>{if(!p)return null;if(typeof Ue?.toJSONSchema=="function")try{return Ue.toJSONSchema(p)}catch{}try{return Dn(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let p of r)if(p.target==="END"){i+=1;let c=`END__${i}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let o=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:m}}_topoOrderNodes(e,t){let r=new Map(e.map((p,c)=>[p.id,c])),s=new Map(e.map(p=>[p.id,p])),i=new Map(e.map(p=>[p.id,0])),o=new Map(e.map(p=>[p.id,[]]));for(let p of t)o.has(p.source)&&i.has(p.target)&&(o.get(p.source).push(p.target),i.set(p.target,i.get(p.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(p=>i.get(p)===0),m=[];for(;m.length<e.length;){let p;if(u.length>0){if(u.sort((c,f)=>r.get(c)-r.get(f)),p=u.shift(),a.has(p))continue}else p=[...l].sort((c,f)=>r.get(c)-r.get(f))[0];a.add(p),l.delete(p),m.push(s.get(p));for(let c of o.get(p)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return m}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(r))!==null;){let u=o[2]!==void 0?o[2]:o[3];u!==void 0&&u!==""&&s.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 s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=u.exec(r))!==null;)l.add(m[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let l=t?`${t}.${o}`:o;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(v){let b=new Error(`agent.normalizeInput() rejected the trigger input: ${v?.message||v}`);throw b.cause=v,b.code=v?.code||"NORMALIZE_INPUT_FAILED",b}let s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();qr({path:se(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let v=se(o,".zibby.config.js");Et(v)&&(a=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let v=a?.agent;v?.provider?l=v.provider:v?.gemini?l="gemini":v?.claude?l="claude":v?.cursor?l="cursor":v?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let v=m.safeParse(t);if(!v.success){let b=v.error.issues.map(j=>`${j.path.join(".")}: ${j.message}`);throw console.error("\u274C Initial state validation failed:"),b.forEach(j=>console.error(` - ${j}`)),new Error(`State validation failed: ${b.join(", ")}`)}C.step("State validated against schema")}let p=Fn(),c=t.sessionPath||p;c||Gn();let{sessionPath:f,sessionTimestamp:d,sessionId:y}=zn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});C.step(`Session ${y}`);let T=await ve.loadContext(t.specPath||"",o,u);Object.keys(T).length>0&&C.step(`Context loaded: ${Object.keys(T).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new fe({...t,config:a,agentType:l,outputPath:$,sessionPath:f,sessionTimestamp:d,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(Se(),sn)),k=a.skills&&typeof a.skills=="object"?a.skills:{},w=Object.values(k).filter(v=>v&&typeof v=="object"&&typeof v.id=="string"),g=v=>{for(let b of w)if(b.id===v)return b;return E(v)},S=new Set;for(let[,v]of this.nodes)for(let b of v.config?.skills||[])S.add(b);for(let v of S){let b=g(v);if(typeof b?.middleware=="function")try{let j=await b.middleware();typeof j=="function"&&_.set(v,j)}catch{}}let{backEdges:x,joinDegree:O}=this._analyzeFlow(),N=new Map,I=[],D=(v,b,j)=>{if(!v||v==="END")return;let L=O.get(v)||0;if(j&&L>1&&!x.has(`${b}->${v}`)){let Y=(N.get(v)||0)+1;if(Y<L){N.set(v,Y);return}N.set(v,0)}I.includes(v)||I.push(v)};this.entryPoint&&I.push(this.entryPoint);let F=[],$e=a?.recursionLimit??100,de=0;try{for(;I.length>0;){let b=I.pop();if(!b||b==="END")continue;if(++de>$e)throw new Error(`Workflow exceeded recursion limit (${$e}) \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 j=se(f,Xe);if(Et(j)){try{Jr(j)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
43
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),C.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:F,stoppedExternally:!0};let L=this.nodes.get(b);if(!L)throw new Error(`Node '${b}' not found in graph`);let Y=JSON.stringify({sessionPath:f,sessionTimestamp:d,currentNode:b,createdAt:new Date().toISOString(),config:h.get("config")}),K=se(f,Q);Bn(K,Y,"utf-8");let pe=h.get("config")?.paths?.output||ye,He=se(o,pe,Q);jn(se(o,pe),{recursive:!0});try{Bn(He,Y,"utf-8")}catch{}let ke=t.onPipelineProgress;if(typeof ke=="function")try{ke({cwd:o,sessionPath:f,sessionId:y,outputBase:h.get("config")?.paths?.output||ye,currentNode:b})}catch{}let Kn=(this.resolvedToolsMap||{})[b]||null;h.set("_currentNodeTools",Kn);let Zn=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Zn[b]||{}),C.nodeStart(b);let Nt=Date.now(),Ne=this.nodePrompts.get(b);if(!this._invokeAgent){let M=await Promise.resolve().then(()=>(ce(),_e));this._invokeAgent=M.invokeAgent}let Vn=this._invokeAgent,ze={},Xn=L.config?.skills||[];for(let M of Xn){let U=g(M);if(typeof U?.invokeAgentOptions=="function")try{let R=U.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:b});R&&typeof R=="object"&&(ze={...ze,...R})}catch(R){console.warn(`[graph] skill '${M}' invokeAgentOptions threw: ${R.message}`)}}let xt=async(M,U,R={})=>{let G=Vn(M,U,{...ze,...R,signal:s.signal});return G.catch(()=>{}),s.signal.aborted?G:Promise.race([G,new Promise((ie,q)=>{let W=()=>{setTimeout(()=>{let Mt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Mt.name="AbortError",q(Mt)},i)};s.signal.addEventListener("abort",W,{once:!0})})])},Qn=async(M={},U={})=>{let R=U.prompt||"";if(Ne){let G=this._compiledPrompts.get(b);G||(G=Yr.compile(Ne,{noEscape:!0}),this._compiledPrompts.set(b,G));try{R=G(M)}catch(ie){throw console.error(`\u274C Template rendering failed for node '${b}':`,ie.message),new Error(`Template rendering failed: ${ie.message}`,{cause:ie})}}else if(!R)throw new Error(`No prompt template configured for node '${b}' and no prompt provided in options`);return xt(R,{state:h.getAll(),images:U.images||[]},{model:U.model||h.get("model"),workspace:h.get("workspace"),schema:U.schema,...U,signal:s.signal,nodeName:b})},Ot=h.getAll(),er=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let M of er)Object.prototype.hasOwnProperty.call(Ot,M)&&console.warn(`[workflow] node "${b}": state key "${M}" is shadowed by the engine context prop; read it via context.state.get('${M}')`);let Rt={...Ot,state:h,invokeAgent:Qn,_coreInvokeAgent:xt,agent:e,nodeId:b,promptTemplate:Ne,getPromptTemplate:()=>Ne};try{let M=(L.config?.skills||[]).map(W=>_.get(W)).filter(Boolean),U=[...this.middleware,...M],R;R=await hn(e,s.signal,async()=>U.length>0?this._composeMiddleware(U,b,async()=>L.execute(Rt,h),h.getAll(),h):L.execute(Rt,h));let G=Date.now()-Nt;if(F.push({node:b,success:R.success,duration:G,timestamp:new Date().toISOString()}),!R.success){if(s.signal.aborted)return C.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:F,stoppedExternally:!0};h.append("errors",{node:b,error:R.error});let W=Number.isInteger(R.attempts)&&R.attempts>0?R.attempts:(L.config?.retries||0)+1;throw C.nodeFailed(b,R.error,{duration:G}),new Error(`Node '${b}' failed after ${W} attempt(s): ${R.error}`)}h.update({[b]:R.output});let ie=this._summarizeNodeOutput(b,R.output);C.nodeComplete(b,{duration:G,details:ie});let q=this.edges.get(b);if(q)if(q.conditional){let W=q.routes(h.getAll());C.route(b,W),D(W,b,!1)}else if(Array.isArray(q))for(let W=q.length-1;W>=0;W--)D(q[W],b,!0);else D(q,b,!0)}catch(M){throw C.isInsideNode&&C.nodeFailed(b,M.message,{duration:Date.now()-Nt}),h.set("failed",!0),h.set("failedAt",b),M}}C.graphComplete();let v={success:!0,state:h.getAll(),executionLog:F};return e&&typeof e.onComplete=="function"&&await e.onComplete(v),v}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(v){console.warn(`[workflow] agent.cleanup() failed: ${v.message}`)}}}};var Tt=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Tt]||(globalThis[Tt]=new Map);var Ae=globalThis[Tt];function Jn(n,e){Ae.set(n,e)}function It(n){return Ae.get(n)}function Fe(n){return Ae.has(n)}function Zr(){return Array.from(Ae.keys())}function vt(n){let e=Ae.get(n);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Jn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(ce(),_e))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=Vr(s,t),o=await r(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:o,nodeId:n},raw:typeof o=="string"?o:o.raw}}})});function Vr(n,e){let t=/@([\w.]+)/g,r=new Set,s;for(;(s=t.exec(n))!==null;)r.add(s[1]);if(r.size===0)return n;let i=[],o=new Set;for(let a of r){let l=a.split(".")[0];if(o.has(l))continue;let u=a.split(".").reduce((c,f)=>c?.[f],e);if(u===void 0)continue;let m=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),p=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${p}
|
|
44
44
|
${m}`),a.includes(".")||o.add(l)}return i.length===0?n:`${n}
|
|
45
45
|
|
|
46
46
|
---
|
|
@@ -48,16 +48,16 @@ ${m}`),a.includes(".")||o.add(l)}return i.length===0?n:`${n}
|
|
|
48
48
|
|
|
49
49
|
${i.join(`
|
|
50
50
|
|
|
51
|
-
`)}`}Se();Z();var Ge={};function $t(n,e){if(Array.isArray(e))return At(e);let t=Ge[n];return!t||t.length===0?null:At(t)}function At(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let s of n){let i=ae(s);if(!i){A.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let o of i.tools||[])e.push({name:o.name,description:o.description,input_schema:o.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let o=i.resolve();o&&(t[i.serverName]={...o,toolPrefix:s})}else{let o={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(o[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:o,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}Z();function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`)}function
|
|
51
|
+
`)}`}Se();Z();var Ge={};function $t(n,e){if(Array.isArray(e))return At(e);let t=Ge[n];return!t||t.length===0?null:At(t)}function At(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let s of n){let i=ae(s);if(!i){A.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let o of i.tools||[])e.push({name:o.name,description:o.description,input_schema:o.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let o=i.resolve();o&&(t[i.serverName]={...o,toolPrefix:s})}else{let o={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(o[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:o,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}Z();function Xr(n,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=n;if(!Array.isArray(t)||t.length===0)throw new J("Graph must have at least one node");if(!Array.isArray(r))throw new J("Graph edges must be an array");let i=new ue(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let o=new Set,a=new Map,l={};for(let c of t){let f=We(c);a.set(c.id,{...c,resolvedType:f}),f==="decision"&&o.add(c.id)}for(let[c,f]of a){if(o.has(c))continue;let d=f.resolvedType,y=s[c]||{},T=$t(d,y.tools);T&&(l[c]=T);let $={};y.prompt&&($.prompt=y.prompt);let h=Fe(d);if(A.debug(`[workflow] compiler: node "${c}" type="${d}" registered=${h}`),y.customCode&&!h)i.addNode(c,qn(c,y.customCode,y),$),i.setNodeType(c,d);else if(h){let _=It(d);_.factory?i.addNode(c,_.create(c,{...y,resolvedTools:T}),$):i.addNode(c,_,$),i.setNodeType(c,d)}else if(y.executeCode)i.addNode(c,qn(c,y.executeCode,y),$),i.setNodeType(c,d);else throw new J(`Unknown node type "${d}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of r)o.has(c.target)||u.add(c.target);let m=t.find(c=>!o.has(c.id)&&!u.has(c.id));if(!m)throw new J("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(m.id);let p=to(r,"source");for(let c of r)if(!o.has(c.source))if(o.has(c.target)){let f=c.target,d=p.get(f)||[];if(d.length===0)throw new J(`Decision node "${f}" has no outgoing edges`);let y=no(f,d,o);i.addConditionalEdges(c.source,y)}else i.addEdge(c.source,c.target);return i}function Qr(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let l=We(a);if(l==="decision"||Fe(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(n.nodes.filter(a=>We(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)s.has(a.target)||i.add(a.target);let o=n.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));o.length===0?e.push("No entry point found (every node has incoming edges)"):o.length>1&&e.push(`Multiple entry points found: ${o.map(a=>a.id).join(", ")}`);for(let a of s){let l=n.edges.filter(m=>m.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(m=>m.data?.conditionalCode||m.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function eo(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>We(e)!=="decision").map(e=>e.id)}function We(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function to(n,e){let t=new Map;for(let r of n){let s=r[e];t.has(s)||t.set(s,[]),t.get(s).push(r)}return t}function no(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new J(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let s=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),o;try{let l=new Function(`return (${s})`)();o=u=>{let m=l(u);return i.has(m)||A.warn(`[workflow] conditional route from "${n}" returned "${m}" which is not in valid targets: ${[...i].join(", ")}`),m}}catch(a){throw new J(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return o}function qn(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(o){throw new J(`Failed to compile customCode for node "${n}": ${o.message}`)}let s=r(async(...o)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ce(),_e));return a(...o)},typeof Je<"u"?Je:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async o=>{try{let a=await s(o);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var J=class extends Error{constructor(e){super(e),this.name="CompilationError"}};Se();var kt=/^[a-z][a-z0-9_]{0,40}$/;function ro(n){if(n==null)return[];if(!Array.isArray(n))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return n.forEach((r,s)=>{if(r==null||typeof r!="object"||Array.isArray(r)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=r;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}kt.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${kt} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}it();ce();function oo(n,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=n,i=new Set,o=[],a=new Map;for(let T of t){let $=T.data?.nodeType||T.type;a.set(T.id,$),$==="decision"?i.add(T.id):o.push({id:T.id,nodeType:$,label:T.data?.label||T.id})}let l=o.some(T=>{let $=s[T.id]||{};return!$.customCode&&!$.executeCode}),{toolsPerNode:u,toolIdsByVar:m}=fo(o,s),{simpleEdges:p,conditionalEdges:c}=ho(r,i),f=go(o,r,i),d=[],y=e.workflowType||"workflow";return d.push(io(e)),d.push(ao(y,{usesRegisteredNodes:l})),d.push(co(m)),d.push(lo(y)),d.push(uo(o,s)),d.push(po(o,f,p,c,u,y)),d.filter(Boolean).join(`
|
|
52
|
+
`)}function so(n){let e={};for(let[t,r]of Object.entries(n)){let{tools:s,...i}=r;Object.keys(i).length>0&&(e[t]=i)}return e}function io(n){let e=n.workflowType||"workflow";return["// Generated workflow",`// ${n.projectId?`Project: ${n.projectId} | `:""}Type: ${e} | Version: ${n.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
53
|
+
`)}function ao(n,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
54
|
+
`)}function co(n){if(n.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,r]of n)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return e.push(""),e.join(`
|
|
55
|
+
`)}function lo(n){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${n}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
56
|
+
`)}function uo(n,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let r of n){let s=Yn(r.id),i=e[r.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),t.push(`const ${s}_execute = ${i};`);else{let o=vt(r.nodeType);o?(t.push(`// Default "${r.nodeType}" implementation`),t.push(`const ${s}_execute = ${o};`)):(t.push(`// No template for "${r.nodeType}" \u2014 passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
57
|
+
`)}function po(n,e,t,r,s,i){let o=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];o.push("export function buildGraph(options = {}) {"),o.push(" const graph = new WorkflowGraph(options);",""),o.push(" // Nodes");for(let l of n){let u=Yn(l.id);o.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),o.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}o.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||r.length>0)&&o.push(" // Edges");for(let l of t)o.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of r){let u=l.code.split(`
|
|
58
58
|
`).map((m,p)=>p===0?m:` ${m}`).join(`
|
|
59
59
|
`);o.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of n){let u=s.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&o.push(""," graph.resolvedToolsMap = {",...a," };"),o.push(""," return graph;","}",""),o.push("export { nodeConfigs };",""),o.join(`
|
|
60
|
-
`)}function
|
|
60
|
+
`)}function fo(n,e){let t=new Map,r=new Map;for(let s of n){let i=e[s.id]?.tools,o;if(Array.isArray(i)&&i.length>0)o=[...i].sort();else{let a=Ge[s.nodeType];a?.length>0&&(o=[...a].sort())}if(o){let a=`${o.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),r.has(a)||r.set(a,o)}}return{toolsPerNode:t,toolIdsByVar:r}}function ho(n,e){let t=[],r=[],s=new Map,i=new Set;for(let o of n)s.has(o.source)||s.set(o.source,[]),s.get(o.source).push(o);for(let o of n)if(!e.has(o.source))if(e.has(o.target)){if(i.has(o.target))continue;i.add(o.target);let l=(s.get(o.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&r.push({source:o.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:o.source,target:o.target});return{simpleEdges:t,conditionalEdges:r}}function go(n,e,t){let r=new Set;for(let i of e)t.has(i.target)||r.add(i.target);let s=n.find(i=>!r.has(i.id));return s?s.id:n[0]?.id}function Yn(n){return n.replace(/[^a-zA-Z0-9]/g,"_")}Z();var mo=`## Composing deployed agents (wrapper over marketplace bricks)
|
|
61
61
|
|
|
62
62
|
**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
|
|
63
63
|
modify a brick template's source and never rebuild its logic from scratch.
|
|
@@ -126,4 +126,4 @@ template workflow.json) and paste the exact array. The platform then
|
|
|
126
126
|
automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
|
|
127
127
|
listed in a deployed wrapper's composedOf stops receiving standalone webhook
|
|
128
128
|
events), so the same event never double-fires a brick inside AND outside the
|
|
129
|
-
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{st as AgentStrategy,Qe as CI_ENV_VARS,
|
|
129
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{st as AgentStrategy,Qe as CI_ENV_VARS,mo as COMPOSE_KNOWLEDGE,J as CompilationError,ve as ContextLoader,ye as DEFAULT_OUTPUT_BASE,Re as DEFAULT_TRANSIENT_BACKOFF_MS,et as DEFAULT_TRANSIENT_RETRIES,Pe as EFFORT_LEVELS,cr as EVENTS_FILE,ue as Graph,ot as MAX_TRANSIENT_BACKOFF_MS,Zt as MAX_TRANSIENT_RETRIES,Ge as NODE_DEFAULT_TOOLS,lr as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,H as Node,he as OutputParser,zt as PROVIDER_ERROR_KIND_CLASS,ar as RAW_OUTPUT_FILE,ir as RESULT_FILE,Ve as SESSIONS_DIR,Q as SESSION_INFO_FILE,Xe as STOP_REQUEST_FILE,kt as STORE_NAME_REGEX,rr as SchemaTypes,Jt as TRANSIENT_MESSAGE_PATTERNS,Oe as Timeline,Ht as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ue as WorkflowGraph,fe as WorkflowState,rt as classifyFailure,Gn as clearInheritedSessionEnvForFreshRun,on as clearSkills,Xr as compileGraph,Me as createAttemptBudget,wt as dispatchParticipant,Le as dispatchSubgraph,eo as extractSteps,dr as formatProviderError,so as generateNodeConfigsJson,oo as generateWorkflowCode,Hn as generateWorkflowSessionId,ft as getAgentStrategy,nn as getAllSkills,It as getNodeImpl,vt as getNodeTemplate,At as getResolvedToolDefinitions,ae as getSkill,tn as getSkillSource,Fe as hasNode,en as hasSkill,ln as invokeAgent,pr as isTransientFailure,Zr as listNodeTypes,St as listParticipants,rn as listSkillIds,cn as listStrategies,Yt as providerErrorKindOf,Kt as providerErrorStatusOf,Fn as readPinnedSessionPathFromEnv,Jn as registerNode,Qt as registerSkill,an as registerStrategy,Mn as remainingWorkflowTimeMs,dt as resolveInvocationEffort,pt as resolveInvocationExtras,ut as resolveInvocationModel,$t as resolveNodeTools,zn as resolveWorkflowSession,_t as runCollaboration,or as setLogger,Un as shouldTrustInheritedSessionEnv,Wn as syncProcessEnvToSession,C as timeline,Xt as transientBackoffBaseMs,tt as transientBackoffMs,Vt as transientRetryBudget,Qr as validateGraphConfig,ro as validateStoreDefs};
|
|
@@ -68,10 +68,16 @@ export { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS };
|
|
|
68
68
|
* On the HTTP path, a string is also sent as `resultPath` so the
|
|
69
69
|
* control plane can persist only that declared result before applying
|
|
70
70
|
* its final-state size cap. Function extractors remain local-only.
|
|
71
|
+
* @param {boolean} [options.includeExecutionMetadata=false]
|
|
72
|
+
* Sync mode only. Return `{ executionId, output }`, where `output` is the
|
|
73
|
+
* same projected value this call would otherwise return. This exposes the
|
|
74
|
+
* child identity the dispatcher already owns without making callers infer
|
|
75
|
+
* it from process-global environment or query the execution list.
|
|
71
76
|
*
|
|
72
77
|
* @returns {Promise<any>}
|
|
73
78
|
* async: `{ jobId, status: 'accepted' }`
|
|
74
|
-
* sync : the child's final state (or `getPath(state, output)`)
|
|
79
|
+
* sync : the child's final state (or `getPath(state, output)`), optionally
|
|
80
|
+
* wrapped as `{ executionId, output }`
|
|
75
81
|
*
|
|
76
82
|
* @throws {Error}
|
|
77
83
|
* - Network / 5xx errors from the trigger endpoint
|