@zibby/agent-workflow 2.0.13 → 2.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js CHANGED
@@ -1,9 +1,9 @@
1
- var Et=Object.defineProperty;var x=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var Nt=(r,t)=>{for(var e in t)Et(r,e,{get:t[e],enumerable:!0})};var Y,Tt,W,P,d,C=x(()=>{Y=()=>{},Tt={debug:Y,info:Y,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},W=Symbol.for("@zibby/agent-workflow.logger");globalThis[W]||(globalThis[W]={impl:Tt});P=globalThis[W],d={debug:(...r)=>P.impl.debug?.(...r),info:(...r)=>P.impl.info?.(...r),warn:(...r)=>P.impl.warn?.(...r),error:(...r)=>P.impl.error?.(...r)}});var ut=x(()=>{});function ct(r){return Ct.get(r)||null}var H,K,Ct,Zt,dt=x(()=>{H=Symbol.for("@zibby/agent-workflow.skills"),K=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[H]||(globalThis[H]=new Map);globalThis[K]||(globalThis[K]=new Map);Ct=globalThis[H],Zt=globalThis[K]});var gt={};Nt(gt,{EFFORT_LEVELS:()=>z,getAgentStrategy:()=>ht,invokeAgent:()=>Dt,listStrategies:()=>Ft,registerStrategy:()=>Lt,resolveInvocationEffort:()=>ft,resolveInvocationExtras:()=>mt,resolveInvocationModel:()=>pt});function Lt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=$.findIndex(e=>e.getName()===r.getName());t>=0?$[t]=r:$.push(r)}function Ft(){return $.map(r=>r.getName())}function pt({config:r={},options:t={},strategyName:e,envModel:n,nodeConfigModel:o}={}){let i=r.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,p=t.nodeName&&i[t.nodeName]||null,u=i.default||null,b=r.agent?.[e]?.model||null,N=(typeof n=="string"?n.trim():"")||null;return s||p||u||b||t.model||N||null}function ft({options:r={},envEffort:t,nodeConfigEffort:e}={}){let n=[e,r.effort,t].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return n?z.indexOf(n)===-1?(d.warn(`[workflow] ignoring unknown effort "${n}" \u2014 expected one of ${z.join(", ")}`),null):n:null}function mt({options:r={},stateView:t={},context:e={}}={}){return{workspace:t.workspace||r.workspace,schema:r.schema||e.schema,images:r.images||e.images||[],skills:r.skills||e.skills||[],extraMcpServers:r.extraMcpServers||t.extraMcpServers||e.extraMcpServers||[],plugins:r.plugins||e.plugins||[]}}function ht(r={}){let{state:t={},preferredAgent:e=null}=r,n=e||t.agentType||process.env.AGENT_TYPE;if(!n){let i=$.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}d.debug(`[workflow] agent selection: requested=${n}`);let o=$.find(i=>i.getName()===n);if(!o){let i=$.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!o.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return d.debug(`[workflow] using agent: ${o.getName()}`),o}async function Dt(r,t={},e={}){let n=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:n},i=ht(o),s=n.config||e.config||{},p=n._currentNodeConfig||{},u=typeof p.agent=="string"?p.agent.trim():"",b=!u||u===i.name?p.model:null,N=pt({config:s,options:e,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:b}),O=!u||u===i.name?p.effort:null,A=ft({options:e,envEffort:process.env.EFFORT,nodeConfigEffort:O}),c={...e,model:N,...A?{effort:A}:{},...mt({options:e,stateView:n,context:t}),config:s},f=r,g=c.skills||[];if(g.length>0&&!e.skipPromptFragments){let l=e.connectedIntegrations;if(!l){let _=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof _=="string"&&_.trim()!==""){l={};for(let S of _.split(",").map(T=>T.trim()).filter(Boolean))l[S]=!0}}let y=_=>{let S=_&&_.requiresIntegration;return!S||!l?!0:(Array.isArray(S)?S:[S]).some(v=>l[v]===!0)},a=i.name==="assistant",w=_=>_?.inProcessOnly!==!0||a,m=g.map(_=>{let S=ct(_);if(!y(S)||!w(S))return null;let T=S?.promptFragment;return typeof T=="function"?T():T}).filter(Boolean);m.length>0&&(f+=`
1
+ var Et=Object.defineProperty;var x=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var Nt=(r,t)=>{for(var e in t)Et(r,e,{get:t[e],enumerable:!0})};var X,$t,P,W,d,C=x(()=>{X=()=>{},$t={debug:X,info:X,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},P=Symbol.for("@zibby/agent-workflow.logger");globalThis[P]||(globalThis[P]={impl:$t});W=globalThis[P],d={debug:(...r)=>W.impl.debug?.(...r),info:(...r)=>W.impl.info?.(...r),warn:(...r)=>W.impl.warn?.(...r),error:(...r)=>W.impl.error?.(...r)}});var lt=x(()=>{});function ct(r){return Ct.get(r)||null}var J,z,Ct,Zt,dt=x(()=>{J=Symbol.for("@zibby/agent-workflow.skills"),z=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[J]||(globalThis[J]=new Map);globalThis[z]||(globalThis[z]=new Map);Ct=globalThis[J],Zt=globalThis[z]});var gt={};Nt(gt,{EFFORT_LEVELS:()=>V,getAgentStrategy:()=>ht,invokeAgent:()=>Dt,listStrategies:()=>Ft,registerStrategy:()=>Lt,resolveInvocationEffort:()=>ft,resolveInvocationExtras:()=>mt,resolveInvocationModel:()=>pt});function Lt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=T.findIndex(e=>e.getName()===r.getName());t>=0?T[t]=r:T.push(r)}function Ft(){return T.map(r=>r.getName())}function pt({config:r={},options:t={},strategyName:e,envModel:n,nodeConfigModel:o}={}){let i=r.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,p=t.nodeName&&i[t.nodeName]||null,l=i.default||null,b=r.agent?.[e]?.model||null,N=(typeof n=="string"?n.trim():"")||null;return s||p||l||b||t.model||N||null}function ft({options:r={},envEffort:t,nodeConfigEffort:e}={}){let n=[e,r.effort,t].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return n?V.indexOf(n)===-1?(d.warn(`[workflow] ignoring unknown effort "${n}" \u2014 expected one of ${V.join(", ")}`),null):n:null}function mt({options:r={},stateView:t={},context:e={}}={}){return{workspace:t.workspace||r.workspace,schema:r.schema||e.schema,images:r.images||e.images||[],skills:r.skills||e.skills||[],extraMcpServers:r.extraMcpServers||t.extraMcpServers||e.extraMcpServers||[],plugins:r.plugins||e.plugins||[]}}function ht(r={}){let{state:t={},preferredAgent:e=null}=r,n=e||t.agentType||process.env.AGENT_TYPE;if(!n){let i=T.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}d.debug(`[workflow] agent selection: requested=${n}`);let o=T.find(i=>i.getName()===n);if(!o){let i=T.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!o.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return d.debug(`[workflow] using agent: ${o.getName()}`),o}async function Dt(r,t={},e={}){let n=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:n},i=ht(o),s=n.config||e.config||{},p=n._currentNodeConfig||{},l=typeof p.agent=="string"?p.agent.trim():"",b=!l||l===i.name?p.model:null,N=pt({config:s,options:e,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:b}),v=!l||l===i.name?p.effort:null,O=ft({options:e,envEffort:process.env.EFFORT,nodeConfigEffort:v}),c={...e,model:N,...O?{effort:O}:{},...mt({options:e,stateView:n,context:t}),config:s},f=r,g=c.skills||[];if(g.length>0&&!e.skipPromptFragments){let u=e.connectedIntegrations;if(!u){let _=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof _=="string"&&_.trim()!==""){u={};for(let S of _.split(",").map($=>$.trim()).filter(Boolean))u[S]=!0}}let y=_=>{let S=_&&_.requiresIntegration;return!S||!u?!0:(Array.isArray(S)?S:[S]).some(R=>u[R]===!0)},a=i.name==="assistant",w=_=>_?.inProcessOnly!==!0||a,m=g.map(_=>{let S=ct(_);if(!y(S)||!w(S))return null;let $=S?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);m.length>0&&(f+=`
2
2
 
3
3
  ${m.join(`
4
4
 
5
- `)}`)}let E=n._currentNodeConfig?.stores;if(Array.isArray(E)&&E.length>0&&typeof E[0]=="object"){let l=E.length<=8,y=E.map(a=>{let w=a?.id??a?.storeId??"",m=(a?.name??"").toString().trim()||w,_=a?.type?` \xB7 ${a.type}`:"",S=(a?.description||"").toString().replace(/\s+/g," ").trim(),T=`- ${m} \xB7 ${S||"(no description)"}${_} (id: ${w})`;if(l&&a?.schema&&typeof a.schema=="object"){let v=a.schema.properties&&typeof a.schema.properties=="object"?Object.keys(a.schema.properties):Object.keys(a.schema);v.length&&(T+=`
6
- fields: ${v.join(", ")}`)}return T});f+=`
5
+ `)}`)}let E=n._currentNodeConfig?.stores;if(Array.isArray(E)&&E.length>0&&typeof E[0]=="object"){let u=E.length<=8,y=E.map(a=>{let w=a?.id??a?.storeId??"",m=(a?.name??"").toString().trim()||w,_=a?.type?` \xB7 ${a.type}`:"",S=(a?.description||"").toString().replace(/\s+/g," ").trim(),$=`- ${m} \xB7 ${S||"(no description)"}${_} (id: ${w})`;if(u&&a?.schema&&typeof a.schema=="object"){let R=a.schema.properties&&typeof a.schema.properties=="object"?Object.keys(a.schema.properties):Object.keys(a.schema);R.length&&($+=`
6
+ fields: ${R.join(", ")}`)}return $});f+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
9
  ${y.join(`
@@ -14,21 +14,21 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
14
14
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
15
15
 
16
16
  ${I}
17
- `),d.debug(`[workflow] prompt length: ${f.length} chars`),i.invoke(f,c)}var J,$,z,yt=x(()=>{ut();C();dt();J=Symbol.for("@zibby/agent-workflow.strategies");globalThis[J]||(globalThis[J]=[]);$=globalThis[J];z=["low","medium","high","xhigh","max"]});import k from"handlebars";var M=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let n=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of n)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[n,o]of Object.entries(this.schema)){if(o.required&&!(n in t)&&e.push(`Missing required field: ${n}`),n in t&&o.type){let i=typeof t[n];i!==o.type&&e.push(`Field '${n}' expected ${o.type}, got ${i}`)}if(o.validate&&n in t){let i=o.validate(t[n]);i&&e.push(`Field '${n}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
17
+ `),d.debug(`[workflow] prompt length: ${f.length} chars`),i.invoke(f,c)}var q,T,V,yt=x(()=>{lt();C();dt();q=Symbol.for("@zibby/agent-workflow.strategies");globalThis[q]||(globalThis[q]=[]);T=globalThis[q];V=["low","medium","high","xhigh","max"]});import k from"handlebars";var M=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let n=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of n)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[n,o]of Object.entries(this.schema)){if(o.required&&!(n in t)&&e.push(`Missing required field: ${n}`),n in t&&o.type){let i=typeof t[n];i!==o.type&&e.push(`Field '${n}' expected ${o.type}, got ${i}`)}if(o.validate&&n in t){let i=o.validate(t[n]);i&&e.push(`Field '${n}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
18
18
  ${e.join(`
19
- `)}`);return t}};C();import{writeFileSync as q,readFileSync as _t,existsSync as wt,mkdirSync as jt}from"node:fs";import{join as V,dirname as Bt}from"node:path";import h from"chalk";var $t="__WORKFLOW_GRAPH_LOG__",R=h.gray("\u2502"),kt=h.gray("\u250C"),Z=h.gray("\u2514"),L=h.green("\u25C6"),X=h.hex("#c084fc")("\u25C6"),Q=h.hex("#2dd4bf")("\u25C6"),F=h.red("\u25C6"),tt=`${R} `,et=2;function rt(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function nt(r,t){return(e,n,o)=>{if(typeof e!="string")return r(e,n,o);let i=process.stdout.columns||120,s="";for(let p=0;p<e.length;p++){let u=e[p];t.lineStart&&(s+=tt,t.col=et,t.lineStart=!1),u===`
20
- `?(s+=u,t.lineStart=!0,t.col=0,t.inEsc=!1):u==="\x1B"?(t.inEsc=!0,s+=u):t.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(t.inEsc=!1)):(t.col++,s+=u,t.col>=i&&(s+=`
21
- ${tt}`,t.col=et))}return r(s,n,o)}}var D=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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=nt(this._origStdoutWrite,t),process.stderr.write=nt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
- `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
- `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
24
- `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${$t}${JSON.stringify(t)}
19
+ `)}`);return t}};C();import{writeFileSync as Y,readFileSync as _t,existsSync as wt,mkdirSync as jt}from"node:fs";import{join as Z,dirname as Bt}from"node:path";import h from"chalk";var Tt="__WORKFLOW_GRAPH_LOG__",A=h.gray("\u2502"),kt=h.gray("\u250C"),L=h.gray("\u2514"),F=h.green("\u25C6"),Q=h.hex("#c084fc")("\u25C6"),tt=h.hex("#2dd4bf")("\u25C6"),D=h.red("\u25C6"),et=`${A} `,rt=2;function j(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function nt(r,t){return(e,n,o)=>{if(typeof e!="string")return r(e,n,o);let i=process.stdout.columns||120,s="";for(let p=0;p<e.length;p++){let l=e[p];t.lineStart&&(s+=et,t.col=rt,t.lineStart=!1),l===`
20
+ `?(s+=l,t.lineStart=!0,t.col=0,t.inEsc=!1):l==="\x1B"?(t.inEsc=!0,s+=l):t.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(t.inEsc=!1)):(t.col++,s+=l,t.col>=i&&(s+=`
21
+ ${et}`,t.col=rt))}return r(s,n,o)}}var B=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._prevStdoutWrite=process.stdout.write,this._prevStderrWrite=process.stderr.write,this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=nt(this._origStdoutWrite,t),process.stderr.write=nt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
+ `),process.stdout.write=this._prevStdoutWrite||this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
+ `),process.stderr.write=this._prevStderrWrite||this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null,this._prevStdoutWrite=null,this._prevStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
24
+ `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Tt}${JSON.stringify(t)}
25
25
  `;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
26
26
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
27
27
  `)):process.stdout.write.bind(process.stdout)(`${t} ${e}
28
- `)}step(t){this._origStdoutWrite?this._writeDot(L,t):process.stdout.write.bind(process.stdout)(`${R} ${L} ${t}
29
- `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(X,t):process.stdout.write.bind(process.stdout)(`${R} ${X} ${t}
30
- `)}stepMemory(t){let e=h.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Q,e):process.stdout.write.bind(process.stdout)(`${R} ${Q} ${e}
31
- `)}stepFail(t){this._origStdoutWrite?this._writeDot(F,h.red(t)):process.stdout.write.bind(process.stdout)(`${R} ${F} ${h.red(t)}
32
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${kt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:n,details:o}=e;if(o)for(let s of o)this._rawWrite(`${L} ${s}`);let i=n?h.dim(` ${rt(n)}`):"";this._rawWrite(`${Z} ${h.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting();let{duration:o}=n,i=o?h.dim(` ${rt(o)}`):"";this._rawWrite(`${F} ${h.red(e)}`),this._rawWrite(`${Z} ${h.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(h.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},ot=new D;var j=".session-info.json";var zt=Object.freeze(["codebase-memory","code-scan","artifact"]);var It=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"}),Ot=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]),At=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),at=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function G(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r!="object")return String(r);let t=r;return[t.message,t.name,t.code,t.providerErrorText,t.cause?.message??(typeof t.cause=="string"?t.cause:void 0),t.cause?.code].filter(n=>typeof n=="string"||typeof n=="number").join(" | ")}function Rt(r){if(r&&typeof r=="object"){let e=r.providerErrorKind;if(typeof e=="string"&&e.trim())return e.trim()}let t=at.exec(G(r));return t?t[1].toLowerCase():null}function vt(r){if(r&&typeof r=="object"){let n=Number(r.providerErrorStatus);if(Number.isInteger(n)&&n>=100&&n<=599)return n}let t=at.exec(G(r)),e=t&&t[2]?Number(t[2]):NaN;return Number.isInteger(e)?e:null}function xt(r){let t=G(r);if(!t)return"deterministic";for(let o of At)if(o.test(t))return"deterministic";let e=Rt(r);if(e){let o=It[e];if(o==="transient"||o==="deterministic")return o}let n=vt(r);if(n===429||n>=500&&n<=599)return"transient";for(let o of Ot)if(o.test(t))return"transient";return"deterministic"}var it=2,Mt=5;function Pt(r=process.env){let t=r?.AGENT_TRANSIENT_RETRIES;if(t==null||String(t).trim()==="")return it;let e=Number(t);return!Number.isFinite(e)||e<0?it:Math.min(Mt,Math.floor(e))}var B=5e3,lt=3e4;function Wt(r=process.env){let t=r?.AGENT_TRANSIENT_BACKOFF_MS;if(t==null||String(t).trim()==="")return B;let e=Number(t);return!Number.isFinite(e)||e<0?B:Math.min(lt,Math.floor(e))}function st(r,t=Math.random,e=B){if(!(e>0))return 0;let n=Math.max(1,Math.floor(Number(r)||1)),o=Math.min(lt,e*2**(n-1)),i=1+(t()-.5)*.4;return Math.max(1,Math.round(o*i))}function U(r,{env:t=process.env,rand:e=Math.random}={}){let n=Math.max(0,Math.floor(Number(r)||0)),o=Pt(t),i=Wt(t),s=0,p=0;return{get attemptsMade(){return 1+s+p},get transientUsed(){return p},get transientMax(){return o},next(u){let b=xt(u);return s<n?(s+=1,{retry:!0,paidBy:"declared",delayMs:b==="transient"?st(s,e,i):0,failureClass:b,index:s,of:n}):b==="transient"&&p<o?(p+=1,{retry:!0,paidBy:"transient",delayMs:st(p,e,i),failureClass:b,index:p,of:o}):{retry:!1,delayMs:0,failureClass:b}}}}async function St(r,t,e,n){if(!t.retry)return!1;if(n())return d.info(`[workflow] node '${r}': run aborted \u2014 not retrying`),!1;let o=e?.message??String(e??"");return t.paidBy==="transient"?d.warn(`[workflow] node '${r}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(t.delayMs/1e3)}s (transient retry ${t.index}/${t.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):d.info(`[workflow] node '${r}' failed (${t.failureClass}), retrying (${t.index}/${t.of})\u2026`),t.delayMs>0&&(await new Promise(i=>setTimeout(i,t.delayMs)),n())?(d.info(`[workflow] node '${r}': run aborted during backoff \u2014 not retrying`),!1):!0}k.helpers.inc||k.registerHelper("inc",r=>Number(r)+1);k.helpers.json||k.registerHelper("json",r=>JSON.stringify(r,null,2));k.helpers.eq||k.registerHelper("eq",(r,t)=>r===t);var bt=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._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=t.outputSchema&&!this.isZodSchema?new M(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return d.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){d.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let c=U(this.retries),f=null,g=null;for(;;){try{let l=await this.customExecute(t);if(typeof l=="object"&&l!==null&&l.success===!1)g=null,f={success:!1,error:l.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:l.raw||null};else return this.isZodSchema?(d.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){d.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&d.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),g=l,f={success:!1,error:l.message,raw:null}}let E=g??f?.error,I=c.next(E);if(!await St(this.name,I,E,i))break}return f&&(f.attempts=c.attemptsMade),f}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=k.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let p=o("_skillHints");p&&(s=`${p}
28
+ `)}step(t){this._origStdoutWrite?this._writeDot(F,t):process.stdout.write.bind(process.stdout)(`${A} ${F} ${t}
29
+ `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Q,t):process.stdout.write.bind(process.stdout)(`${A} ${Q} ${t}
30
+ `)}stepMemory(t){let e=h.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(tt,e):process.stdout.write.bind(process.stdout)(`${A} ${tt} ${e}
31
+ `)}stepFail(t){this._origStdoutWrite?this._writeDot(D,h.red(t)):process.stdout.write.bind(process.stdout)(`${A} ${D} ${h.red(t)}
32
+ `)}nodeStart(t){(this._origStdoutWrite||this._origStderrWrite)&&(console.warn(`[timeline] node '${t}' started while '${this._currentNode||"?"}' still had the stdout interceptor installed \u2014 a node ended without closing its box; unwrapping`),this._stopIntercepting()),this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${kt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting(),this._currentNode=null;let{duration:n,details:o}=e;if(o)for(let s of o)this._rawWrite(`${F} ${s}`);let i=n?h.dim(` ${j(n)}`):"";this._rawWrite(`${L} ${h.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting(),this._currentNode=null;let{duration:o}=n,i=o?h.dim(` ${j(o)}`):"";this._rawWrite(`${D} ${h.red(e)}`),this._rawWrite(`${L} ${h.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeStopped(t,e={}){this._stopIntercepting(),this._currentNode=null;let{duration:n}=e,o=n?h.dim(` ${j(n)}`):"";this._rawWrite(`${L} ${h.dim("stopped")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(h.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},ot=new B;var G=".session-info.json";var zt=Object.freeze(["codebase-memory","code-scan","artifact"]);var It=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"}),vt=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]),Ot=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),at=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function H(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r!="object")return String(r);let t=r;return[t.message,t.name,t.code,t.providerErrorText,t.cause?.message??(typeof t.cause=="string"?t.cause:void 0),t.cause?.code].filter(n=>typeof n=="string"||typeof n=="number").join(" | ")}function At(r){if(r&&typeof r=="object"){let e=r.providerErrorKind;if(typeof e=="string"&&e.trim())return e.trim()}let t=at.exec(H(r));return t?t[1].toLowerCase():null}function Rt(r){if(r&&typeof r=="object"){let n=Number(r.providerErrorStatus);if(Number.isInteger(n)&&n>=100&&n<=599)return n}let t=at.exec(H(r)),e=t&&t[2]?Number(t[2]):NaN;return Number.isInteger(e)?e:null}function xt(r){let t=H(r);if(!t)return"deterministic";for(let o of Ot)if(o.test(t))return"deterministic";let e=At(r);if(e){let o=It[e];if(o==="transient"||o==="deterministic")return o}let n=Rt(r);if(n===429||n>=500&&n<=599)return"transient";for(let o of vt)if(o.test(t))return"transient";return"deterministic"}var it=2,Mt=5;function Wt(r=process.env){let t=r?.AGENT_TRANSIENT_RETRIES;if(t==null||String(t).trim()==="")return it;let e=Number(t);return!Number.isFinite(e)||e<0?it:Math.min(Mt,Math.floor(e))}var U=5e3,ut=3e4;function Pt(r=process.env){let t=r?.AGENT_TRANSIENT_BACKOFF_MS;if(t==null||String(t).trim()==="")return U;let e=Number(t);return!Number.isFinite(e)||e<0?U:Math.min(ut,Math.floor(e))}function st(r,t=Math.random,e=U){if(!(e>0))return 0;let n=Math.max(1,Math.floor(Number(r)||1)),o=Math.min(ut,e*2**(n-1)),i=1+(t()-.5)*.4;return Math.max(1,Math.round(o*i))}function K(r,{env:t=process.env,rand:e=Math.random}={}){let n=Math.max(0,Math.floor(Number(r)||0)),o=Wt(t),i=Pt(t),s=0,p=0;return{get attemptsMade(){return 1+s+p},get transientUsed(){return p},get transientMax(){return o},next(l){let b=xt(l);return s<n?(s+=1,{retry:!0,paidBy:"declared",delayMs:b==="transient"?st(s,e,i):0,failureClass:b,index:s,of:n}):b==="transient"&&p<o?(p+=1,{retry:!0,paidBy:"transient",delayMs:st(p,e,i),failureClass:b,index:p,of:o}):{retry:!1,delayMs:0,failureClass:b}}}}async function St(r,t,e,n){if(!t.retry)return!1;if(n())return d.info(`[workflow] node '${r}': run aborted \u2014 not retrying`),!1;let o=e?.message??String(e??"");return t.paidBy==="transient"?d.warn(`[workflow] node '${r}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(t.delayMs/1e3)}s (transient retry ${t.index}/${t.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):d.info(`[workflow] node '${r}' failed (${t.failureClass}), retrying (${t.index}/${t.of})\u2026`),t.delayMs>0&&(await new Promise(i=>setTimeout(i,t.delayMs)),n())?(d.info(`[workflow] node '${r}': run aborted during backoff \u2014 not retrying`),!1):!0}k.helpers.inc||k.registerHelper("inc",r=>Number(r)+1);k.helpers.json||k.registerHelper("json",r=>JSON.stringify(r,null,2));k.helpers.eq||k.registerHelper("eq",(r,t)=>r===t);var bt=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._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=t.outputSchema&&!this.isZodSchema?new M(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return d.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){d.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let c=K(this.retries),f=null,g=null;for(;;){try{let u=await this.customExecute(t);if(typeof u=="object"&&u!==null&&u.success===!1)g=null,f={success:!1,error:u.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:u.raw||null};else return this.isZodSchema?(d.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){d.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&d.error(`Schema errors: ${JSON.stringify(u.issues||u.errors,null,2)}`),g=u,f={success:!1,error:u.message,raw:null}}let E=g??f?.error,I=c.next(E);if(!await St(this.name,I,E,i))break}return f&&(f.attempts=c.attemptsMade),f}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=k.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let p=o("_skillHints");p&&(s=`${p}
33
33
 
34
- ${s}`);let u=n(),b=u.cwd||process.cwd(),N=u.sessionPath;try{if(N){let c=V(N,j);if(wt(c)){let g=JSON.parse(_t(c,"utf-8"));g.currentNode=this.name,q(c,JSON.stringify(g,null,2),"utf-8")}let f=V(N,"..",j);if(wt(f))try{let g=JSON.parse(_t(f,"utf-8"));g.currentNode=this.name,q(f,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(c){d.debug(`[workflow] could not update session info: ${c.message}`)}let O=U(this.retries),A=null;for(;;)try{d.debug(`[workflow] node '${this.name}' attempt ${O.attemptsMade-1}`);let c=n().config||{},f=c.agents||{},g=this.config.agent??f[this.name]??null,E={state:n()};g&&(E.preferredAgent=g);let I={workspace:b,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:N,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},l=t?._coreInvokeAgent;l||(l=(await Promise.resolve().then(()=>(yt(),gt))).invokeAgent);let y=await l(s,E,I),a,w;if(typeof y=="string"?(a=y,w=null):y.structured?(a=y.raw||JSON.stringify(y.structured,null,2),w=y.structured):(a=y.raw||JSON.stringify(y,null,2),w=y.extracted||null),N)try{let m=V(N,this.name,"raw_stream_output.txt");jt(Bt(m),{recursive:!0}),q(m,typeof a=="string"?a:JSON.stringify(a),"utf-8")}catch(m){d.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&w){d.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let m=w;if(typeof this.onComplete=="function")try{m=await this.onComplete(n(),w)}catch(_){d.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:m,raw:a}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:a}),raw:a}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(a);return d.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),ot.step("Output parsed"),{success:!0,output:m,raw:a}}return{success:!0,output:a,raw:a}}catch(c){A=c;let f=O.next(c);if(!await St(this.name,f,c,i))break}return{success:!1,error:A.message,raw:null,attempts:O.attemptsMade}}};export{bt as Node};
34
+ ${s}`);let l=n(),b=l.cwd||process.cwd(),N=l.sessionPath;try{if(N){let c=Z(N,G);if(wt(c)){let g=JSON.parse(_t(c,"utf-8"));g.currentNode=this.name,Y(c,JSON.stringify(g,null,2),"utf-8")}let f=Z(N,"..",G);if(wt(f))try{let g=JSON.parse(_t(f,"utf-8"));g.currentNode=this.name,Y(f,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(c){d.debug(`[workflow] could not update session info: ${c.message}`)}let v=K(this.retries),O=null;for(;;)try{d.debug(`[workflow] node '${this.name}' attempt ${v.attemptsMade-1}`);let c=n().config||{},f=c.agents||{},g=this.config.agent??f[this.name]??null,E={state:n()};g&&(E.preferredAgent=g);let I={workspace:b,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:N,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},u=t?._coreInvokeAgent;u||(u=(await Promise.resolve().then(()=>(yt(),gt))).invokeAgent);let y=await u(s,E,I),a,w;if(typeof y=="string"?(a=y,w=null):y.structured?(a=y.raw||JSON.stringify(y.structured,null,2),w=y.structured):(a=y.raw||JSON.stringify(y,null,2),w=y.extracted||null),N)try{let m=Z(N,this.name,"raw_stream_output.txt");jt(Bt(m),{recursive:!0}),Y(m,typeof a=="string"?a:JSON.stringify(a),"utf-8")}catch(m){d.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&w){d.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let m=w;if(typeof this.onComplete=="function")try{m=await this.onComplete(n(),w)}catch(_){d.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:m,raw:a}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:a}),raw:a}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(a);return d.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),ot.step("Output parsed"),{success:!0,output:m,raw:a}}return{success:!0,output:a,raw:a}}catch(c){O=c;let f=v.next(c);if(!await St(this.name,f,c,i))break}return{success:!1,error:O.message,raw:null,attempts:v.attemptsMade}}};export{bt as Node};
@@ -68,10 +68,16 @@ export { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS };
68
68
  * On the HTTP path, a string is also sent as `resultPath` so the
69
69
  * control plane can persist only that declared result before applying
70
70
  * its final-state size cap. Function extractors remain local-only.
71
+ * @param {boolean} [options.includeExecutionMetadata=false]
72
+ * Sync mode only. Return `{ executionId, output }`, where `output` is the
73
+ * same projected value this call would otherwise return. This exposes the
74
+ * child identity the dispatcher already owns without making callers infer
75
+ * it from process-global environment or query the execution list.
71
76
  *
72
77
  * @returns {Promise<any>}
73
78
  * async: `{ jobId, status: 'accepted' }`
74
- * sync : the child's final state (or `getPath(state, output)`)
79
+ * sync : the child's final state (or `getPath(state, output)`), optionally
80
+ * wrapped as `{ executionId, output }`
75
81
  *
76
82
  * @throws {Error}
77
83
  * - Network / 5xx errors from the trigger endpoint
@@ -1 +1 @@
1
- var K=()=>{},ge={debug:K,info:K,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},N=Symbol.for("@zibby/agent-workflow.logger");globalThis[N]||(globalThis[N]={impl:ge});var L=globalThis[N];var h={debug:(...e)=>L.impl.debug?.(...e),info:(...e)=>L.impl.info?.(...e),warn:(...e)=>L.impl.warn?.(...e),error:(...e)=>L.impl.error?.(...e)};import{mkdirSync as Ie,existsSync as M,statSync as re,readdirSync as oe,rmSync as Ee}from"node:fs";import{spawn as ee}from"node:child_process";import{join as $}from"node:path";import{pathToFileURL as Te}from"node:url";import{AsyncLocalStorage as me}from"node:async_hooks";import{AsyncLocalStorage as he}from"node:async_hooks";var z=new he;function B(){let e=z.getStore();return e||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 X(e,t){let n=z.getStore()||B(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return z.run(r,t)}var J=new Map,q=new Map,W=new Map;function Y(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");J.set(e,t),q.set(e,"ready"),W.set(e,{...n,cachedAt:Date.now()})}function V(e,t){q.set(e,"failed"),W.set(e,{error:t?.message||String(t),failedAt:Date.now()}),J.delete(e)}function Z(e){return q.get(e)==="ready"?J.get(e):null}var x=3e4,Q=15e3;function C(e,t,n=process.env){let r=Number(n[e]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):t}function k(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function G(e,t){return k(C(e,t),e)}function S(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}function R(e,t){return t.aborted?(Promise.resolve(e).catch(()=>{}),Promise.reject(t.reason)):new Promise((n,r)=>{let o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),Promise.resolve(e).then(s=>{t.removeEventListener("abort",o),n(s)},s=>{t.removeEventListener("abort",o),r(s)})})}var H=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function _e(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var E=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}};function j(e,t,n,r="timeout",o=null){let s=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(n/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=t,s.subgraphStatus=r,o&&(s.subgraphTransportError=o),s}function we(e,t=process.env,n=process.uptime()){let r=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(n)&&n>0?n*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(r===null&&a===null)return null;let i=r===null?a:a===null?r:Math.min(r,a);return Math.max(1,i)}function Se(e,t){let n=new AbortController,r=!1,o=null,s=()=>{n.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),t!=null&&!n.signal.aborted&&(o=setTimeout(()=>{r=!0,n.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var te=new me,ne=Promise.resolve();async function Ae(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(n.length===0)return t();let r=te.getStore()===!0,o=null;if(!r){let a=ne;ne=new Promise(i=>{o=i}),await a}let s=new Map;try{for(let[a,i]of n)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return h.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await te.run(!0,t)}finally{for(let[a,i]of s)i===void 0?delete process.env[a]:process.env[a]=i;o&&o()}}function Re(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!r||!o)throw new E("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:o}}async function $e({apiBase:e,authToken:t,body:n}){let r=G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal})}catch(a){throw new E(S(a)?"begin-timeout":"network",S(a)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${a.message}`)}let s=null;try{s=await o.json()}catch(a){if(S(a))throw new E("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let a=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw a.code="SUBGRAPH_NOT_FOUND",a.status=404,a}if(o.status===429){let a=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${a.used??"?"}/${a.limit??"?"} on ${a.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=a,i}if(o.status===400&&s?.validationErrors){let a=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw a.code="SUBGRAPH_INVALID_INPUT",a.status=400,a.validationErrors=s.validationErrors,a.missing=s.missing,a}throw new E("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function P({apiBase:e,authToken:t,payload:n}){let r=G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal});o.ok||h.warn(`[in-process subgraph] finalize returned ${o.status} for ${n.childExecutionId}`)}catch(o){h.warn(`[in-process subgraph] finalize ${S(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Oe(e,t){let n=$(t,".ready"),r=$(t,"graph.mjs");if(M(n)&&M(r))return;Ie(t,{recursive:!0});let o=$(t,".lock"),s=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),g=a(o,"wx");i(g),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(M(n)&&M(r))return;await new Promise(i=>setTimeout(i,100))}throw new E("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((g,d)=>{let _=Math.ceil(1e4/1e3),v=Math.ceil(C("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),f=ee("curl",["-fsSL","--connect-timeout",String(_),"--max-time",String(v),e],{stdio:["ignore","pipe","inherit"]}),I=ee("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(I.stdin);let y,p,U=()=>{if(y!==void 0&&p!==void 0){if(y!==0)return d(new Error(`curl exited ${y}`));if(p!==0)return d(new Error(`tar exited ${p}`));g()}};f.on("close",A=>{y=A,U()}),I.on("close",A=>{p=A,U()}),f.on("error",d),I.on("error",d)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(o)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new E("bundle-extract-failed",a.message)}}async function Pe(e){let t=$(e,"graph.mjs");if(!M(t))throw new E("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Te(t).href)}catch(o){throw new E("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new E("entry-class-missing","no buildGraph() class export found");return r}async function ae(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=B(),r;try{r=Re()}catch(c){throw c}h.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await $e({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:g,workflowVersion:d,workflowUuid:_,bundleReady:v,nodeConfigs:f}=o,I=_e();if(a&&a!==I)throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,discard:!0}}),new E("runtime-mismatch",`${I} vs ${a}`);if(!v||!i)throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,discard:!0}}),new E("no-bundle","workflow bundle not built yet");let y=Z(e);if(!y){let c=$(H,`${_}@${d||"0"}`);try{await Oe(i,c);try{Ue()}catch{}}catch(l){throw l.fallback&&await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:l.message,code:l.reason}}}),l}try{y=await Pe(c),Y(e,y,{workflowUuid:_,version:d,runtimeTag:a,cacheDir:c})}catch(l){throw V(e,l),await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:l.message,code:l.reason||"IMPORT_FAILED"}}}),l.fallback?l:new E("import-failed",l.message)}}let p=Date.now(),U=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,A=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,D={...t.input||{},...A?{nodeConfigs:f}:{}},w=we(t.timeoutMs),O=Se(t.signal,w),T,u;try{T=await Ae(U,async()=>{let l=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return X({executionId:s,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>l.run(t.parentAgent,D,{signal:O.signal}))}),u=T&&typeof T=="object"&&"state"in T?T.state:T}catch(c){let l=O.timedOut();throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:l?"timeout":"failed",error:l?{message:`aborted at the declared ${Math.round(w/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-p}}),l?j(e,s,w):c}finally{O.dispose()}if(T&&typeof T=="object"&&T.stoppedExternally){let c=O.timedOut();if(await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:c?"timeout":"canceled",finalState:u,durationMs:Date.now()-p}}),c)throw j(e,s,w);let l=new Error(`Sub-graph '${e}' canceled by parent abort`);throw l.code="SUBGRAPH_CANCELED",l.subgraphJobId=s,l}return await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:u,durationMs:Date.now()-p}}),{finalState:u,executionId:s}}function Me(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),o;try{o=re(r)}catch{continue}if(o.isDirectory()){let s;try{s=oe(r)}catch{continue}for(let a of s)n.push($(r,a))}else t+=o.size}return t}function Ue({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!M(H))return{evicted:0,freedBytes:0};let t=oe(H),n=[],r=0;for(let i of t){let g=$(H,i),d;try{d=re(g)}catch{continue}let _=d.isDirectory()?Me(g):d.size;r+=_,n.push({name:i,full:g,size:_,mtimeMs:d.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,g)=>i.mtimeMs-g.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let i of n){if(r-s<=o)break;if(!M($(i.full,".lock")))try{Ee(i.full,{recursive:!0,force:!0}),s+=i.size,a+=1}catch(g){h.debug(`[sub-graph cache] evict skip ${i.name}: ${g.message}`)}}return a>0&&h.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:r-s}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ve=2e3,Be=600*1e3,xe=new Set(["completed","failed","canceled","cancelled","timeout"]);var ie=()=>G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Ce(e){let t=C("SUBGRAPH_POLL_TIMEOUT_MS",15e3),n=Math.max(1,Math.min(t,e-Date.now()));return k(n,"SUBGRAPH_POLL_TIMEOUT_MS")}function ce(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function ue(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function le(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function de(){return process.env.EXECUTION_ID||null}function se(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}async function Ge(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=B();t.parentAgent==null&&n.agent&&(t.parentAgent=n.agent),t.signal==null&&n.signal&&(t.signal=n.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:Be;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async&&!t.participantBindingId)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await ae(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),c=se(u,t.output);return h.info(`[sub-graph] '${e}' completed in-process`),c}catch(u){if(u instanceof E||u?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let s=ce(),a=ue(),i=le(),g=de(),d=t.participantBindingId?"participant":e,_=`${s}/projects/${encodeURIComponent(a)}/workflows/${encodeURIComponent(d)}/trigger`,v={input:t.input||{},...g?{parentExecutionId:g}:{},...!t.async&&typeof t.output=="string"&&t.output.trim()?{resultPath:t.output.trim()}:{},...t.conversationId?{conversationId:t.conversationId}:{},...typeof t.idempotencyKey=="string"&&t.idempotencyKey?{idempotencyKey:t.idempotencyKey.slice(0,200)}:{},...t.participantBindingId?{participantBindingId:t.participantBindingId}:{},...t.protocolId?{protocolId:t.protocolId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${g||"<none>"}`);let f=ie(),I;try{I=await R(fetch(_,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(v),signal:f.signal}),f.signal)}catch(u){if(!S(u))throw u;let c=new Error(`Sub-graph '${e}' trigger TIMED OUT ${f.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw c.code="SUBGRAPH_TRIGGER_TIMEOUT",c.subgraph=e,c.timedOut=!0,c.cause=u,c}if(!I.ok){let u=null,c="";try{u=await R(I.json(),f.signal),c=u?.error||u?.message||JSON.stringify(u)}catch{c=await R(I.text(),f.signal).catch(()=>"")}if(I.status===429){let m=u?.quotaInfo||{},b=new Error(`Sub-graph '${e}' blocked by execution quota (${m.used??"?"}/${m.limit??"?"} on plan ${m.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw b.code="SUBGRAPH_QUOTA_EXCEEDED",b.status=429,b.subgraph=e,b.quotaInfo=m,b}if(I.status===400){let m=new Error(`Sub-graph '${e}' rejected input: ${c}`);throw m.code="SUBGRAPH_INVALID_INPUT",m.status=400,m.subgraph=e,m.validationErrors=u?.validationErrors||null,m.missing=u?.missing||null,m}let l=new Error(`Sub-graph '${e}' trigger rejected (${I.status}): ${c}`);throw l.code="SUBGRAPH_TRIGGER_FAILED",l.status=I.status,l.subgraph=e,l}let y;try{y=await R(I.json(),f.signal)}catch(u){if(!S(u))throw u;let c=new Error(`Sub-graph '${e}' trigger body read TIMED OUT ${f.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw c.code="SUBGRAPH_TRIGGER_TIMEOUT",c.subgraph=e,c.timedOut=!0,c.cause=u,c}let p=y?.data?.jobId||y?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(y).slice(0,200)}`);if(t.async)return h.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let U=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ve,A=`${s}/executions/${encodeURIComponent(p)}`,D=Date.now()+o,w="accepted",O=0,T=null;for(;Date.now()<D;){await new Promise(b=>setTimeout(b,U)),O+=1;let u=Ce(D),c;try{c=await R(fetch(A,{headers:{Authorization:`Bearer ${i}`},signal:u.signal}),u.signal)}catch(b){T=S(b)?`poll TIMED OUT ${u.label}`:b?.message||String(b),h.warn(`[sub-graph] status poll for ${p} could not reach the API (${T}), will retry`);continue}if(!c.ok){if(c.status>=500){h.warn(`[sub-graph] status poll for ${p} returned ${c.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${c.status}`)}let l;try{l=await R(c.json(),u.signal)}catch(b){T=S(b)?`poll body read TIMED OUT ${u.label}`:b?.message||String(b),h.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${T}), will retry`);continue}let m=l?.data||l?.execution||l;if(w=m?.status||w,xe.has(w)){if(w!=="completed"){let F=new Error(`Sub-graph '${e}' (${p}) ended in status '${w}'`);throw F.subgraphJobId=p,F.subgraphStatus=w,F}let b=m?.finalState||m?.state||{},pe=se(b,t.output);return h.info(`[sub-graph] '${e}' (${p}) completed after ${O} polls`),pe}}try{let u=k(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),c=await R(fetch(`${A}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${i}`},signal:u.signal}),u.signal);!c.ok&&c.status!==400&&c.status!==404&&h.warn(`[sub-graph] best-effort cancel for ${p} returned ${c.status}`)}catch(u){h.warn(`[sub-graph] best-effort cancel for ${p} failed: ${u?.message||String(u)}`)}throw j(e,p,o,w,T)}async function et(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!t.protocolId||typeof t.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return Ge("participant",{...t,async:t.async!==!1,participantBindingId:e})}async function tt(e){if(!e||typeof e!="string")throw new Error("listParticipants: protocolId (string) is required");let t=ce(),n=ue(),r=le(),o=de();if(!o){let d=new Error("Collaboration requires a running parent execution");throw d.code="PARENT_EXECUTION_REQUIRED",d}let s=`${t}/projects/${encodeURIComponent(n)}/workflows/participant/trigger`,a=ie(),i;try{i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:e}),signal:a.signal})}catch(d){let _=new Error(`Participant roster lookup failed: ${d?.message||String(d)}`);throw _.code=S(d)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",_.cause=d,_}let g=null;try{g=await i.json()}catch{}if(!i.ok){let d=new Error(g?.error||`Participant roster lookup rejected (${i.status})`);throw d.code=g?.code||"PARTICIPANT_ROSTER_REJECTED",d.status=i.status,d}return Array.isArray(g?.participants)?g.participants:[]}export{Q as SUBGRAPH_POLL_TIMEOUT_MS,x as SUBGRAPH_TRIGGER_TIMEOUT_MS,et as dispatchParticipant,Ge as dispatchSubgraph,tt as listParticipants};
1
+ var K=()=>{},ge={debug:K,info:K,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},N=Symbol.for("@zibby/agent-workflow.logger");globalThis[N]||(globalThis[N]={impl:ge});var L=globalThis[N];var h={debug:(...e)=>L.impl.debug?.(...e),info:(...e)=>L.impl.info?.(...e),warn:(...e)=>L.impl.warn?.(...e),error:(...e)=>L.impl.error?.(...e)};import{mkdirSync as Ie,existsSync as M,statSync as re,readdirSync as oe,rmSync as Ee}from"node:fs";import{spawn as ee}from"node:child_process";import{join as $}from"node:path";import{pathToFileURL as Te}from"node:url";import{AsyncLocalStorage as me}from"node:async_hooks";import{AsyncLocalStorage as he}from"node:async_hooks";var z=new he;function x(){let e=z.getStore();return e||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 X(e,t){let n=z.getStore()||x(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return z.run(r,t)}var J=new Map,q=new Map,W=new Map;function Y(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");J.set(e,t),q.set(e,"ready"),W.set(e,{...n,cachedAt:Date.now()})}function V(e,t){q.set(e,"failed"),W.set(e,{error:t?.message||String(t),failedAt:Date.now()}),J.delete(e)}function Z(e){return q.get(e)==="ready"?J.get(e):null}var B=3e4,Q=15e3;function C(e,t,n=process.env){let r=Number(n[e]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):t}function k(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function G(e,t){return k(C(e,t),e)}function S(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}function R(e,t){return t.aborted?(Promise.resolve(e).catch(()=>{}),Promise.reject(t.reason)):new Promise((n,r)=>{let o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),Promise.resolve(e).then(s=>{t.removeEventListener("abort",o),n(s)},s=>{t.removeEventListener("abort",o),r(s)})})}var H=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function _e(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var E=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}};function j(e,t,n,r="timeout",o=null){let s=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(n/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=t,s.subgraphStatus=r,o&&(s.subgraphTransportError=o),s}function we(e,t=process.env,n=process.uptime()){let r=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(n)&&n>0?n*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(r===null&&a===null)return null;let i=r===null?a:a===null?r:Math.min(r,a);return Math.max(1,i)}function Se(e,t){let n=new AbortController,r=!1,o=null,s=()=>{n.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),t!=null&&!n.signal.aborted&&(o=setTimeout(()=>{r=!0,n.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var te=new me,ne=Promise.resolve();async function Ae(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(n.length===0)return t();let r=te.getStore()===!0,o=null;if(!r){let a=ne;ne=new Promise(i=>{o=i}),await a}let s=new Map;try{for(let[a,i]of n)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return h.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await te.run(!0,t)}finally{for(let[a,i]of s)i===void 0?delete process.env[a]:process.env[a]=i;o&&o()}}function Re(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!r||!o)throw new E("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:o}}async function $e({apiBase:e,authToken:t,body:n}){let r=G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal})}catch(a){throw new E(S(a)?"begin-timeout":"network",S(a)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${a.message}`)}let s=null;try{s=await o.json()}catch(a){if(S(a))throw new E("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let a=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw a.code="SUBGRAPH_NOT_FOUND",a.status=404,a}if(o.status===429){let a=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${a.used??"?"}/${a.limit??"?"} on ${a.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=a,i}if(o.status===400&&s?.validationErrors){let a=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw a.code="SUBGRAPH_INVALID_INPUT",a.status=400,a.validationErrors=s.validationErrors,a.missing=s.missing,a}throw new E("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function P({apiBase:e,authToken:t,payload:n}){let r=G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal});o.ok||h.warn(`[in-process subgraph] finalize returned ${o.status} for ${n.childExecutionId}`)}catch(o){h.warn(`[in-process subgraph] finalize ${S(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Oe(e,t){let n=$(t,".ready"),r=$(t,"graph.mjs");if(M(n)&&M(r))return;Ie(t,{recursive:!0});let o=$(t,".lock"),s=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),g=a(o,"wx");i(g),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(M(n)&&M(r))return;await new Promise(i=>setTimeout(i,100))}throw new E("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((g,d)=>{let _=Math.ceil(1e4/1e3),U=Math.ceil(C("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),f=ee("curl",["-fsSL","--connect-timeout",String(_),"--max-time",String(U),e],{stdio:["ignore","pipe","inherit"]}),I=ee("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(I.stdin);let y,p,v=()=>{if(y!==void 0&&p!==void 0){if(y!==0)return d(new Error(`curl exited ${y}`));if(p!==0)return d(new Error(`tar exited ${p}`));g()}};f.on("close",A=>{y=A,v()}),I.on("close",A=>{p=A,v()}),f.on("error",d),I.on("error",d)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(o)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new E("bundle-extract-failed",a.message)}}async function Pe(e){let t=$(e,"graph.mjs");if(!M(t))throw new E("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Te(t).href)}catch(o){throw new E("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new E("entry-class-missing","no buildGraph() class export found");return r}async function ae(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=x(),r;try{r=Re()}catch(c){throw c}h.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await $e({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:g,workflowVersion:d,workflowUuid:_,bundleReady:U,nodeConfigs:f}=o,I=_e();if(a&&a!==I)throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,discard:!0}}),new E("runtime-mismatch",`${I} vs ${a}`);if(!U||!i)throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,discard:!0}}),new E("no-bundle","workflow bundle not built yet");let y=Z(e);if(!y){let c=$(H,`${_}@${d||"0"}`);try{await Oe(i,c);try{ve()}catch{}}catch(l){throw l.fallback&&await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:l.message,code:l.reason}}}),l}try{y=await Pe(c),Y(e,y,{workflowUuid:_,version:d,runtimeTag:a,cacheDir:c})}catch(l){throw V(e,l),await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:l.message,code:l.reason||"IMPORT_FAILED"}}}),l.fallback?l:new E("import-failed",l.message)}}let p=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,A=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,D={...t.input||{},...A?{nodeConfigs:f}:{}},w=we(t.timeoutMs),O=Se(t.signal,w),T,u;try{T=await Ae(v,async()=>{let l=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return X({executionId:s,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>l.run(t.parentAgent,D,{signal:O.signal}))}),u=T&&typeof T=="object"&&"state"in T?T.state:T}catch(c){let l=O.timedOut();throw await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:l?"timeout":"failed",error:l?{message:`aborted at the declared ${Math.round(w/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-p}}),l?j(e,s,w):c}finally{O.dispose()}if(T&&typeof T=="object"&&T.stoppedExternally){let c=O.timedOut();if(await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:c?"timeout":"canceled",finalState:u,durationMs:Date.now()-p}}),c)throw j(e,s,w);let l=new Error(`Sub-graph '${e}' canceled by parent abort`);throw l.code="SUBGRAPH_CANCELED",l.subgraphJobId=s,l}return await P({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:u,durationMs:Date.now()-p}}),{finalState:u,executionId:s}}function Me(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),o;try{o=re(r)}catch{continue}if(o.isDirectory()){let s;try{s=oe(r)}catch{continue}for(let a of s)n.push($(r,a))}else t+=o.size}return t}function ve({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!M(H))return{evicted:0,freedBytes:0};let t=oe(H),n=[],r=0;for(let i of t){let g=$(H,i),d;try{d=re(g)}catch{continue}let _=d.isDirectory()?Me(g):d.size;r+=_,n.push({name:i,full:g,size:_,mtimeMs:d.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,g)=>i.mtimeMs-g.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let i of n){if(r-s<=o)break;if(!M($(i.full,".lock")))try{Ee(i.full,{recursive:!0,force:!0}),s+=i.size,a+=1}catch(g){h.debug(`[sub-graph cache] evict skip ${i.name}: ${g.message}`)}}return a>0&&h.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:r-s}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var Ue=2e3,xe=600*1e3,Be=new Set(["completed","failed","canceled","cancelled","timeout"]);var ie=()=>G("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Ce(e){let t=C("SUBGRAPH_POLL_TIMEOUT_MS",15e3),n=Math.max(1,Math.min(t,e-Date.now()));return k(n,"SUBGRAPH_POLL_TIMEOUT_MS")}function ce(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function ue(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function le(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function de(){return process.env.EXECUTION_ID||null}function Ge(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}function se(e,t,n,r){let o=Ge(t,n);return r?{executionId:e,output:o}:o}async function De(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=x();t.parentAgent==null&&n.agent&&(t.parentAgent=n.agent),t.signal==null&&n.signal&&(t.signal=n.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:xe;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async&&!t.participantBindingId)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u,executionId:c}=await ae(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),l=se(c,u,t.output,t.includeExecutionMetadata===!0);return h.info(`[sub-graph] '${e}' completed in-process`),l}catch(u){if(u instanceof E||u?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let s=ce(),a=ue(),i=le(),g=de(),d=t.participantBindingId?"participant":e,_=`${s}/projects/${encodeURIComponent(a)}/workflows/${encodeURIComponent(d)}/trigger`,U={input:t.input||{},...g?{parentExecutionId:g}:{},...!t.async&&typeof t.output=="string"&&t.output.trim()?{resultPath:t.output.trim()}:{},...t.conversationId?{conversationId:t.conversationId}:{},...typeof t.idempotencyKey=="string"&&t.idempotencyKey?{idempotencyKey:t.idempotencyKey.slice(0,200)}:{},...t.participantBindingId?{participantBindingId:t.participantBindingId}:{},...t.protocolId?{protocolId:t.protocolId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${g||"<none>"}`);let f=ie(),I;try{I=await R(fetch(_,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(U),signal:f.signal}),f.signal)}catch(u){if(!S(u))throw u;let c=new Error(`Sub-graph '${e}' trigger TIMED OUT ${f.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw c.code="SUBGRAPH_TRIGGER_TIMEOUT",c.subgraph=e,c.timedOut=!0,c.cause=u,c}if(!I.ok){let u=null,c="";try{u=await R(I.json(),f.signal),c=u?.error||u?.message||JSON.stringify(u)}catch{c=await R(I.text(),f.signal).catch(()=>"")}if(I.status===429){let m=u?.quotaInfo||{},b=new Error(`Sub-graph '${e}' blocked by execution quota (${m.used??"?"}/${m.limit??"?"} on plan ${m.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw b.code="SUBGRAPH_QUOTA_EXCEEDED",b.status=429,b.subgraph=e,b.quotaInfo=m,b}if(I.status===400){let m=new Error(`Sub-graph '${e}' rejected input: ${c}`);throw m.code="SUBGRAPH_INVALID_INPUT",m.status=400,m.subgraph=e,m.validationErrors=u?.validationErrors||null,m.missing=u?.missing||null,m}let l=new Error(`Sub-graph '${e}' trigger rejected (${I.status}): ${c}`);throw l.code="SUBGRAPH_TRIGGER_FAILED",l.status=I.status,l.subgraph=e,l}let y;try{y=await R(I.json(),f.signal)}catch(u){if(!S(u))throw u;let c=new Error(`Sub-graph '${e}' trigger body read TIMED OUT ${f.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw c.code="SUBGRAPH_TRIGGER_TIMEOUT",c.subgraph=e,c.timedOut=!0,c.cause=u,c}let p=y?.data?.jobId||y?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(y).slice(0,200)}`);if(t.async)return h.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let v=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:Ue,A=`${s}/executions/${encodeURIComponent(p)}`,D=Date.now()+o,w="accepted",O=0,T=null;for(;Date.now()<D;){await new Promise(b=>setTimeout(b,v)),O+=1;let u=Ce(D),c;try{c=await R(fetch(A,{headers:{Authorization:`Bearer ${i}`},signal:u.signal}),u.signal)}catch(b){T=S(b)?`poll TIMED OUT ${u.label}`:b?.message||String(b),h.warn(`[sub-graph] status poll for ${p} could not reach the API (${T}), will retry`);continue}if(!c.ok){if(c.status>=500){h.warn(`[sub-graph] status poll for ${p} returned ${c.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${c.status}`)}let l;try{l=await R(c.json(),u.signal)}catch(b){T=S(b)?`poll body read TIMED OUT ${u.label}`:b?.message||String(b),h.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${T}), will retry`);continue}let m=l?.data||l?.execution||l;if(w=m?.status||w,Be.has(w)){if(w!=="completed"){let F=new Error(`Sub-graph '${e}' (${p}) ended in status '${w}'`);throw F.subgraphJobId=p,F.subgraphStatus=w,F}let b=m?.finalState||m?.state||{},pe=se(p,b,t.output,t.includeExecutionMetadata===!0);return h.info(`[sub-graph] '${e}' (${p}) completed after ${O} polls`),pe}}try{let u=k(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),c=await R(fetch(`${A}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${i}`},signal:u.signal}),u.signal);!c.ok&&c.status!==400&&c.status!==404&&h.warn(`[sub-graph] best-effort cancel for ${p} returned ${c.status}`)}catch(u){h.warn(`[sub-graph] best-effort cancel for ${p} failed: ${u?.message||String(u)}`)}throw j(e,p,o,w,T)}async function tt(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!t.protocolId||typeof t.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return De("participant",{...t,async:t.async!==!1,participantBindingId:e})}async function nt(e){if(!e||typeof e!="string")throw new Error("listParticipants: protocolId (string) is required");let t=ce(),n=ue(),r=le(),o=de();if(!o){let d=new Error("Collaboration requires a running parent execution");throw d.code="PARENT_EXECUTION_REQUIRED",d}let s=`${t}/projects/${encodeURIComponent(n)}/workflows/participant/trigger`,a=ie(),i;try{i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:e}),signal:a.signal})}catch(d){let _=new Error(`Participant roster lookup failed: ${d?.message||String(d)}`);throw _.code=S(d)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",_.cause=d,_}let g=null;try{g=await i.json()}catch{}if(!i.ok){let d=new Error(g?.error||`Participant roster lookup rejected (${i.status})`);throw d.code=g?.code||"PARTICIPANT_ROSTER_REJECTED",d.status=i.status,d}return Array.isArray(g?.participants)?g.participants:[]}export{Q as SUBGRAPH_POLL_TIMEOUT_MS,B as SUBGRAPH_TRIGGER_TIMEOUT_MS,tt as dispatchParticipant,De as dispatchSubgraph,nt as listParticipants};
@@ -33,6 +33,8 @@ declare class Timeline {
33
33
  _origStderrWrite?: any;
34
34
  _origStdoutWrite?: any;
35
35
  _outState?: any;
36
+ _prevStdoutWrite?: any;
37
+ _prevStderrWrite?: any;
36
38
  constructor();
37
39
  get isInsideNode(): boolean;
38
40
  _startIntercepting(): void;
@@ -57,6 +59,13 @@ declare class Timeline {
57
59
  nodeStart(name: any): void;
58
60
  nodeComplete(name: any, opts?: any): void;
59
61
  nodeFailed(name: any, error: any, opts?: any): void;
62
+ /**
63
+ * The node was cut short by a deliberate stop (external abort / stop file).
64
+ * Not a failure — no red line — but the box MUST still close: this is the
65
+ * third way out of a node, and the one that used to leave the stdout
66
+ * interceptor installed (see nodeStart).
67
+ */
68
+ nodeStopped(name: any, opts?: any): void;
60
69
  route(from: any, to: any): void;
61
70
  graphComplete(): void;
62
71
  }
package/dist/timeline.js CHANGED
@@ -1,14 +1,14 @@
1
- import e from"chalk";var I="__WORKFLOW_GRAPH_LOG__",c=e.gray("\u2502"),E=e.gray("\u250C"),S=e.gray("\u2514"),a=e.green("\u25C6"),p=e.hex("#c084fc")("\u25C6"),W=e.hex("#2dd4bf")("\u25C6"),h=e.red("\u25C6"),f=`${c} `,w=2;function g(_){return _<1e3?`${_}ms`:`${(_/1e3).toFixed(1)}s`}function $(_,t){return(r,o,n)=>{if(typeof r!="string")return _(r,o,n);let d=process.stdout.columns||120,s="";for(let u=0;u<r.length;u++){let i=r[u];t.lineStart&&(s+=f,t.col=w,t.lineStart=!1),i===`
2
- `?(s+=i,t.lineStart=!0,t.col=0,t.inEsc=!1):i==="\x1B"?(t.inEsc=!0,s+=i):t.inEsc?(s+=i,(i>="A"&&i<="Z"||i>="a"&&i<="z")&&(t.inEsc=!1)):(t.col++,s+=i,t.col>=d&&(s+=`
3
- ${f}`,t.col=w))}return _(s,o,n)}}var l=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 t={lineStart:!0,col:0,inEsc:!1},r={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=r,process.stdout.write=$(this._origStdoutWrite,t),process.stderr.write=$(this._origStderrWrite,r)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
4
- `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
5
- `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
1
+ import e from"chalk";var I="__WORKFLOW_GRAPH_LOG__",h=e.gray("\u2502"),y=e.gray("\u250C"),c=e.gray("\u2514"),a=e.green("\u25C6"),W=e.hex("#c084fc")("\u25C6"),w=e.hex("#2dd4bf")("\u25C6"),p=e.red("\u25C6"),g=`${h} `,f=2;function l(d){return d<1e3?`${d}ms`:`${(d/1e3).toFixed(1)}s`}function $(d,t){return(r,i,o)=>{if(typeof r!="string")return d(r,i,o);let _=process.stdout.columns||120,n="";for(let u=0;u<r.length;u++){let s=r[u];t.lineStart&&(n+=g,t.col=f,t.lineStart=!1),s===`
2
+ `?(n+=s,t.lineStart=!0,t.col=0,t.inEsc=!1):s==="\x1B"?(t.inEsc=!0,n+=s):t.inEsc?(n+=s,(s>="A"&&s<="Z"||s>="a"&&s<="z")&&(t.inEsc=!1)):(t.col++,n+=s,t.col>=_&&(n+=`
3
+ ${g}`,t.col=f))}return d(n,i,o)}}var S=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._prevStdoutWrite=process.stdout.write,this._prevStderrWrite=process.stderr.write,this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},r={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=r,process.stdout.write=$(this._origStdoutWrite,t),process.stderr.write=$(this._origStderrWrite,r)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
4
+ `),process.stdout.write=this._prevStdoutWrite||this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
5
+ `),process.stderr.write=this._prevStderrWrite||this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null,this._prevStdoutWrite=null,this._prevStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
6
6
  `)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let r=`${I}${JSON.stringify(t)}
7
7
  `;this._origStdoutWrite?this._origStdoutWrite(r):process.stdout.write(r)}_writeDot(t,r){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
8
8
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${r}
9
9
  `)):process.stdout.write.bind(process.stdout)(`${t} ${r}
10
- `)}step(t){this._origStdoutWrite?this._writeDot(a,t):process.stdout.write.bind(process.stdout)(`${c} ${a} ${t}
11
- `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(p,t):process.stdout.write.bind(process.stdout)(`${c} ${p} ${t}
12
- `)}stepMemory(t){let r=e.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(W,r):process.stdout.write.bind(process.stdout)(`${c} ${W} ${r}
13
- `)}stepFail(t){this._origStdoutWrite?this._writeDot(h,e.red(t)):process.stdout.write.bind(process.stdout)(`${c} ${h} ${e.red(t)}
14
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${E} ${t}`),this._startIntercepting()}nodeComplete(t,r={}){this._stopIntercepting();let{duration:o,details:n}=r;if(n)for(let s of n)this._rawWrite(`${a} ${s}`);let d=o?e.dim(` ${g(o)}`):"";this._rawWrite(`${S} ${e.green("done")}${d}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,r,o={}){this._stopIntercepting();let{duration:n}=o,d=n?e.dim(` ${g(n)}`):"";this._rawWrite(`${h} ${e.red(r)}`),this._rawWrite(`${S} ${e.red("failed")}${d}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,r){this._rawWrite(e.dim(` ${t} \u2192 ${r}`)),this._rawWrite("")}graphComplete(){}},y=new l;var R=y;export{l as Timeline,I as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,R as default,y as timeline};
10
+ `)}step(t){this._origStdoutWrite?this._writeDot(a,t):process.stdout.write.bind(process.stdout)(`${h} ${a} ${t}
11
+ `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(W,t):process.stdout.write.bind(process.stdout)(`${h} ${W} ${t}
12
+ `)}stepMemory(t){let r=e.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(w,r):process.stdout.write.bind(process.stdout)(`${h} ${w} ${r}
13
+ `)}stepFail(t){this._origStdoutWrite?this._writeDot(p,e.red(t)):process.stdout.write.bind(process.stdout)(`${h} ${p} ${e.red(t)}
14
+ `)}nodeStart(t){(this._origStdoutWrite||this._origStderrWrite)&&(console.warn(`[timeline] node '${t}' started while '${this._currentNode||"?"}' still had the stdout interceptor installed \u2014 a node ended without closing its box; unwrapping`),this._stopIntercepting()),this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${y} ${t}`),this._startIntercepting()}nodeComplete(t,r={}){this._stopIntercepting(),this._currentNode=null;let{duration:i,details:o}=r;if(o)for(let n of o)this._rawWrite(`${a} ${n}`);let _=i?e.dim(` ${l(i)}`):"";this._rawWrite(`${c} ${e.green("done")}${_}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,r,i={}){this._stopIntercepting(),this._currentNode=null;let{duration:o}=i,_=o?e.dim(` ${l(o)}`):"";this._rawWrite(`${p} ${e.red(r)}`),this._rawWrite(`${c} ${e.red("failed")}${_}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeStopped(t,r={}){this._stopIntercepting(),this._currentNode=null;let{duration:i}=r,o=i?e.dim(` ${l(i)}`):"";this._rawWrite(`${c} ${e.dim("stopped")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,r){this._rawWrite(e.dim(` ${t} \u2192 ${r}`)),this._rawWrite("")}graphComplete(){}},E=new S;var R=E;export{S as Timeline,I as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,R as default,E as timeline};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "2.0.13",
3
+ "version": "2.0.15",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",