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