@zibby/agent-workflow 2.0.6 → 2.0.8
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/code-generator.js +17 -17
- package/dist/graph-compiler.js +21 -21
- package/dist/graph.js +20 -20
- package/dist/index.d.ts +1 -1
- package/dist/index.js +32 -32
- package/dist/node-registry.js +10 -10
- package/dist/node.js +18 -18
- package/dist/strategy-registry.d.ts +16 -0
- package/dist/strategy-registry.js +6 -6
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
var
|
|
1
|
+
var en=Object.defineProperty;var ue=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var Qe=(n,e)=>{for(var t in e)en(n,t,{get:e[t],enumerable:!0})};var et,nn,Ie,fe,I,ne=ue(()=>{et=()=>{},nn={debug:et,info:et,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Ie=Symbol.for("@zibby/agent-workflow.logger");globalThis[Ie]||(globalThis[Ie]={impl:nn});fe=globalThis[Ie],I={debug:(...n)=>fe.impl.debug?.(...n),info:(...n)=>fe.impl.info?.(...n),warn:(...n)=>fe.impl.warn?.(...n),error:(...n)=>fe.impl.error?.(...n)}});var gt=ue(()=>{});var mt={};Qe(mt,{clearSkills:()=>wn,getAllSkills:()=>Sn,getSkill:()=>Me,getSkillSource:()=>yn,hasSkill:()=>mn,listSkillIds:()=>_n,registerSkill:()=>gn});function gn(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,o=n.id;if(J.has(o)&&!r){let i=oe.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}J.set(o,Object.freeze({...n})),t===void 0?oe.delete(o):oe.set(o,t)}function Me(n){return J.get(n)||null}function mn(n){return J.has(n)}function yn(n){return oe.get(n)||null}function Sn(){return new Map(J)}function _n(){return Array.from(J.keys())}function wn(){J.clear(),oe.clear()}var ke,Re,J,oe,Pe=ue(()=>{ke=Symbol.for("@zibby/agent-workflow.skills"),Re=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[ke]||(globalThis[ke]=new Map);globalThis[Re]||(globalThis[Re]=new Map);J=globalThis[ke],oe=globalThis[Re]});var Ce={};Qe(Ce,{EFFORT_LEVELS:()=>Be,getAgentStrategy:()=>wt,invokeAgent:()=>In,listStrategies:()=>En,registerStrategy:()=>bn,resolveInvocationEffort:()=>St,resolveInvocationExtras:()=>_t,resolveInvocationModel:()=>yt});function bn(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=z.findIndex(t=>t.getName()===n.getName());e>=0?z[e]=n:z.push(n)}function En(){return z.map(n=>n.getName())}function yt({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:o}={}){let i=n.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,d=n.agent?.[t]?.model||null,E=(typeof r=="string"?r.trim():"")||null;return s||a||l||d||e.model||E||null}function St({options:n={},envEffort:e,nodeConfigEffort:t}={}){let r=[t,n.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return r?Be.indexOf(r)===-1?(I.warn(`[workflow] ignoring unknown effort "${r}" \u2014 expected one of ${Be.join(", ")}`),null):r:null}function _t({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 wt(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${r}`);let o=z.find(i=>i.getName()===r);if(!o){let i=z.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${o.getName()}`),o}async function In(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:r},i=wt(o),s=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",d=!l||l===i.name?a.model:null,E=yt({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:d}),u=!l||l===i.name?a.effort:null,c=St({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:u}),_={...t,model:E,...c?{effort:c}:{},..._t({options:t,stateView:r,context:e}),config:s},p=n,A=_.skills||[];if(A.length>0&&!t.skipPromptFragments){let h=t.connectedIntegrations;if(!h){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){h={};for(let g of f.split(",").map($=>$.trim()).filter(Boolean))h[g]=!0}}let T=f=>{let g=f&&f.requiresIntegration;return!g||!h?!0:(Array.isArray(g)?g:[g]).some(N=>h[N]===!0)},w=i.name==="assistant",y=f=>f?.inProcessOnly!==!0||w,m=A.map(f=>{let g=Me(f);if(!T(g)||!y(g))return null;let $=g?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);m.length>0&&(p+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${m.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let v=r._currentNodeConfig?.stores;if(Array.isArray(v)&&v.length>0&&typeof v[0]=="object"){let h=v.length<=8,T=v.map(w=>{let y=w?.id??w?.storeId??"",m=(w?.name??"").toString().trim()||y,f=w?.type?` \xB7 ${w.type}`:"",g=(w?.description||"").toString().replace(/\s+/g," ").trim(),$=`- ${m} \xB7 ${g||"(no description)"}${f} (id: ${y})`;if(h&&w?.schema&&typeof w.schema=="object"){let N=w.schema.properties&&typeof w.schema.properties=="object"?Object.keys(w.schema.properties):Object.keys(w.schema);N.length&&($+=`
|
|
6
|
+
fields: ${N.join(", ")}`)}return $});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
|
+
${T.join(`
|
|
10
|
+
`)}`}let O=r._currentNodeConfig?.extraPromptInstructions?.trim();return O&&(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
|
+
${O}
|
|
17
|
+
`),I.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,_)}var Ne,z,Be,Ue=ue(()=>{gt();ne();Pe();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);z=globalThis[Ne];Be=["low","medium","high","xhigh","max"]});var tn=new Set(["__proto__","constructor","prototype"]);function Ee(n){if(tn.has(n))throw new Error(`Invalid state key: "${n}"`)}var de=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){Ee(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)Ee(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){Ee(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 Y from"handlebars";var pe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of r)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,o]of Object.entries(this.schema)){if(o.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&o.type){let i=typeof e[r];i!==o.type&&t.push(`Field '${r}' expected ${o.type}, got ${i}`)}if(o.validate&&r in e){let i=o.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};ne();import{writeFileSync as
|
|
20
|
-
`?(
|
|
21
|
-
${
|
|
19
|
+
`)}`);return e}};ne();import{writeFileSync as De,readFileSync as bt,existsSync as Et,mkdirSync as Tn}from"node:fs";import{join as je,dirname as An}from"node:path";import R from"chalk";var rn="__WORKFLOW_GRAPH_LOG__",re=R.gray("\u2502"),on=R.gray("\u250C"),tt=R.gray("\u2514"),Te=R.green("\u25C6"),nt=R.hex("#c084fc")("\u25C6"),rt=R.hex("#2dd4bf")("\u25C6"),Ae=R.red("\u25C6"),ot=`${re} `,st=2;function it(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function at(n,e){return(t,r,o)=>{if(typeof t!="string")return n(t,r,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=ot,e.col=st,e.lineStart=!1),l===`
|
|
20
|
+
`?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
|
|
21
|
+
${ot}`,e.col=st))}return n(s,r,o)}}var $e=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=at(this._origStdoutWrite,e),process.stderr.write=at(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=`${rn}${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
28
|
`)}step(e){this._origStdoutWrite?this._writeDot(Te,e):process.stdout.write.bind(process.stdout)(`${re} ${Te} ${e}
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(nt,e):process.stdout.write.bind(process.stdout)(`${re} ${nt} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=R.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(rt,t):process.stdout.write.bind(process.stdout)(`${re} ${rt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,R.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Ae} ${R.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${on} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:o}=t;if(o)for(let s of o)this._rawWrite(`${Te} ${s}`);let i=r?R.dim(` ${it(r)}`):"";this._rawWrite(`${tt} ${R.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:o}=r,i=o?R.dim(` ${it(o)}`):"";this._rawWrite(`${Ae} ${R.red(t)}`),this._rawWrite(`${tt} ${R.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(R.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new $e;var he=".zibby/output",ct="sessions",X=".session-info.json",lt=".zibby-stop";var yr=Object.freeze(["codebase-memory","code-scan","artifact"]),ut=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var sn=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"}),an=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]),cn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),ft=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Oe(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 ln(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=ft.exec(Oe(n));return e?e[1].toLowerCase():null}function un(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=ft.exec(Oe(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function dn(n){let e=Oe(n);if(!e)return"deterministic";for(let o of cn)if(o.test(e))return"deterministic";let t=ln(n);if(t){let o=sn[t];if(o==="transient"||o==="deterministic")return o}let r=un(n);if(r===429||r>=500&&r<=599)return"transient";for(let o of an)if(o.test(e))return"transient";return"deterministic"}var dt=2,pn=5;function fn(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return dt;let t=Number(e);return!Number.isFinite(t)||t<0?dt:Math.min(pn,Math.floor(t))}var ve=5e3,ht=3e4;function hn(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return ve;let t=Number(e);return!Number.isFinite(t)||t<0?ve:Math.min(ht,Math.floor(t))}function pt(n,e=Math.random,t=ve){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),o=Math.min(ht,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function xe(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),o=fn(e),i=hn(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let d=dn(l);return s<r?(s+=1,{retry:!0,paidBy:"declared",delayMs:d==="transient"?pt(s,t,i):0,failureClass:d,index:s,of:r}):d==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:pt(a,t,i),failureClass:d,index:a,of:o}):{retry:!1,delayMs:0,failureClass:d}}}}async function It(n,e,t,r){if(!e.retry)return!1;if(r())return I.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?I.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):I.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())?(I.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}Y.helpers.inc||Y.registerHelper("inc",n=>Number(n)+1);Y.helpers.json||Y.registerHelper("json",n=>JSON.stringify(n,null,2));Y.helpers.eq||Y.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 pe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=_=>t&&typeof t.get=="function"?t.get(_):e?.[_],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let _=xe(this.retries),p=null,A=null;for(;;){try{let h=await this.customExecute(e);if(typeof h=="object"&&h!==null&&h.success===!1)A=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?(I.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){I.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),A=h,p={success:!1,error:h.message,raw:null}}let v=A??p?.error,O=_.next(v);if(!await It(this.name,O,v,i))break}return p&&(p.attempts=_.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=Y.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
|
|
33
33
|
|
|
34
|
-
${o}`);let l=r(),d=l.cwd||process.cwd(),b=l.sessionPath;try{if(b){let _=De(b,X);if(wt(_)){let A=JSON.parse(_t(_,"utf-8"));A.currentNode=this.name,Ue(_,JSON.stringify(A,null,2),"utf-8")}let f=De(b,"..",X);if(wt(f))try{let A=JSON.parse(_t(f,"utf-8"));A.currentNode=this.name,Ue(f,JSON.stringify(A,null,2),"utf-8")}catch{}}}catch(_){T.debug(`[workflow] could not update session info: ${_.message}`)}let u=ke(this.retries),c=null;for(;;)try{T.debug(`[workflow] node '${this.name}' attempt ${u.attemptsMade-1}`);let _=r().config||{},f=_.agents||{},A=this.config.agent??f[this.name]??null,$={state:r()};A&&($.preferredAgent=A);let v={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:b,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},p=e?._coreInvokeAgent;p||(p=(await Promise.resolve().then(()=>(Ce(),Be))).invokeAgent);let E=await p(o,$,v),I,m;if(typeof E=="string"?(I=E,m=null):E.structured?(I=E.raw||JSON.stringify(E.structured,null,2),m=E.structured):(I=E.raw||JSON.stringify(E,null,2),m=E.extracted||null),b)try{let g=De(b,this.name,"raw_stream_output.txt");En(In(g),{recursive:!0}),Ue(g,typeof I=="string"?I:JSON.stringify(I),"utf-8")}catch(g){T.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&m){T.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let g=m;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),m)}catch(h){T.warn(`[workflow] onComplete hook failed: ${h.message}`)}return{success:!0,output:g,raw:I}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:I}),raw:I}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(I);return T.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),R.step("Output parsed"),{success:!0,output:g,raw:I}}return{success:!0,output:I,raw:I}}catch(_){c=_;let f=u.next(_);if(!await bt(this.name,f,_,i))break}return{success:!1,error:c.message,raw:null,attempts:u.attemptsMade}}};ne();ne();import{mkdirSync as On,existsSync as q,statSync as Mt,readdirSync as Pt,rmSync as kn}from"node:fs";import{spawn as Ot}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as xn}from"node:url";import{AsyncLocalStorage as Mn}from"node:async_hooks";import{AsyncLocalStorage as Tn}from"node:async_hooks";var oe=new Tn;function Q(){let n=oe.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 Et(n,e){let t=oe.getStore()||Q(),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 oe.run(r,e)}function It(n,e,t){let r=oe.getStore()||Q(),s=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return oe.run(s,t)}var je=new Map,Le=new Map,Tt=new Map;function At(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");je.set(n,e),Le.set(n,"ready"),Tt.set(n,{...t,cachedAt:Date.now()})}function $t(n,e){Le.set(n,"failed"),Tt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),je.delete(n)}function vt(n){return Le.get(n)==="ready"?je.get(n):null}function ie(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 Fe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ae(n,e){return Fe(ie(n,e),n)}function D(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var ge=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Pn(){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 me(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 Rn(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 Nn(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 kt=new Mn,xt=Promise.resolve();async function Bn(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=kt.getStore()===!0,s=null;if(!r){let o=xt;xt=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 T.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await kt.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function Cn(){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 P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function Un({apiBase:n,authToken:e,body:t}){let r=ae("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 P(D(o)?"begin-timeout":"network",D(o)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${o.message}`)}let i=null;try{i=await s.json()}catch(o){if(D(o))throw new P("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 P("begin-status",`begin returned ${s.status}`)}return i?.data||i}async function Z({apiBase:n,authToken:e,payload:t}){let r=ae("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||T.warn(`[in-process subgraph] finalize returned ${s.status} for ${t.childExecutionId}`)}catch(s){T.warn(`[in-process subgraph] finalize ${D(s)?`TIMED OUT ${r.label}`:`failed: ${s.message}`}`)}}async function Dn(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(q(t)&&q(r))return;On(e,{recursive:!0});let s=H(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(q(t)&&q(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,d)=>{let b=Math.ceil(1e4/1e3),u=Math.ceil(ie("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ot("curl",["-fsSL","--connect-timeout",String(b),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),_=Ot("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(_.stdin);let f,A,$=()=>{if(f!==void 0&&A!==void 0){if(f!==0)return d(new Error(`curl exited ${f}`));if(A!==0)return d(new Error(`tar exited ${A}`));l()}};c.on("close",v=>{f=v,$()}),_.on("close",v=>{A=v,$()}),c.on("error",d),_.on("error",d)});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 P("bundle-extract-failed",o.message)}}async function jn(n){let e=H(n,"graph.mjs");if(!q(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(xn(e).href)}catch(s){throw new P("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 P("entry-class-missing","no buildGraph() class export found");return r}async function Rt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),r;try{r=Cn()}catch(h){throw h}T.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await Un({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:d,workflowUuid:b,bundleReady:u,nodeConfigs:c}=s,_=Pn();if(o&&o!==_)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${_} vs ${o}`);if(!u||!a)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let f=vt(n);if(!f){let h=H(ge,`${b}@${d||"0"}`);try{await Dn(a,h);try{Fn()}catch{}}catch(y){throw y.fallback&&await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{f=await jn(h),At(n,f,{workflowUuid:b,version:d,runtimeTag:o,cacheDir:h})}catch(y){throw $t(n,y),await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new P("import-failed",y.message)}}let A=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,v=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,p={...e.input||{},...v?{nodeConfigs:c}:{}},E=Rn(e.timeoutMs),I=Nn(e.signal,E),m,g;try{m=await Bn($,async()=>{let y=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return Et({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,p,{signal:I.signal}))}),g=m&&typeof m=="object"&&"state"in m?m.state:m}catch(h){let y=I.timedOut();throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(E/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-A}}),y?me(n,i,E):h}finally{I.dispose()}if(m&&typeof m=="object"&&m.stoppedExternally){let h=I.timedOut();if(await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:h?"timeout":"canceled",finalState:g,durationMs:Date.now()-A}}),h)throw me(n,i,E);let y=new Error(`Sub-graph '${n}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-A}}),{finalState:g,executionId:i}}function Ln(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),s;try{s=Mt(r)}catch{continue}if(s.isDirectory()){let i;try{i=Pt(r)}catch{continue}for(let o of i)t.push(H(r,o))}else e+=s.size}return e}function Fn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!q(ge))return{evicted:0,freedBytes:0};let e=Pt(ge),t=[],r=0;for(let a of e){let l=H(ge,a),d;try{d=Mt(l)}catch{continue}let b=d.isDirectory()?Ln(l):d.size;r+=b,t.push({name:a,full:l,size:b,mtimeMs:d.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(!q(H(a.full,".lock")))try{kn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(l){T.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return o>0&&T.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 T.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Hn=2e3,Wn=600*1e3,Jn=new Set(["completed","failed","canceled","timeout"]);var zn=()=>ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Yn(n){let e=ie("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Fe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Zn(){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 qn(){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 Vn(){return process.env.EXECUTION_ID||null}function Nt(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 Bt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();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:Wn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{T.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:m}=await Rt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),g=Nt(m,e.output);return T.info(`[sub-graph] '${n}' completed in-process`),g}catch(m){if(m instanceof P||m?.fallback)T.info(`[sub-graph] in-process fallback for '${n}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Zn(),o=qn(),a=Kn(),l=Vn(),d=`${i}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(n)}/trigger`,b={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};T.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=zn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(b),signal:u.signal})}catch(m){if(!D(m))throw m;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}if(!c.ok){let m=null,g="";try{m=await c.json(),g=m?.error||m?.message||JSON.stringify(m)}catch{g=await c.text().catch(()=>"")}if(c.status===429){let y=m?.quotaInfo||{},k=new Error(`Sub-graph '${n}' blocked by execution quota (${y.used??"?"}/${y.limit??"?"} on plan ${y.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw k.code="SUBGRAPH_QUOTA_EXCEEDED",k.status=429,k.subgraph=n,k.quotaInfo=y,k}if(c.status===400){let y=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw y.code="SUBGRAPH_INVALID_INPUT",y.status=400,y.subgraph=n,y.validationErrors=m?.validationErrors||null,y.missing=m?.missing||null,y}let h=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${g}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=c.status,h.subgraph=n,h}let _;try{_=await c.json()}catch(m){if(!D(m))throw m;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=m,g}let f=_?.data?.jobId||_?.jobId;if(!f)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(_).slice(0,200)}`);if(e.async)return T.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${f} (not waiting)`),{jobId:f,status:"accepted",workflow:n};let A=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Hn,$=`${i}/executions/${encodeURIComponent(f)}`,v=Date.now()+s,p="accepted",E=0,I=null;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,A)),E+=1;let m=Yn(v),g;try{g=await fetch($,{headers:{Authorization:`Bearer ${a}`},signal:m.signal})}catch(k){I=D(k)?`poll TIMED OUT ${m.label}`:k?.message||String(k),T.warn(`[sub-graph] status poll for ${f} could not reach the API (${I}), will retry`);continue}if(!g.ok){if(g.status>=500){T.warn(`[sub-graph] status poll for ${f} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${f}: ${g.status}`)}let h;try{h=await g.json()}catch(k){I=D(k)?`poll body read TIMED OUT ${m.label}`:k?.message||String(k),T.warn(`[sub-graph] status poll for ${f} returned an unreadable body (${I}), will retry`);continue}let y=h?.data||h?.execution||h;if(p=y?.status||p,Jn.has(p)){if(p!=="completed"){let W=new Error(`Sub-graph '${n}' (${f}) ended in status '${p}'`);throw W.subgraphJobId=f,W.subgraphStatus=p,W}let k=y?.finalState||y?.state||{},F=Nt(k,e.output);return T.info(`[sub-graph] '${n}' (${f}) completed after ${E} polls`),F}}throw me(n,f,s,p,I)}import{existsSync as Ct,readFileSync as Xn}from"node:fs";import{join as Ge,dirname as Ut}from"node:path";var Se=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ut(Ge(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let b=l.replace(/\.[^.]+$/,"").toLowerCase();s[b]=d}}}let o=r.discovery||{};for(let[a,l]of Object.entries(o))try{let d=Ge(t,l);Ct(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let o=Ge(i,e);if(Ct(o))try{s.unshift(await this.loadFile(o))}catch(l){console.warn(`[workflow] could not load ${e} from ${o}: ${l.message}`)}let a=Ut(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
|
|
34
|
+
${s}`);let l=r(),d=l.cwd||process.cwd(),E=l.sessionPath;try{if(E){let _=je(E,X);if(Et(_)){let A=JSON.parse(bt(_,"utf-8"));A.currentNode=this.name,De(_,JSON.stringify(A,null,2),"utf-8")}let p=je(E,"..",X);if(Et(p))try{let A=JSON.parse(bt(p,"utf-8"));A.currentNode=this.name,De(p,JSON.stringify(A,null,2),"utf-8")}catch{}}}catch(_){I.debug(`[workflow] could not update session info: ${_.message}`)}let u=xe(this.retries),c=null;for(;;)try{I.debug(`[workflow] node '${this.name}' attempt ${u.attemptsMade-1}`);let _=r().config||{},p=_.agents||{},A=this.config.agent??p[this.name]??null,v={state:r()};A&&(v.preferredAgent=A);let O={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:E,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(Ue(),Ce))).invokeAgent);let T=await h(s,v,O),w,y;if(typeof T=="string"?(w=T,y=null):T.structured?(w=T.raw||JSON.stringify(T.structured,null,2),y=T.structured):(w=T.raw||JSON.stringify(T,null,2),y=T.extracted||null),E)try{let m=je(E,this.name,"raw_stream_output.txt");Tn(An(m),{recursive:!0}),De(m,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(m){I.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&y){I.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let m=y;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),y)}catch(f){I.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:m,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(w);return I.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),P.step("Output parsed"),{success:!0,output:m,raw:w}}return{success:!0,output:w,raw:w}}catch(_){c=_;let p=u.next(_);if(!await It(this.name,p,_,i))break}return{success:!1,error:c.message,raw:null,attempts:u.attemptsMade}}};ne();ne();import{mkdirSync as kn,existsSync as q,statSync as Pt,readdirSync as Nt,rmSync as Rn}from"node:fs";import{spawn as kt}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Mn}from"node:url";import{AsyncLocalStorage as Pn}from"node:async_hooks";import{AsyncLocalStorage as $n}from"node:async_hooks";var se=new $n;function Q(){let n=se.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 Tt(n,e){let t=se.getStore()||Q(),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 se.run(r,e)}function At(n,e,t){let r=se.getStore()||Q(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return se.run(o,t)}var Le=new Map,Fe=new Map,$t=new Map;function vt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(n,e),Fe.set(n,"ready"),$t.set(n,{...t,cachedAt:Date.now()})}function Ot(n,e){Fe.set(n,"failed"),$t.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(n)}function xt(n){return Fe.get(n)==="ready"?Le.get(n):null}function ie(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 Ge(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ae(n,e){return Ge(ie(n,e),n)}function j(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var ge=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Nn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var M=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function me(n,e,t,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 Bn(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 Cn(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 Rt=new Pn,Mt=Promise.resolve();async function Un(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=Rt.getStore()===!0,o=null;if(!r){let s=Mt;Mt=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 Rt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Dn(){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 M("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function jn({apiBase:n,authToken:e,body:t}){let r=ae("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 M(j(s)?"begin-timeout":"network",j(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(j(s))throw new M("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 M("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function Z({apiBase:n,authToken:e,payload:t}){let r=ae("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 ${j(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Ln(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(q(t)&&q(r))return;kn(e,{recursive:!0});let o=H(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(q(t)&&q(r))return;await new Promise(a=>setTimeout(a,100))}throw new M("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let E=Math.ceil(1e4/1e3),u=Math.ceil(ie("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=kt("curl",["-fsSL","--connect-timeout",String(E),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),_=kt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(_.stdin);let p,A,v=()=>{if(p!==void 0&&A!==void 0){if(p!==0)return d(new Error(`curl exited ${p}`));if(A!==0)return d(new Error(`tar exited ${A}`));l()}};c.on("close",O=>{p=O,v()}),_.on("close",O=>{A=O,v()}),c.on("error",d),_.on("error",d)});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 M("bundle-extract-failed",s.message)}}async function Fn(n){let e=H(n,"graph.mjs");if(!q(e))throw new M("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Mn(e).href)}catch(o){throw new M("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 M("entry-class-missing","no buildGraph() class export found");return r}async function Bt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),r;try{r=Dn()}catch(f){throw f}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await jn({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:d,workflowUuid:E,bundleReady:u,nodeConfigs:c}=o,_=Nn();if(s&&s!==_)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("runtime-mismatch",`${_} vs ${s}`);if(!u||!a)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("no-bundle","workflow bundle not built yet");let p=xt(n);if(!p){let f=H(ge,`${E}@${d||"0"}`);try{await Ln(a,f);try{Hn()}catch{}}catch(g){throw g.fallback&&await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason}}}),g}try{p=await Fn(f),vt(n,p,{workflowUuid:E,version:d,runtimeTag:s,cacheDir:f})}catch(g){throw Ot(n,g),await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason||"IMPORT_FAILED"}}}),g.fallback?g:new M("import-failed",g.message)}}let A=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,O=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...O?{nodeConfigs:c}:{}},T=Bn(e.timeoutMs),w=Cn(e.signal,T),y,m;try{y=await Un(v,async()=>{let g=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Tt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>g.run(e.parentAgent,h,{signal:w.signal}))}),m=y&&typeof y=="object"&&"state"in y?y.state:y}catch(f){let g=w.timedOut();throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"failed",error:g?{message:`aborted at the declared ${Math.round(T/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-A}}),g?me(n,i,T):f}finally{w.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let f=w.timedOut();if(await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:m,durationMs:Date.now()-A}}),f)throw me(n,i,T);let g=new Error(`Sub-graph '${n}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=i,g}return await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-A}}),{finalState:m,executionId:i}}function Gn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Pt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Nt(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Hn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!q(ge))return{evicted:0,freedBytes:0};let e=Nt(ge),t=[],r=0;for(let a of e){let l=H(ge,a),d;try{d=Pt(l)}catch{continue}let E=d.isDirectory()?Gn(l):d.size;r+=E,t.push({name:a,full:l,size:E,mtimeMs:d.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(!q(H(a.full,".lock")))try{Rn(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 Jn=2e3,zn=600*1e3,Yn=new Set(["completed","failed","canceled","timeout"]);var Zn=()=>ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function qn(n){let e=ie("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ge(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Kn(){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 Vn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Xn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Qn(){return process.env.EXECUTION_ID||null}function Ct(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 Ut(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();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:zn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:y}=await Bt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),m=Ct(y,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),m}catch(y){if(y instanceof M||y?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Kn(),s=Vn(),a=Xn(),l=Qn(),d=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,E={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=Zn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(E),signal:u.signal})}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}if(!c.ok){let y=null,m="";try{y=await c.json(),m=y?.error||y?.message||JSON.stringify(y)}catch{m=await c.text().catch(()=>"")}if(c.status===429){let g=y?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${g.used??"?"}/${g.limit??"?"} on plan ${g.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw $.code="SUBGRAPH_QUOTA_EXCEEDED",$.status=429,$.subgraph=n,$.quotaInfo=g,$}if(c.status===400){let g=new Error(`Sub-graph '${n}' rejected input: ${m}`);throw g.code="SUBGRAPH_INVALID_INPUT",g.status=400,g.subgraph=n,g.validationErrors=y?.validationErrors||null,g.missing=y?.missing||null,g}let f=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${m}`);throw f.code="SUBGRAPH_TRIGGER_FAILED",f.status=c.status,f.subgraph=n,f}let _;try{_=await c.json()}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}let p=_?.data?.jobId||_?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(_).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let A=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Jn,v=`${i}/executions/${encodeURIComponent(p)}`,O=Date.now()+o,h="accepted",T=0,w=null;for(;Date.now()<O;){await new Promise($=>setTimeout($,A)),T+=1;let y=qn(O),m;try{m=await fetch(v,{headers:{Authorization:`Bearer ${a}`},signal:y.signal})}catch($){w=j($)?`poll TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} could not reach the API (${w}), will retry`);continue}if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let f;try{f=await m.json()}catch($){w=j($)?`poll body read TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${w}), will retry`);continue}let g=f?.data||f?.execution||f;if(h=g?.status||h,Yn.has(h)){if(h!=="completed"){let W=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw W.subgraphJobId=p,W.subgraphStatus=h,W}let $=g?.finalState||g?.state||{},N=Ct($,e.output);return I.info(`[sub-graph] '${n}' (${p}) completed after ${T} polls`),N}}throw me(n,p,o,h,w)}import{existsSync as Dt,readFileSync as er}from"node:fs";import{join as He,dirname as jt}from"node:path";var Se=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=jt(He(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let E=l.replace(/\.[^.]+$/,"").toLowerCase();o[E]=d}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let d=He(t,l);Dt(d)&&(o[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=He(i,e);if(Dt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=jt(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):
|
|
38
|
+
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=er(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),o=await import(r(e).href);return o.default||o}return t}};import{mkdirSync as Ht,existsSync as We,writeFileSync as Lt,unlinkSync as tr}from"node:fs";import{join as K,resolve as Wt}from"node:path";import{config as nr}from"dotenv";import{zodToJsonSchema as Ft}from"zod-to-json-schema";import{z as _e}from"zod";import rr from"handlebars";function or({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${s} sessionId=${e} source=${r} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let E=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${n}):
|
|
41
|
-
${b}`)}}function rr(){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 sr(){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 Gt(String(e).trim())}catch{return String(e).trim()}}function or(){rr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function ir({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 ar(n={}){let e=lt.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 cr({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 d=Gt(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,o="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,o="config.sessionId"):(a=ar(e),o="generated")}i=i??Date.now();let b=e.paths?.output||he;s=K(n,b,at,a)}let l=!He(s);return l&&Ft(s,{recursive:!0}),(l||o!=="initialState.sessionPath")&&nr({traceFrom:r,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:l}),ir({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var Lt=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"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async d=>{let b=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof o.input=="function"?u=o.input(b):o.input&&typeof o.input=="object"?u=o.input:u={},Bt(o.workflow,{input:u,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(b):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:b?._signal,parentAgent:d?.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],d=o;o=()=>l(t,d,s,i)}return o()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let _=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:_,data:{nodeType:_,label:u}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let A=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;A&&(f.description=A);let $=this.nodePrompts.get(u);if($)f.prompt=$;else if(typeof c.prompt=="function")try{let h=c.prompt({});typeof h=="string"&&h.trim()&&(f.prompt=h,f.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString());let v=c?.config?.dispatchesWorkflow;if(typeof v=="string"&&v.trim())f.dispatchesWorkflow=v.trim();else if(Array.isArray(v)){let h=[...new Set(v.filter(y=>typeof y=="string").map(y=>y.trim()).filter(Boolean))];h.length&&(f.dispatchesWorkflow=h)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(f.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let h=null;if(typeof _e?.toJSONSchema=="function")try{h=_e.toJSONSchema(c.outputSchema)}catch{}if(!h)try{h=jt(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=h?{jsonSchema:h,variables:this._flattenJsonSchemaToVariables(h)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let p=(this.resolvedToolsMap||{})[u];p?.toolIds&&(f.tools=p.toolIds);let E=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;E&&E.length>0&&(f.skills=[...E]);let I=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;I&&I.length>0&&(f.plugins=I.map(h=>h&&typeof h=="object"?{...h}:h));let m=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;m&&m.length>0&&(f.stores=m.map(h=>h&&typeof h=="object"?{...h}:h));let g=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(g&&g.length>0){let h=new Set,y=[];for(let k of g){let F=typeof k=="string"?k.trim():"";!F||h.has(F)||(h.add(F),y.push(F))}y.length>0&&(f.uses=y)}Object.keys(f).length>0&&(t[u]=f)}let r=[];for(let[u,c]of this.edges)if(typeof c=="string")r.push({source:u,target:c});else if(Array.isArray(c))for(let _ of c)r.push({source:u,target:_});else if(c.conditional){let _=this.conditionalCodeMap.get(u)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),A=c.labels||{},$=this.nodes.get(u),v=$?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!$,p=u;if(!v){let E=`${u}__branch`;e.push({id:E,type:"decision",data:{nodeType:"decision",label:E}}),r.push({source:u,target:E}),p=E}for(let E of f){let I={source:p,target:E,data:{conditionalCode:_}};A[E]&&(I.label=A[E]),r.push(I)}}let s=u=>{if(!u)return null;if(typeof _e?.toJSONSchema=="function")try{return _e.toJSONSchema(u)}catch{}try{return jt(u,{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 u of r)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:u,target:c})}let o=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=s(a||this.stateSchema),d=s(this.inputSchema),b=s(this.contextSchema);return{nodes:o,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:b}}_topoOrderNodes(e,t){let r=new Map(e.map((u,c)=>[u.id,c])),s=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),o=new Map(e.map(u=>[u.id,[]]));for(let u of t)o.has(u.source)&&i.has(u.target)&&(o.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(r.keys()),d=[...l].filter(u=>i.get(u)===0),b=[];for(;b.length<e.length;){let u;if(d.length>0){if(d.sort((c,_)=>r.get(c)-r.get(_)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,_)=>r.get(c)-r.get(_))[0];a.add(u),l.delete(u),b.push(s.get(u));for(let c of o.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return b}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(r))!==null;){let d=o[2]!==void 0?o[2]:o[3];d!==void 0&&d!==""&&s.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of s)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,b;for(;(b=d.exec(r))!==null;)l.add(b[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(d=>d?.passed===!0).length,l=i.some(d=>d?.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(w){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${w?.message||w}`);throw S.cause=w,S.code=w?.code||"NORMALIZE_INPUT_FAILED",S}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();er({path:K(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let w=K(o,".zibby.config.js");He(w)&&(a=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let w=a?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},b=this._runtimeSchema();if(b){let w=b.safeParse(t);if(!w.success){let S=w.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${S.join(", ")}`)}R.step("State validated against schema")}let u=sr(),c=t.sessionPath||u;c||or();let{sessionPath:_,sessionTimestamp:f,sessionId:A}=cr({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});R.step(`Session ${A}`);let $=await Se.loadContext(t.specPath||"",o,d);Object.keys($).length>0&&R.step(`Context loaded: ${Object.keys($).join(", ")}`);let v=t.outputPath;!v&&t.specPath&&(e?.calculateOutputPath?v=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let p=new de({...t,config:a,agentType:l,outputPath:v,sessionPath:_,sessionTimestamp:f,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),E=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:I}=await Promise.resolve().then(()=>(Re(),gt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),h=w=>{for(let S of g)if(S.id===w)return S;return I(w)},y=new Set;for(let[,w]of this.nodes)for(let S of w.config?.skills||[])y.add(S);for(let w of y){let S=h(w);if(typeof S?.middleware=="function")try{let B=await S.middleware();typeof B=="function"&&E.set(w,B)}catch{}}let{backEdges:k,joinDegree:F}=this._analyzeFlow(),W=new Map,ee=[],we=(w,S,B)=>{if(!w||w==="END")return;let j=F.get(w)||0;if(B&&j>1&&!k.has(`${S}->${w}`)){let te=(W.get(w)||0)+1;if(te<j){W.set(w,te);return}W.set(w,0)}ee.includes(w)||ee.push(w)};this.entryPoint&&ee.push(this.entryPoint);let ce=[],We=a?.recursionLimit??100,Ht=0;try{for(;ee.length>0;){let S=ee.pop();if(!S||S==="END")continue;if(++Ht>We)throw new Error(`Workflow exceeded recursion limit (${We}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=K(_,ct);if(He(B)){try{Qn(B)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
${E}`)}}function sr(){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 ir(){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 Wt(String(e).trim())}catch{return String(e).trim()}}function ar(){sr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function cr({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 lr(n={}){let e=ut.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 ur({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 d=Wt(String(process.env.ZIBBY_SESSION_PATH));d&&(o=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,s="config.sessionId"):(a=lr(e),s="generated")}i=i??Date.now();let E=e.paths?.output||he;o=K(n,E,ct,a)}let l=!We(o);return l&&Ht(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&or({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),cr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Gt=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"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let E=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof s.input=="function"?u=s.input(E):s.input&&typeof s.input=="object"?u=s.input:u={},Ut(s.workflow,{input:u,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(E):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:E?._signal,parentAgent:d?.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 o=!(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(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],d=s;s=()=>l(t,d,o,i)}return s()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let _=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:_,data:{nodeType:_,label:u}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let A=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;A&&(p.description=A);let v=this.nodePrompts.get(u);if(v)p.prompt=v;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(p.prompt=f,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let O=c?.config?.dispatchesWorkflow;if(typeof O=="string"&&O.trim())p.dispatchesWorkflow=O.trim();else if(Array.isArray(O)){let f=[...new Set(O.filter(g=>typeof g=="string").map(g=>g.trim()).filter(Boolean))];f.length&&(p.dispatchesWorkflow=f)}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 f=null;if(typeof _e?.toJSONSchema=="function")try{f=_e.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=Ft(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[u];h?.toolIds&&(p.tools=h.toolIds);let T=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;T&&T.length>0&&(p.skills=[...T]);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(f=>f&&typeof f=="object"?{...f}:f));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(p.stores=y.map(f=>f&&typeof f=="object"?{...f}:f));let m=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(m&&m.length>0){let f=new Set,g=[];for(let $ of m){let N=typeof $=="string"?$.trim():"";!N||f.has(N)||(f.add(N),g.push(N))}g.length>0&&(p.uses=g)}Object.keys(p).length>0&&(t[u]=p)}let r=[];for(let[u,c]of this.edges)if(typeof c=="string")r.push({source:u,target:c});else if(Array.isArray(c))for(let _ of c)r.push({source:u,target:_});else if(c.conditional){let _=this.conditionalCodeMap.get(u)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),A=c.labels||{},v=this.nodes.get(u),O=v?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!v,h=u;if(!O){let T=`${u}__branch`;e.push({id:T,type:"decision",data:{nodeType:"decision",label:T}}),r.push({source:u,target:T}),h=T}for(let T of p){let w={source:h,target:T,data:{conditionalCode:_}};A[T]&&(w.label=A[T]),r.push(w)}}let o=u=>{if(!u)return null;if(typeof _e?.toJSONSchema=="function")try{return _e.toJSONSchema(u)}catch{}try{return Ft(u,{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 u of r)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:u,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),d=o(this.inputSchema),E=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:E}}_topoOrderNodes(e,t){let r=new Map(e.map((u,c)=>[u.id,c])),o=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),s=new Map(e.map(u=>[u.id,[]]));for(let u of t)s.has(u.source)&&i.has(u.target)&&(s.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(r.keys()),d=[...l].filter(u=>i.get(u)===0),E=[];for(;E.length<e.length;){let u;if(d.length>0){if(d.sort((c,_)=>r.get(c)-r.get(_)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,_)=>r.get(c)-r.get(_))[0];a.add(u),l.delete(u),E.push(o.get(u));for(let c of s.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return E}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&o.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of o)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,E;for(;(E=d.exec(r))!==null;)l.add(E[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(d=>d?.passed===!0).length,l=i.some(d=>d?.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(b){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw S.cause=b,S.code=b?.code||"NORMALIZE_INPUT_FAILED",S}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();nr({path:K(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=K(s,".zibby.config.js");We(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let b=a?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},E=this._runtimeSchema();if(E){let b=E.safeParse(t);if(!b.success){let S=b.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${S.join(", ")}`)}P.step("State validated against schema")}let u=ir(),c=t.sessionPath||u;c||ar();let{sessionPath:_,sessionTimestamp:p,sessionId:A}=ur({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let v=await Se.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&P.step(`Context loaded: ${Object.keys(v).join(", ")}`);let O=t.outputPath;!O&&t.specPath&&(e?.calculateOutputPath?O=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new de({...t,config:a,agentType:l,outputPath:O,sessionPath:_,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),T=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(Pe(),mt)),y=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values(y).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),f=b=>{for(let S of m)if(S.id===b)return S;return w(b)},g=new Set;for(let[,b]of this.nodes)for(let S of b.config?.skills||[])g.add(S);for(let b of g){let S=f(b);if(typeof S?.middleware=="function")try{let C=await S.middleware();typeof C=="function"&&T.set(b,C)}catch{}}let{backEdges:$,joinDegree:N}=this._analyzeFlow(),W=new Map,ee=[],we=(b,S,C)=>{if(!b||b==="END")return;let L=N.get(b)||0;if(C&&L>1&&!$.has(`${S}->${b}`)){let te=(W.get(b)||0)+1;if(te<L){W.set(b,te);return}W.set(b,0)}ee.includes(b)||ee.push(b)};this.entryPoint&&ee.push(this.entryPoint);let ce=[],Je=a?.recursionLimit??100,Jt=0;try{for(;ee.length>0;){let S=ee.pop();if(!S||S==="END")continue;if(++Jt>Je)throw new Error(`Workflow exceeded recursion limit (${Je}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=K(_,lt);if(We(C)){try{tr(C)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ce,stoppedExternally:!0};let L=this.nodes.get(S);if(!L)throw new Error(`Node '${S}' not found in graph`);let te=JSON.stringify({sessionPath:_,sessionTimestamp:p,currentNode:S,createdAt:new Date().toISOString(),config:h.get("config")}),zt=K(_,X);Lt(zt,te,"utf-8");let ze=h.get("config")?.paths?.output||he,Yt=K(s,ze,X);Ht(K(s,ze),{recursive:!0});try{Lt(Yt,te,"utf-8")}catch{}let Ye=t.onPipelineProgress;if(typeof Ye=="function")try{Ye({cwd:s,sessionPath:_,sessionId:A,outputBase:h.get("config")?.paths?.output||he,currentNode:S})}catch{}let Zt=(this.resolvedToolsMap||{})[S]||null;h.set("_currentNodeTools",Zt);let qt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",qt[S]||{}),P.nodeStart(S);let Ze=Date.now(),le=this.nodePrompts.get(S);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(Ue(),Ce));this._invokeAgent=k.invokeAgent}let Kt=this._invokeAgent,be={},Vt=L.config?.skills||[];for(let k of Vt){let B=f(k);if(typeof B?.invokeAgentOptions=="function")try{let x=B.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:S});x&&typeof x=="object"&&(be={...be,...x})}catch(x){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${x.message}`)}}let qe=async(k,B,x={})=>{let U=Kt(k,B,{...be,...x,signal:o.signal});return U.catch(()=>{}),o.signal.aborted?U:Promise.race([U,new Promise((V,F)=>{let D=()=>{setTimeout(()=>{let Xe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Xe.name="AbortError",F(Xe)},i)};o.signal.addEventListener("abort",D,{once:!0})})])},Xt=async(k={},B={})=>{let x=B.prompt||"";if(le){let U=this._compiledPrompts.get(S);U||(U=rr.compile(le,{noEscape:!0}),this._compiledPrompts.set(S,U));try{x=U(k)}catch(V){throw console.error(`\u274C Template rendering failed for node '${S}':`,V.message),new Error(`Template rendering failed: ${V.message}`,{cause:V})}}else if(!x)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return qe(x,{state:h.getAll(),images:B.images||[]},{model:B.model||h.get("model"),workspace:h.get("workspace"),schema:B.schema,...B,signal:o.signal,nodeName:S})},Ke=h.getAll(),Qt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Qt)Object.prototype.hasOwnProperty.call(Ke,k)&&console.warn(`[workflow] node "${S}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ve={...Ke,state:h,invokeAgent:Xt,_coreInvokeAgent:qe,agent:e,nodeId:S,promptTemplate:le,getPromptTemplate:()=>le};try{let k=(L.config?.skills||[]).map(D=>T.get(D)).filter(Boolean),B=[...this.middleware,...k],x;x=await At(e,o.signal,async()=>B.length>0?this._composeMiddleware(B,S,async()=>L.execute(Ve,h),h.getAll(),h):L.execute(Ve,h));let U=Date.now()-Ze;if(ce.push({node:S,success:x.success,duration:U,timestamp:new Date().toISOString()}),!x.success){if(o.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ce,stoppedExternally:!0};h.append("errors",{node:S,error:x.error});let D=Number.isInteger(x.attempts)&&x.attempts>0?x.attempts:(L.config?.retries||0)+1;throw P.nodeFailed(S,x.error,{duration:U}),new Error(`Node '${S}' failed after ${D} attempt(s): ${x.error}`)}h.update({[S]:x.output});let V=this._summarizeNodeOutput(S,x.output);P.nodeComplete(S,{duration:U,details:V});let F=this.edges.get(S);if(F)if(F.conditional){let D=F.routes(h.getAll());P.route(S,D),we(D,S,!1)}else if(Array.isArray(F))for(let D=F.length-1;D>=0;D--)we(F[D],S,!0);else we(F,S,!0)}catch(k){throw P.isInsideNode&&P.nodeFailed(S,k.message,{duration:Date.now()-Ze}),h.set("failed",!0),h.set("failedAt",S),k}}P.graphComplete();let b={success:!0,state:h.getAll(),executionLog:ce};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};export{Gt as WorkflowGraph,ar as clearInheritedSessionEnvForFreshRun,lr as generateWorkflowSessionId,ir as readPinnedSessionPathFromEnv,ur as resolveWorkflowSession,sr as shouldTrustInheritedSessionEnv,cr as syncProcessEnvToSession};
|
package/dist/index.d.ts
CHANGED
|
@@ -39,7 +39,7 @@ export { registerSkill, getSkill, getSkillSource, hasSkill, getAllSkills, listSk
|
|
|
39
39
|
export { resolveNodeTools, getResolvedToolDefinitions, NODE_DEFAULT_TOOLS } from './tool-resolver.js';
|
|
40
40
|
export { validateStoreDefs, STORE_NAME_REGEX } from './stores.js';
|
|
41
41
|
export { AgentStrategy } from './agents/base.js';
|
|
42
|
-
export { registerStrategy, listStrategies, getAgentStrategy, invokeAgent, resolveInvocationModel, resolveInvocationExtras } from './strategy-registry.js';
|
|
42
|
+
export { registerStrategy, listStrategies, getAgentStrategy, invokeAgent, resolveInvocationModel, resolveInvocationExtras, resolveInvocationEffort, EFFORT_LEVELS } from './strategy-registry.js';
|
|
43
43
|
export { generateWorkflowCode, generateNodeConfigsJson } from './code-generator.js';
|
|
44
44
|
export { setLogger } from './logger.js';
|
|
45
45
|
export { NO_INTEGRATION_TOGGLEABLE_SKILL_IDS, DEFAULT_OUTPUT_BASE, SESSIONS_DIR, SESSION_INFO_FILE, STOP_REQUEST_FILE, RESULT_FILE, RAW_OUTPUT_FILE, EVENTS_FILE, CI_ENV_VARS, } from './constants.js';
|