@zibby/agent-workflow 2.0.4 → 2.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/failure-class.d.ts +193 -0
- package/dist/failure-class.js +1 -0
- package/dist/fetch-deadline.d.ts +78 -0
- package/dist/fetch-deadline.js +1 -0
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.js +20 -20
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +33 -33
- package/dist/node.js +18 -18
- package/dist/sub-graph-executor.d.ts +2 -0
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/node.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _t=Object.defineProperty;var R=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var wt=(r,t)=>{for(var e in t)_t(r,e,{get:t[e],enumerable:!0})};var z,St,M,x,f,P=R(()=>{z=()=>{},St={debug:z,info:z,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},M=Symbol.for("@zibby/agent-workflow.logger");globalThis[M]||(globalThis[M]={impl:St});x=globalThis[M],f={debug:(...r)=>x.impl.debug?.(...r),info:(...r)=>x.impl.info?.(...r),warn:(...r)=>x.impl.warn?.(...r),error:(...r)=>x.impl.error?.(...r)}});var st=R(()=>{});function at(r){return xt.get(r)||null}var G,U,xt,zt,ut=R(()=>{G=Symbol.for("@zibby/agent-workflow.skills"),U=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[G]||(globalThis[G]=new Map);globalThis[U]||(globalThis[U]=new Map);xt=globalThis[G],zt=globalThis[U]});var pt={};wt(pt,{getAgentStrategy:()=>dt,invokeAgent:()=>Wt,listStrategies:()=>Pt,registerStrategy:()=>Mt,resolveInvocationExtras:()=>lt,resolveInvocationModel:()=>ct});function Mt(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 Pt(){return $.map(r=>r.getName())}function ct({config:r={},options:t={},strategyName:e,envModel:n,nodeConfigModel:o}={}){let i=r.models||{},a=typeof o=="string"&&o.trim()?o.trim():null,m=t.nodeName&&i[t.nodeName]||null,l=i.default||null,S=r.agent?.[e]?.model||null,E=(typeof n=="string"?n.trim():"")||null;return a||m||l||S||t.model||E||null}function lt({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 dt(r={}){let{state:t={},preferredAgent:e=null}=r,n=e||t.agentType||process.env.AGENT_TYPE;if(!n){let i=$.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}f.debug(`[workflow] agent selection: requested=${n}`);let o=$.find(i=>i.getName()===n);if(!o){let i=$.map(a=>a.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 f.debug(`[workflow] using agent: ${o.getName()}`),o}async function Wt(r,t={},e={}){let n=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:n},i=dt(o),a=n.config||e.config||{},m=n._currentNodeConfig||{},l=typeof m.agent=="string"?m.agent.trim():"",S=!l||l===i.name?m.model:null,E=ct({config:a,options:e,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:S}),I={...e,model:E,...lt({options:e,stateView:n,context:t}),config:a},N=r,c=I.skills||[];if(c.length>0&&!e.skipPromptFragments){let w=e.connectedIntegrations;if(!w){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){w={};for(let u of p.split(",").map(b=>b.trim()).filter(Boolean))w[u]=!0}}let T=p=>{let u=p&&p.requiresIntegration;return!u||!w?!0:(Array.isArray(u)?u:[u]).some(O=>w[O]===!0)},s=i.name==="assistant",_=p=>p?.inProcessOnly!==!0||s,h=c.map(p=>{let u=at(p);if(!T(u)||!_(u))return null;let b=u?.promptFragment;return typeof b=="function"?b():b}).filter(Boolean);h.length>0&&(N+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${h.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let d=n._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let w=d.length<=8,T=d.map(s=>{let _=s?.id??s?.storeId??"",h=(s?.name??"").toString().trim()||_,p=s?.type?` \xB7 ${s.type}`:"",u=(s?.description||"").toString().replace(/\s+/g," ").trim(),b=`- ${h} \xB7 ${u||"(no description)"}${p} (id: ${_})`;if(w&&s?.schema&&typeof s.schema=="object"){let O=s.schema.properties&&typeof s.schema.properties=="object"?Object.keys(s.schema.properties):Object.keys(s.schema);O.length&&(b+=`
|
|
6
|
+
fields: ${O.join(", ")}`)}return b});N+=`
|
|
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 y=n._currentNodeConfig?.extraPromptInstructions?.trim();return y&&(N+=`
|
|
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
|
-
`),f.debug(`[workflow] prompt length: ${
|
|
16
|
+
${y}
|
|
17
|
+
`),f.debug(`[workflow] prompt length: ${N.length} chars`),i.invoke(N,I)}var H,$,ft=R(()=>{st();P();ut();H=Symbol.for("@zibby/agent-workflow.strategies");globalThis[H]||(globalThis[H]=[]);$=globalThis[H]});import k from"handlebars";var v=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}};P();import{writeFileSync as
|
|
20
|
-
`?(
|
|
21
|
-
${Z}`,t.col=
|
|
19
|
+
`)}`);return t}};P();import{writeFileSync as K,readFileSync as mt,existsSync as ht,mkdirSync as Ct}from"node:fs";import{join as J,dirname as Lt}from"node:path";import g from"chalk";var bt="__WORKFLOW_GRAPH_LOG__",A=g.gray("\u2502"),Et=g.gray("\u250C"),q=g.gray("\u2514"),W=g.green("\u25C6"),Y=g.hex("#c084fc")("\u25C6"),V=g.hex("#2dd4bf")("\u25C6"),C=g.red("\u25C6"),Z=`${A} `,X=2;function Q(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function tt(r,t){return(e,n,o)=>{if(typeof e!="string")return r(e,n,o);let i=process.stdout.columns||120,a="";for(let m=0;m<e.length;m++){let l=e[m];t.lineStart&&(a+=Z,t.col=X,t.lineStart=!1),l===`
|
|
20
|
+
`?(a+=l,t.lineStart=!0,t.col=0,t.inEsc=!1):l==="\x1B"?(t.inEsc=!0,a+=l):t.inEsc?(a+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(t.inEsc=!1)):(t.col++,a+=l,t.col>=i&&(a+=`
|
|
21
|
+
${Z}`,t.col=X))}return r(a,n,o)}}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},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=tt(this._origStdoutWrite,t),process.stderr.write=tt(this._origStderrWrite,e)}_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(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
24
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
24
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${bt}${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(
|
|
29
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(t){let e=
|
|
31
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(W,t):process.stdout.write.bind(process.stdout)(`${A} ${W} ${t}
|
|
29
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Y,t):process.stdout.write.bind(process.stdout)(`${A} ${Y} ${t}
|
|
30
|
+
`)}stepMemory(t){let e=g.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(V,e):process.stdout.write.bind(process.stdout)(`${A} ${V} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(C,g.red(t)):process.stdout.write.bind(process.stdout)(`${A} ${C} ${g.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Et} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:n,details:o}=e;if(o)for(let a of o)this._rawWrite(`${W} ${a}`);let i=n?g.dim(` ${Q(n)}`):"";this._rawWrite(`${q} ${g.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting();let{duration:o}=n,i=o?g.dim(` ${Q(o)}`):"";this._rawWrite(`${C} ${g.red(e)}`),this._rawWrite(`${q} ${g.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(g.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},et=new L;var F=".session-info.json";var Ut=Object.freeze(["codebase-memory","code-scan","artifact"]);var Nt=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"}),Tt=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]),$t=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),ot=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function j(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 kt(r){if(r&&typeof r=="object"){let e=r.providerErrorKind;if(typeof e=="string"&&e.trim())return e.trim()}let t=ot.exec(j(r));return t?t[1].toLowerCase():null}function It(r){if(r&&typeof r=="object"){let n=Number(r.providerErrorStatus);if(Number.isInteger(n)&&n>=100&&n<=599)return n}let t=ot.exec(j(r)),e=t&&t[2]?Number(t[2]):NaN;return Number.isInteger(e)?e:null}function At(r){let t=j(r);if(!t)return"deterministic";for(let o of $t)if(o.test(t))return"deterministic";let e=kt(r);if(e){let o=Nt[e];if(o==="transient"||o==="deterministic")return o}let n=It(r);if(n===429||n>=500&&n<=599)return"transient";for(let o of Tt)if(o.test(t))return"transient";return"deterministic"}var rt=2,Ot=5;function Rt(r=process.env){let t=r?.AGENT_TRANSIENT_RETRIES;if(t==null||String(t).trim()==="")return rt;let e=Number(t);return!Number.isFinite(e)||e<0?rt:Math.min(Ot,Math.floor(e))}var D=5e3,it=3e4;function vt(r=process.env){let t=r?.AGENT_TRANSIENT_BACKOFF_MS;if(t==null||String(t).trim()==="")return D;let e=Number(t);return!Number.isFinite(e)||e<0?D:Math.min(it,Math.floor(e))}function nt(r,t=Math.random,e=D){if(!(e>0))return 0;let n=Math.max(1,Math.floor(Number(r)||1)),o=Math.min(it,e*2**(n-1)),i=1+(t()-.5)*.4;return Math.max(1,Math.round(o*i))}function B(r,{env:t=process.env,rand:e=Math.random}={}){let n=Math.max(0,Math.floor(Number(r)||0)),o=Rt(t),i=vt(t),a=0,m=0;return{get attemptsMade(){return 1+a+m},get transientUsed(){return m},get transientMax(){return o},next(l){let S=At(l);return a<n?(a+=1,{retry:!0,paidBy:"declared",delayMs:S==="transient"?nt(a,e,i):0,failureClass:S,index:a,of:n}):S==="transient"&&m<o?(m+=1,{retry:!0,paidBy:"transient",delayMs:nt(m,e,i),failureClass:S,index:m,of:o}):{retry:!1,delayMs:0,failureClass:S}}}}async function gt(r,t,e,n){if(!t.retry)return!1;if(n())return f.info(`[workflow] node '${r}': run aborted \u2014 not retrying`),!1;let o=e?.message??String(e??"");return t.paidBy==="transient"?f.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).`):f.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())?(f.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 yt=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 v(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 f.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"){f.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let c=B(this.retries),d=null,y=null;for(;;){try{let s=await this.customExecute(t);if(typeof s=="object"&&s!==null&&s.success===!1)y=null,d={success:!1,error:s.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:s.raw||null};else return this.isZodSchema?(f.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){f.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&f.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),y=s,d={success:!1,error:s.message,raw:null}}let w=y??d?.error,T=c.next(w);if(!await gt(this.name,T,w,i))break}return d&&(d.attempts=c.attemptsMade),d}let a;typeof this.prompt=="function"?a=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=k.compile(this.prompt,{noEscape:!0})),a=this._compiledPrompt(n())):a=this.prompt;let m=o("_skillHints");m&&(a=`${m}
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${a}`);let l=n(),S=l.cwd||process.cwd(),E=l.sessionPath;try{if(E){let c=J(E,F);if(ht(c)){let y=JSON.parse(mt(c,"utf-8"));y.currentNode=this.name,K(c,JSON.stringify(y,null,2),"utf-8")}let d=J(E,"..",F);if(ht(d))try{let y=JSON.parse(mt(d,"utf-8"));y.currentNode=this.name,K(d,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(c){f.debug(`[workflow] could not update session info: ${c.message}`)}let I=B(this.retries),N=null;for(;;)try{f.debug(`[workflow] node '${this.name}' attempt ${I.attemptsMade-1}`);let c=n().config||{},d=c.agents||{},y=this.config.agent??d[this.name]??null,w={state:n()};y&&(w.preferredAgent=y);let T={workspace:S,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:E,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},s=t?._coreInvokeAgent;s||(s=(await Promise.resolve().then(()=>(ft(),pt))).invokeAgent);let _=await s(a,w,T),h,p;if(typeof _=="string"?(h=_,p=null):_.structured?(h=_.raw||JSON.stringify(_.structured,null,2),p=_.structured):(h=_.raw||JSON.stringify(_,null,2),p=_.extracted||null),E)try{let u=J(E,this.name,"raw_stream_output.txt");Ct(Lt(u),{recursive:!0}),K(u,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(u){f.debug(`[workflow] could not save raw output: ${u.message}`)}if(this.isZodSchema&&p){f.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(p,null,2)}`);let u=p;if(typeof this.onComplete=="function")try{u=await this.onComplete(n(),p)}catch(b){f.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:u,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:h}),raw:h}}catch(u){throw new Error(`onComplete failed: ${u.message}`,{cause:u})}if(this.parser){let u=this.parser.parse(h);return f.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(u,null,2)}`),et.step("Output parsed"),{success:!0,output:u,raw:h}}return{success:!0,output:h,raw:h}}catch(c){N=c;let d=I.next(c);if(!await gt(this.name,d,c,i))break}return{success:!1,error:N.message,raw:null,attempts:I.attemptsMade}}};export{yt as Node};
|
|
@@ -33,6 +33,8 @@
|
|
|
33
33
|
* error. In-process is never attempted without PROJECT_API_TOKEN — we
|
|
34
34
|
* keep the "no cloud creds = no sub-graphs" invariant from v1.
|
|
35
35
|
*/
|
|
36
|
+
import { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS } from './fetch-deadline.js';
|
|
37
|
+
export { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS };
|
|
36
38
|
/**
|
|
37
39
|
* Dispatch `workflowName` as a child of the currently-running execution.
|
|
38
40
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var L=()=>{},W={debug:L,info:L,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},M=Symbol.for("@zibby/agent-workflow.logger");globalThis[M]||(globalThis[M]={impl:W});var B=globalThis[M];var h={debug:(...e)=>B.impl.debug?.(...e),info:(...e)=>B.impl.info?.(...e),warn:(...e)=>B.impl.warn?.(...e),error:(...e)=>B.impl.error?.(...e)};import{mkdirSync as te,existsSync as A,statSync as Y,readdirSync as K,rmSync as ne}from"node:fs";import{spawn as q}from"node:child_process";import{join as T}from"node:path";import{pathToFileURL as re}from"node:url";import{AsyncLocalStorage as oe}from"node:async_hooks";import{AsyncLocalStorage as Q}from"node:async_hooks";var k=new Q;function x(){let e=k.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 G(e,t){let r=k.getStore()||x(),n=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:r.agent??null,signal:e.signal!==void 0?e.signal:r.signal??null});return k.run(n,t)}var D=new Map,j=new Map,H=new Map;function z(e,t,r={}){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");D.set(e,t),j.set(e,"ready"),H.set(e,{...r,cachedAt:Date.now()})}function F(e,t){j.set(e,"failed"),H.set(e,{error:t?.message||String(t),failedAt:Date.now()}),D.delete(e)}function J(e){return j.get(e)==="ready"?D.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function se(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var f=class extends Error{constructor(t,r){super(`in-process sub-graph fallback: ${t}${r?` (${r})`:""}`),this.fallback=!0,this.reason=t,this.detail=r||null,this.name="SubgraphFallback"}};function O(e,t,r,n="timeout",o=null){let s=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(r/1e3)}s (last status: ${n})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=t,s.subgraphStatus=n,o&&(s.subgraphTransportError=o),s}function ae(e,t=process.env,r=process.uptime()){let n=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(r)&&r>0?r*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(n===null&&a===null)return null;let c=n===null?a:a===null?n:Math.min(n,a);return Math.max(1,c)}function ie(e,t){let r=new AbortController,n=!1,o=null,s=()=>{r.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),t!=null&&!r.signal.aborted&&(o=setTimeout(()=>{n=!0,r.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:r.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var N=new oe,X=Promise.resolve();async function ce(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,c])=>typeof a=="string"&&a&&typeof c=="string"):[];if(r.length===0)return t();let n=N.getStore()===!0,o=null;if(!n){let a=X;X=new Promise(c=>{o=c}),await a}let s=new Map;try{for(let[a,c]of r)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=c;return h.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await N.run(!0,t)}finally{for(let[a,c]of s)c===void 0?delete process.env[a]:process.env[a]=c;o&&o()}}function ue(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!r||!n||!o)throw new f("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:o}}async function le({apiBase:e,authToken:t,body:r}){let n;try{n=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}catch(s){throw new f("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=o?.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(n.status===400&&o?.validationErrors){let s=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=o.validationErrors,s.missing=o.missing,s}throw new f("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function _({apiBase:e,authToken:t,payload:r}){try{let n=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});n.ok||h.warn(`[in-process subgraph] finalize returned ${n.status} for ${r.childExecutionId}`)}catch(n){h.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function de(e,t){let r=T(t,".ready"),n=T(t,"graph.mjs");if(A(r)&&A(n))return;te(t,{recursive:!0});let o=T(t,".lock"),s=!1;try{let{openSync:a,closeSync:c}=await import("node:fs"),g=a(o,"wx");c(g),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(A(r)&&A(n))return;await new Promise(c=>setTimeout(c,100))}throw new f("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((g,y)=>{let E=q("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),b=q("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});E.stdout.pipe(b.stdin);let w,p,m=()=>{if(w!==void 0&&p!==void 0){if(w!==0)return y(new Error(`curl exited ${w}`));if(p!==0)return y(new Error(`tar exited ${p}`));g()}};E.on("close",$=>{w=$,m()}),b.on("close",$=>{p=$,m()}),E.on("error",y),b.on("error",y)});let{writeFileSync:a,unlinkSync:c}=await import("node:fs");a(r,"");try{c(o)}catch{}}catch(a){try{let{unlinkSync:c}=await import("node:fs");c(o)}catch{}throw new f("bundle-extract-failed",a.message)}}async function pe(e){let t=T(e,"graph.mjs");if(!A(t))throw new f("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(re(t).href)}catch(o){throw new f("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=r.default||Object.values(r).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new f("entry-class-missing","no buildGraph() class export found");return n}async function V(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=x(),n;try{n=ue()}catch(i){throw i}h.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let o=await le({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:c,sourcesPresignedUrl:g,workflowVersion:y,workflowUuid:E,bundleReady:b,nodeConfigs:w}=o,p=se();if(a&&a!==p)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("runtime-mismatch",`${p} vs ${a}`);if(!b||!c)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("no-bundle","workflow bundle not built yet");let m=J(e);if(!m){let i=T(P,`${E}@${y||"0"}`);try{await de(c,i);try{ge()}catch{}}catch(u){throw u.fallback&&await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{m=await pe(i),z(e,m,{workflowUuid:E,version:y,runtimeTag:a,cacheDir:i})}catch(u){throw F(e,u),await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new f("import-failed",u.message)}}let $=Date.now(),C=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,v=w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0,R={...t.input||{},...v?{nodeConfigs:w}:{}},S=ae(t.timeoutMs),l=ie(t.signal,S),d,I;try{d=await ce(C,async()=>{let u=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return G({executionId:s,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(t.parentAgent,R,{signal:l.signal}))}),I=d&&typeof d=="object"&&"state"in d?d.state:d}catch(i){let u=l.timedOut();throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:u?"timeout":"failed",error:u?{message:`aborted at the declared ${Math.round(S/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:i.message,code:i.code||"CHILD_THREW",stack:i.stack},durationMs:Date.now()-$}}),u?O(e,s,S):i}finally{l.dispose()}if(d&&typeof d=="object"&&d.stoppedExternally){let i=l.timedOut();if(await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:i?"timeout":"canceled",finalState:I,durationMs:Date.now()-$}}),i)throw O(e,s,S);let u=new Error(`Sub-graph '${e}' canceled by parent abort`);throw u.code="SUBGRAPH_CANCELED",u.subgraphJobId=s,u}return await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:I,durationMs:Date.now()-$}}),{finalState:I,executionId:s}}function he(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),o;try{o=Y(n)}catch{continue}if(o.isDirectory()){let s;try{s=K(n)}catch{continue}for(let a of s)r.push(T(n,a))}else t+=o.size}return t}function ge({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!A(P))return{evicted:0,freedBytes:0};let t=K(P),r=[],n=0;for(let c of t){let g=T(P,c),y;try{y=Y(g)}catch{continue}let E=y.isDirectory()?he(g):y.size;n+=E,r.push({name:c,full:g,size:E,mtimeMs:y.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((c,g)=>c.mtimeMs-g.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let c of r){if(n-s<=o)break;if(!A(T(c.full,".lock")))try{ne(c.full,{recursive:!0,force:!0}),s+=c.size,a+=1}catch(g){h.debug(`[sub-graph cache] evict skip ${c.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:n-s}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var fe=2e3,ye=600*1e3,be=new Set(["completed","failed","canceled","timeout"]);function we(){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 Ie(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function me(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function Ee(){return process.env.EXECUTION_ID||null}function Z(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((r,n)=>r==null?r:r[n],e):e}async function ke(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let r=x();t.parentAgent==null&&r.agent&&(t.parentAgent=r.agent),t.signal==null&&r.signal&&(t.signal=r.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((r.depth||0)>=n)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${r.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:ye;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:l}=await V(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),d=Z(l,t.output);return h.info(`[sub-graph] '${e}' completed in-process`),d}catch(l){if(l instanceof f||l?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${l.reason||"unknown"} \u2014 using HTTP`);else throw l}let s=we(),a=Ie(),c=me(),g=Ee(),y=`${s}/projects/${encodeURIComponent(a)}/workflows/${encodeURIComponent(e)}/trigger`,E={input:t.input||{},...g?{parentExecutionId:g}:{},...t.conversationId?{conversationId:t.conversationId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${g||"<none>"}`);let b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify(E)});if(!b.ok){let l=null,d="";try{l=await b.json(),d=l?.error||l?.message||JSON.stringify(l)}catch{d=await b.text().catch(()=>"")}if(b.status===429){let i=l?.quotaInfo||{},u=new Error(`Sub-graph '${e}' blocked by execution quota (${i.used??"?"}/${i.limit??"?"} on plan ${i.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw u.code="SUBGRAPH_QUOTA_EXCEEDED",u.status=429,u.subgraph=e,u.quotaInfo=i,u}if(b.status===400){let i=new Error(`Sub-graph '${e}' rejected input: ${d}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.subgraph=e,i.validationErrors=l?.validationErrors||null,i.missing=l?.missing||null,i}let I=new Error(`Sub-graph '${e}' trigger rejected (${b.status}): ${d}`);throw I.code="SUBGRAPH_TRIGGER_FAILED",I.status=b.status,I.subgraph=e,I}let w=await b.json(),p=w?.data?.jobId||w?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(w).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 m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:fe,$=`${s}/executions/${encodeURIComponent(p)}`,C=Date.now()+o,v="accepted",R=0,S=null;for(;Date.now()<C;){await new Promise(i=>setTimeout(i,m)),R+=1;let l;try{l=await fetch($,{headers:{Authorization:`Bearer ${c}`}})}catch(i){S=i?.message||String(i),h.warn(`[sub-graph] status poll for ${p} could not reach the API (${S}), will retry`);continue}if(!l.ok){if(l.status>=500){h.warn(`[sub-graph] status poll for ${p} returned ${l.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${l.status}`)}let d;try{d=await l.json()}catch(i){S=i?.message||String(i),h.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${S}), will retry`);continue}let I=d?.data||d?.execution||d;if(v=I?.status||v,be.has(v)){if(v!=="completed"){let U=new Error(`Sub-graph '${e}' (${p}) ended in status '${v}'`);throw U.subgraphJobId=p,U.subgraphStatus=v,U}let i=I?.finalState||I?.state||{},u=Z(i,t.output);return h.info(`[sub-graph] '${e}' (${p}) completed after ${R} polls`),u}}throw O(e,p,o,v,S)}export{ke as dispatchSubgraph};
|
|
1
|
+
var J=()=>{},ae={debug:J,info:J,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k=Symbol.for("@zibby/agent-workflow.logger");globalThis[k]||(globalThis[k]={impl:ae});var G=globalThis[k];var g={debug:(...e)=>G.impl.debug?.(...e),info:(...e)=>G.impl.info?.(...e),warn:(...e)=>G.impl.warn?.(...e),error:(...e)=>G.impl.error?.(...e)};import{mkdirSync as de,existsSync as U,statSync as te,readdirSync as ne,rmSync as pe}from"node:fs";import{spawn as W}from"node:child_process";import{join as O}from"node:path";import{pathToFileURL as he}from"node:url";import{AsyncLocalStorage as ge}from"node:async_hooks";import{AsyncLocalStorage as ie}from"node:async_hooks";var j=new ie;function x(){let e=j.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 q(e,t){let n=j.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 j.run(r,t)}var F=new Map,z=new Map,X=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");F.set(e,t),z.set(e,"ready"),X.set(e,{...n,cachedAt:Date.now()})}function K(e,t){z.set(e,"failed"),X.set(e,{error:t?.message||String(t),failedAt:Date.now()}),F.delete(e)}function V(e){return z.get(e)==="ready"?F.get(e):null}var P=3e4,Z=15e3;function B(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 N(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function C(e,t){return N(B(e,t),e)}function _(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}var D=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function fe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var b=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 L(e,t,n,r="timeout",o=null){let a=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 a.code="SUBGRAPH_TIMEOUT",a.subgraphJobId=t,a.subgraphStatus=r,o&&(a.subgraphTransportError=o),a}function ye(e,t=process.env,n=process.uptime()){let r=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),a=Number.isFinite(n)&&n>0?n*1e3:0,s=Number.isFinite(o)&&o>0?o-a:null;if(r===null&&s===null)return null;let i=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,i)}function be(e,t){let n=new AbortController,r=!1,o=null,a=()=>{n.abort(e?.reason)};return e&&(e.aborted?a():e.addEventListener("abort",a,{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",a)}}}var Q=new ge,ee=Promise.resolve();async function Ie(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(n.length===0)return t();let r=Q.getStore()===!0,o=null;if(!r){let s=ee;ee=new Promise(i=>{o=i}),await s}let a=new Map;try{for(let[s,i]of n)a.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return g.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await Q.run(!0,t)}finally{for(let[s,i]of a)i===void 0?delete process.env[s]:process.env[s]=i;o&&o()}}function Ee(){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 b("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:o}}async function me({apiBase:e,authToken:t,body:n}){let r=C("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(s){throw new b(_(s)?"begin-timeout":"network",_(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let a=null;try{a=await o.json()}catch(s){if(_(s))throw new b("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=a?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=s,i}if(o.status===400&&a?.validationErrors){let s=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=a.validationErrors,s.missing=a.missing,s}throw new b("begin-status",`begin returned ${o.status}`)}return a?.data||a}async function M({apiBase:e,authToken:t,payload:n}){let r=C("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||g.warn(`[in-process subgraph] finalize returned ${o.status} for ${n.childExecutionId}`)}catch(o){g.warn(`[in-process subgraph] finalize ${_(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Te(e,t){let n=O(t,".ready"),r=O(t,"graph.mjs");if(U(n)&&U(r))return;de(t,{recursive:!0});let o=O(t,".lock"),a=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),y=s(o,"wx");i(y),a=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!a){let s=Date.now()+3e4;for(;Date.now()<s;){if(U(n)&&U(r))return;await new Promise(i=>setTimeout(i,100))}throw new b("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,I)=>{let S=Math.ceil(1e4/1e3),R=Math.ceil(B("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),h=W("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(R),e],{stdio:["ignore","pipe","inherit"]}),E=W("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(E.stdin);let d,m,v=()=>{if(d!==void 0&&m!==void 0){if(d!==0)return I(new Error(`curl exited ${d}`));if(m!==0)return I(new Error(`tar exited ${m}`));y()}};h.on("close",$=>{d=$,v()}),E.on("close",$=>{m=$,v()}),h.on("error",I),E.on("error",I)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(n,"");try{i(o)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new b("bundle-extract-failed",s.message)}}async function _e(e){let t=O(e,"graph.mjs");if(!U(t))throw new b("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(he(t).href)}catch(o){throw new b("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 b("entry-class-missing","no buildGraph() class export found");return r}async function re(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=x(),r;try{r=Ee()}catch(p){throw p}g.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await me({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:a,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:y,workflowVersion:I,workflowUuid:S,bundleReady:R,nodeConfigs:h}=o,E=fe();if(s&&s!==E)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("runtime-mismatch",`${E} vs ${s}`);if(!R||!i)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("no-bundle","workflow bundle not built yet");let d=V(e);if(!d){let p=O(D,`${S}@${I||"0"}`);try{await Te(i,p);try{we()}catch{}}catch(c){throw c.fallback&&await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{d=await _e(p),Y(e,d,{workflowUuid:S,version:I,runtimeTag:s,cacheDir:p})}catch(c){throw K(e,c),await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new b("import-failed",c.message)}}let m=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=h&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,w={...t.input||{},...$?{nodeConfigs:h}:{}},A=ye(t.timeoutMs),T=be(t.signal,A),u,l;try{u=await Ie(v,async()=>{let c=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return q({executionId:a,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,w,{signal:T.signal}))}),l=u&&typeof u=="object"&&"state"in u?u.state:u}catch(p){let c=T.timedOut();throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(A/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),c?L(e,a,A):p}finally{T.dispose()}if(u&&typeof u=="object"&&u.stoppedExternally){let p=T.timedOut();if(await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:p?"timeout":"canceled",finalState:l,durationMs:Date.now()-m}}),p)throw L(e,a,A);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=a,c}return await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"completed",finalState:l,durationMs:Date.now()-m}}),{finalState:l,executionId:a}}function Se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),o;try{o=te(r)}catch{continue}if(o.isDirectory()){let a;try{a=ne(r)}catch{continue}for(let s of a)n.push(O(r,s))}else t+=o.size}return t}function we({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!U(D))return{evicted:0,freedBytes:0};let t=ne(D),n=[],r=0;for(let i of t){let y=O(D,i),I;try{I=te(y)}catch{continue}let S=I.isDirectory()?Se(y):I.size;r+=S,n.push({name:i,full:y,size:S,mtimeMs:I.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,y)=>i.mtimeMs-y.mtimeMs);let o=Math.floor(e*.7),a=0,s=0;for(let i of n){if(r-a<=o)break;if(!U(O(i.full,".lock")))try{pe(i.full,{recursive:!0,force:!0}),a+=i.size,s+=1}catch(y){g.debug(`[sub-graph cache] evict skip ${i.name}: ${y.message}`)}}return s>0&&g.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(a/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:a,totalBytes:r-a}}catch(t){return g.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var $e=2e3,Oe=600*1e3,Re=new Set(["completed","failed","canceled","timeout"]);var Ae=()=>C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Me(e){let t=B("SUBGRAPH_POLL_TIMEOUT_MS",15e3),n=Math.max(1,Math.min(t,e-Date.now()));return N(n,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ue(){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 ve(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function xe(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function Pe(){return process.env.EXECUTION_ID||null}function oe(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 Ze(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:Oe;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{g.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await re(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),l=oe(u,t.output);return g.info(`[sub-graph] '${e}' completed in-process`),l}catch(u){if(u instanceof b||u?.fallback)g.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let a=Ue(),s=ve(),i=xe(),y=Pe(),I=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(e)}/trigger`,S={input:t.input||{},...y?{parentExecutionId:y}:{},...t.conversationId?{conversationId:t.conversationId}:{}};g.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${y||"<none>"}`);let R=Ae(),h;try{h=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(S),signal:R.signal})}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger TIMED OUT ${R.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}if(!h.ok){let u=null,l="";try{u=await h.json(),l=u?.error||u?.message||JSON.stringify(u)}catch{l=await h.text().catch(()=>"")}if(h.status===429){let c=u?.quotaInfo||{},f=new Error(`Sub-graph '${e}' blocked by execution quota (${c.used??"?"}/${c.limit??"?"} on plan ${c.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw f.code="SUBGRAPH_QUOTA_EXCEEDED",f.status=429,f.subgraph=e,f.quotaInfo=c,f}if(h.status===400){let c=new Error(`Sub-graph '${e}' rejected input: ${l}`);throw c.code="SUBGRAPH_INVALID_INPUT",c.status=400,c.subgraph=e,c.validationErrors=u?.validationErrors||null,c.missing=u?.missing||null,c}let p=new Error(`Sub-graph '${e}' trigger rejected (${h.status}): ${l}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=h.status,p.subgraph=e,p}let E;try{E=await h.json()}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger body read TIMED OUT ${R.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}let d=E?.data?.jobId||E?.jobId;if(!d)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(E).slice(0,200)}`);if(t.async)return g.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:e};let m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:$e,v=`${a}/executions/${encodeURIComponent(d)}`,$=Date.now()+o,w="accepted",A=0,T=null;for(;Date.now()<$;){await new Promise(f=>setTimeout(f,m)),A+=1;let u=Me($),l;try{l=await fetch(v,{headers:{Authorization:`Bearer ${i}`},signal:u.signal})}catch(f){T=_(f)?`poll TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} could not reach the API (${T}), will retry`);continue}if(!l.ok){if(l.status>=500){g.warn(`[sub-graph] status poll for ${d} returned ${l.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${l.status}`)}let p;try{p=await l.json()}catch(f){T=_(f)?`poll body read TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} returned an unreadable body (${T}), will retry`);continue}let c=p?.data||p?.execution||p;if(w=c?.status||w,Re.has(w)){if(w!=="completed"){let H=new Error(`Sub-graph '${e}' (${d}) ended in status '${w}'`);throw H.subgraphJobId=d,H.subgraphStatus=w,H}let f=c?.finalState||c?.state||{},se=oe(f,t.output);return g.info(`[sub-graph] '${e}' (${d}) completed after ${A} polls`),se}}throw L(e,d,o,w,T)}export{Z as SUBGRAPH_POLL_TIMEOUT_MS,P as SUBGRAPH_TRIGGER_TIMEOUT_MS,Ze as dispatchSubgraph};
|