@zibby/agent-workflow 2.0.13 → 2.0.14
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 +14 -0
- package/dist/collaboration.js +2 -2
- package/dist/graph-compiler.js +12 -12
- package/dist/graph.js +10 -10
- package/dist/index.js +21 -21
- package/dist/sub-graph-executor.d.ts +7 -1
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
|
@@ -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};
|