@zibby/agent-workflow 0.4.28 → 0.4.30

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.
@@ -1 +1 @@
1
- var M=()=>{},Y={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Y};var f={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as K,existsSync as v,statSync as F,readdirSync as q,rmSync as W}from"node:fs";import{spawn as z}from"node:child_process";import{join as T}from"node:path";import{pathToFileURL as Q}from"node:url";import{AsyncLocalStorage as Z}from"node:async_hooks";var U=new Z;function A(){let e=U.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})}function j(e,t){let n=U.getStore()||A(),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});return U.run(r,t)}var k=new Map,D=new Map,L=new Map;function G(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");k.set(e,t),D.set(e,"ready"),L.set(e,{...n,cachedAt:Date.now()})}function H(e,t){D.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),k.delete(e)}function J(e){return D.get(e)==="ready"?k.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ee(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var g=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 te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!n||!r||!a)throw new g("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:a}}async function re({apiBase:e,authToken:t,body:n}){let r;try{r=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(o){throw new g("network",`begin fetch failed: ${o.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let o=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(r.status===429){let o=a?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=o,i}if(r.status===400&&a?.validationErrors){let o=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=a.validationErrors,o.missing=a.missing,o}throw new g("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function x({apiBase:e,authToken:t,payload:n}){try{let r=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});r.ok||f.warn(`[in-process subgraph] finalize returned ${r.status} for ${n.childExecutionId}`)}catch(r){f.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ne(e,t){let n=T(t,".ready"),r=T(t,"graph.mjs");if(v(n)&&v(r))return;K(t,{recursive:!0});let a=T(t,".lock"),o=!1;try{let{openSync:i,closeSync:c}=await import("node:fs"),I=i(a,"wx");c(I),o=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!o){let i=Date.now()+3e4;for(;Date.now()<i;){if(v(n)&&v(r))return;await new Promise(c=>setTimeout(c,100))}throw new g("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((I,b)=>{let p=z("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),E=z("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(E.stdin);let d,l,m=()=>{if(d!==void 0&&l!==void 0){if(d!==0)return b(new Error(`curl exited ${d}`));if(l!==0)return b(new Error(`tar exited ${l}`));I()}};p.on("close",B=>{d=B,m()}),E.on("close",B=>{l=B,m()}),p.on("error",b),E.on("error",b)});let{writeFileSync:i,unlinkSync:c}=await import("node:fs");i(n,"");try{c(a)}catch{}}catch(i){try{let{unlinkSync:c}=await import("node:fs");c(a)}catch{}throw new g("bundle-extract-failed",i.message)}}async function oe(e){let t=T(e,"graph.mjs");if(!v(t))throw new g("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Q(t).href)}catch(a){throw new g("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=n.default||Object.values(n).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new g("entry-class-missing","no buildGraph() class export found");return r}async function N(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=A(),r;try{r=te()}catch(s){throw s}f.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let a=await re({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:o,runtimeTag:i,bundlePresignedUrl:c,sourcesPresignedUrl:I,workflowVersion:b,workflowUuid:p,bundleReady:E}=a,d=ee();if(i&&i!==d)throw await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${d} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new g("runtime-mismatch",`${d} vs ${i}`);if(!E||!c)throw await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new g("no-bundle","workflow bundle not built yet");let l=J(e);if(!l){let s=T(P,`${p}@${b||"0"}`);try{await ne(c,s);try{ae()}catch{}}catch(u){throw u.fallback&&await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{l=await oe(s),G(e,l,{workflowUuid:p,version:b,runtimeTag:i,cacheDir:s})}catch(u){throw H(e,u),await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new g("import-failed",u.message)}}let m=Date.now(),C=await(typeof l=="function"&&l.prototype?.buildGraph?new l:l).buildGraph(),w={...t.input||{}},y,S;try{y=await j({executionId:o,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>C.run(t.parentAgent,w,{signal:t.signal})),S=y&&typeof y=="object"&&"state"in y?y.state:y}catch(s){throw await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:s.message,code:s.code||"CHILD_THREW",stack:s.stack},durationMs:Date.now()-m}}),s}if(y&&typeof y=="object"&&y.stoppedExternally){await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",finalState:S,durationMs:Date.now()-m}});let s=new Error(`Sub-graph '${e}' canceled by parent abort`);throw s.code="SUBGRAPH_CANCELED",s.subgraphJobId=o,s}return await x({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"completed",finalState:S,durationMs:Date.now()-m}}),{finalState:S,executionId:o}}function se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),a;try{a=F(r)}catch{continue}if(a.isDirectory()){let o;try{o=q(r)}catch{continue}for(let i of o)n.push(T(r,i))}else t+=a.size}return t}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!v(P))return{evicted:0,freedBytes:0};let t=q(P),n=[],r=0;for(let c of t){let I=T(P,c),b;try{b=F(I)}catch{continue}let p=b.isDirectory()?se(I):b.size;r+=p,n.push({name:c,full:I,size:p,mtimeMs:b.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((c,I)=>c.mtimeMs-I.mtimeMs);let a=Math.floor(e*.7),o=0,i=0;for(let c of n){if(r-o<=a)break;if(!v(T(c.full,".lock")))try{W(c.full,{recursive:!0,force:!0}),o+=c.size,i+=1}catch(I){f.debug(`[sub-graph cache] evict skip ${c.name}: ${I.message}`)}}return i>0&&f.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:o,totalBytes:r-o}}catch(t){return f.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ie=2e3,ce=600*1e3,ue=new Set(["completed","failed","canceled","timeout"]);function de(){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 pe(){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 he(){return process.env.EXECUTION_ID||null}function X(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 ve(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=A(),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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{f.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:s}=await N(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),u=X(s,t.output);return f.info(`[sub-graph] '${e}' completed in-process`),u}catch(s){if(s instanceof g||s?.fallback)f.info(`[sub-graph] in-process fallback for '${e}': ${s.reason||"unknown"} \u2014 using HTTP`);else throw s}let a=de(),o=pe(),i=le(),c=he(),I=`${a}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(e)}/trigger`,b={input:t.input||{},...c?{parentExecutionId:c}:{},...t.conversationId?{conversationId:t.conversationId}:{}};f.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${c||"<none>"}`);let p=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(b)});if(!p.ok){let s=null,u="";try{s=await p.json(),u=s?.error||s?.message||JSON.stringify(s)}catch{u=await p.text().catch(()=>"")}if(p.status===429){let h=s?.quotaInfo||{},_=new Error(`Sub-graph '${e}' blocked by execution quota (${h.used??"?"}/${h.limit??"?"} on plan ${h.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw _.code="SUBGRAPH_QUOTA_EXCEEDED",_.status=429,_.subgraph=e,_.quotaInfo=h,_}if(p.status===400){let h=new Error(`Sub-graph '${e}' rejected input: ${u}`);throw h.code="SUBGRAPH_INVALID_INPUT",h.status=400,h.subgraph=e,h.validationErrors=s?.validationErrors||null,h.missing=s?.missing||null,h}let $=new Error(`Sub-graph '${e}' trigger rejected (${p.status}): ${u}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=p.status,$.subgraph=e,$}let E=await p.json(),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 f.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:e};let l=Number.isFinite(t.timeoutMs)?t.timeoutMs:ce,m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ie,B=`${a}/executions/${encodeURIComponent(d)}`,C=Date.now()+l,w="accepted",y=0;for(;Date.now()<C;){await new Promise(h=>setTimeout(h,m)),y+=1;let s=await fetch(B,{headers:{Authorization:`Bearer ${i}`}});if(!s.ok){if(s.status>=500){f.warn(`[sub-graph] status poll for ${d} returned ${s.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${s.status}`)}let u=await s.json(),$=u?.data||u?.execution||u;if(w=$?.status||w,ue.has(w)){if(w!=="completed"){let O=new Error(`Sub-graph '${e}' (${d}) ended in status '${w}'`);throw O.subgraphJobId=d,O.subgraphStatus=w,O}let h=$?.finalState||$?.state||{},_=X(h,t.output);return f.info(`[sub-graph] '${e}' (${d}) completed after ${y} polls`),_}}let S=new Error(`Sub-graph '${e}' (${d}) timed out after ${Math.round(l/1e3)}s (last status: ${w})`);throw S.subgraphJobId=d,S.subgraphStatus=w,S}export{ve as dispatchSubgraph};
1
+ var M=()=>{},Y={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Y};var f={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as K,existsSync as x,statSync as F,readdirSync as q,rmSync as W}from"node:fs";import{spawn as z}from"node:child_process";import{join as $}from"node:path";import{pathToFileURL as Q}from"node:url";import{AsyncLocalStorage as Z}from"node:async_hooks";var O=new Z;function A(){let e=O.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})}function j(e,t){let n=O.getStore()||A(),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});return O.run(r,t)}var U=new Map,k=new Map,L=new Map;function G(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");U.set(e,t),k.set(e,"ready"),L.set(e,{...n,cachedAt:Date.now()})}function H(e,t){k.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),U.delete(e)}function J(e){return k.get(e)==="ready"?U.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ee(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var g=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 te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!n||!r||!s)throw new g("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:s}}async function re({apiBase:e,authToken:t,body:n}){let r;try{r=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(o){throw new g("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){if(r.status===404){let o=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(r.status===429){let o=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(r.status===400&&s?.validationErrors){let o=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=s.validationErrors,o.missing=s.missing,o}throw new g("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function _({apiBase:e,authToken:t,payload:n}){try{let r=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});r.ok||f.warn(`[in-process subgraph] finalize returned ${r.status} for ${n.childExecutionId}`)}catch(r){f.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ne(e,t){let n=$(t,".ready"),r=$(t,"graph.mjs");if(x(n)&&x(r))return;K(t,{recursive:!0});let s=$(t,".lock"),o=!1;try{let{openSync:a,closeSync:u}=await import("node:fs"),b=a(s,"wx");u(b),o=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!o){let a=Date.now()+3e4;for(;Date.now()<a;){if(x(n)&&x(r))return;await new Promise(u=>setTimeout(u,100))}throw new g("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((b,I)=>{let l=z("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),m=z("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});l.stdout.pipe(m.stdin);let p,w,y=()=>{if(p!==void 0&&w!==void 0){if(p!==0)return I(new Error(`curl exited ${p}`));if(w!==0)return I(new Error(`tar exited ${w}`));b()}};l.on("close",S=>{p=S,y()}),m.on("close",S=>{w=S,y()}),l.on("error",I),m.on("error",I)});let{writeFileSync:a,unlinkSync:u}=await import("node:fs");a(n,"");try{u(s)}catch{}}catch(a){try{let{unlinkSync:u}=await import("node:fs");u(s)}catch{}throw new g("bundle-extract-failed",a.message)}}async function oe(e){let t=$(e,"graph.mjs");if(!x(t))throw new g("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Q(t).href)}catch(s){throw new g("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=n.default||Object.values(n).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new g("entry-class-missing","no buildGraph() class export found");return r}async function N(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=A(),r;try{r=te()}catch(d){throw d}f.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let s=await re({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:u,sourcesPresignedUrl:b,workflowVersion:I,workflowUuid:l,bundleReady:m,nodeConfigs:p}=s,w=ee();if(a&&a!==w)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${w} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new g("runtime-mismatch",`${w} vs ${a}`);if(!m||!u)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new g("no-bundle","workflow bundle not built yet");let y=J(e);if(!y){let d=$(P,`${l}@${I||"0"}`);try{await ne(u,d);try{ae()}catch{}}catch(c){throw c.fallback&&await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{y=await oe(d),G(e,y,{workflowUuid:l,version:I,runtimeTag:a,cacheDir:d})}catch(c){throw H(e,c),await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new g("import-failed",c.message)}}let S=Date.now(),E=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph(),B=p&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,v={...t.input||{},...B?{nodeConfigs:p}:{}},i,h;try{i=await j({executionId:o,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,v,{signal:t.signal})),h=i&&typeof i=="object"&&"state"in i?i.state:i}catch(d){throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-S}}),d}if(i&&typeof i=="object"&&i.stoppedExternally){await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",finalState:h,durationMs:Date.now()-S}});let d=new Error(`Sub-graph '${e}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=o,d}return await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"completed",finalState:h,durationMs:Date.now()-S}}),{finalState:h,executionId:o}}function se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),s;try{s=F(r)}catch{continue}if(s.isDirectory()){let o;try{o=q(r)}catch{continue}for(let a of o)n.push($(r,a))}else t+=s.size}return t}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!x(P))return{evicted:0,freedBytes:0};let t=q(P),n=[],r=0;for(let u of t){let b=$(P,u),I;try{I=F(b)}catch{continue}let l=I.isDirectory()?se(b):I.size;r+=l,n.push({name:u,full:b,size:l,mtimeMs:I.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((u,b)=>u.mtimeMs-b.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let u of n){if(r-o<=s)break;if(!x($(u.full,".lock")))try{W(u.full,{recursive:!0,force:!0}),o+=u.size,a+=1}catch(b){f.debug(`[sub-graph cache] evict skip ${u.name}: ${b.message}`)}}return a>0&&f.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:r-o}}catch(t){return f.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ie=2e3,ce=600*1e3,ue=new Set(["completed","failed","canceled","timeout"]);function de(){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 pe(){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 he(){return process.env.EXECUTION_ID||null}function X(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 ve(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=A(),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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{f.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:i}=await N(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),h=X(i,t.output);return f.info(`[sub-graph] '${e}' completed in-process`),h}catch(i){if(i instanceof g||i?.fallback)f.info(`[sub-graph] in-process fallback for '${e}': ${i.reason||"unknown"} \u2014 using HTTP`);else throw i}let s=de(),o=pe(),a=le(),u=he(),b=`${s}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(e)}/trigger`,I={input:t.input||{},...u?{parentExecutionId:u}:{},...t.conversationId?{conversationId:t.conversationId}:{}};f.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${u||"<none>"}`);let l=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(I)});if(!l.ok){let i=null,h="";try{i=await l.json(),h=i?.error||i?.message||JSON.stringify(i)}catch{h=await l.text().catch(()=>"")}if(l.status===429){let c=i?.quotaInfo||{},T=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 T.code="SUBGRAPH_QUOTA_EXCEEDED",T.status=429,T.subgraph=e,T.quotaInfo=c,T}if(l.status===400){let c=new Error(`Sub-graph '${e}' rejected input: ${h}`);throw c.code="SUBGRAPH_INVALID_INPUT",c.status=400,c.subgraph=e,c.validationErrors=i?.validationErrors||null,c.missing=i?.missing||null,c}let d=new Error(`Sub-graph '${e}' trigger rejected (${l.status}): ${h}`);throw d.code="SUBGRAPH_TRIGGER_FAILED",d.status=l.status,d.subgraph=e,d}let m=await l.json(),p=m?.data?.jobId||m?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(m).slice(0,200)}`);if(t.async)return f.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let w=Number.isFinite(t.timeoutMs)?t.timeoutMs:ce,y=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ie,S=`${s}/executions/${encodeURIComponent(p)}`,D=Date.now()+w,E="accepted",B=0;for(;Date.now()<D;){await new Promise(c=>setTimeout(c,y)),B+=1;let i=await fetch(S,{headers:{Authorization:`Bearer ${a}`}});if(!i.ok){if(i.status>=500){f.warn(`[sub-graph] status poll for ${p} returned ${i.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${i.status}`)}let h=await i.json(),d=h?.data||h?.execution||h;if(E=d?.status||E,ue.has(E)){if(E!=="completed"){let C=new Error(`Sub-graph '${e}' (${p}) ended in status '${E}'`);throw C.subgraphJobId=p,C.subgraphStatus=E,C}let c=d?.finalState||d?.state||{},T=X(c,t.output);return f.info(`[sub-graph] '${e}' (${p}) completed after ${B} polls`),T}}let v=new Error(`Sub-graph '${e}' (${p}) timed out after ${Math.round(w/1e3)}s (last status: ${E})`);throw v.subgraphJobId=p,v.subgraphStatus=E,v}export{ve as dispatchSubgraph};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "0.4.28",
3
+ "version": "0.4.30",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",