@zibby/agent-workflow 2.0.11 → 2.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration.d.ts +8 -0
- package/dist/collaboration.js +2 -0
- package/dist/fetch-deadline.d.ts +9 -0
- package/dist/fetch-deadline.js +1 -1
- package/dist/graph-compiler.js +23 -22
- package/dist/graph.js +22 -21
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +31 -30
- package/dist/sub-graph-executor.d.ts +15 -0
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,42 +1,43 @@
|
|
|
1
|
-
var
|
|
1
|
+
var pr=Object.defineProperty;var Se=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var st=(r,e)=>{for(var t in e)pr(r,t,{get:e[t],enumerable:!0})};var it,hr,ke,be,A,ce=Se(()=>{it=()=>{},hr={debug:it,info:it,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ke=Symbol.for("@zibby/agent-workflow.logger");globalThis[ke]||(globalThis[ke]={impl:hr});be=globalThis[ke],A={debug:(...r)=>be.impl.debug?.(...r),info:(...r)=>be.impl.info?.(...r),warn:(...r)=>be.impl.warn?.(...r),error:(...r)=>be.impl.error?.(...r)}});var bt=Se(()=>{});var Et={};st(Et,{clearSkills:()=>Pr,getAllSkills:()=>Mr,getSkill:()=>Fe,getSkillSource:()=>Or,hasSkill:()=>$r,listSkillIds:()=>Rr,registerSkill:()=>vr});function vr(r,e={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,o=r.id;if(V.has(o)&&!n){let i=ue.get(o);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}V.set(o,Object.freeze({...r})),t===void 0?ue.delete(o):ue.set(o,t)}function Fe(r){return V.get(r)||null}function $r(r){return V.has(r)}function Or(r){return ue.get(r)||null}function Mr(){return new Map(V)}function Rr(){return Array.from(V.keys())}function Pr(){V.clear(),ue.clear()}var je,Le,V,ue,Ge=Se(()=>{je=Symbol.for("@zibby/agent-workflow.skills"),Le=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[je]||(globalThis[je]=new Map);globalThis[Le]||(globalThis[Le]=new Map);V=globalThis[je],ue=globalThis[Le]});var ze={};st(ze,{EFFORT_LEVELS:()=>He,getAgentStrategy:()=>vt,invokeAgent:()=>Nr,listStrategies:()=>xr,registerStrategy:()=>kr,resolveInvocationEffort:()=>Tt,resolveInvocationExtras:()=>At,resolveInvocationModel:()=>It});function kr(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=X.findIndex(t=>t.getName()===r.getName());e>=0?X[e]=r:X.push(r)}function xr(){return X.map(r=>r.getName())}function It({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:o}={}){let i=r.models||{},s=typeof o=="string"&&o.trim()?o.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=r.agent?.[t]?.model||null,I=(typeof n=="string"?n.trim():"")||null;return s||a||l||u||e.model||I||null}function Tt({options:r={},envEffort:e,nodeConfigEffort:t}={}){let n=[t,r.effort,e].map(o=>typeof o=="string"?o.trim().toLowerCase():"").find(Boolean);return n?He.indexOf(n)===-1?(A.warn(`[workflow] ignoring unknown effort "${n}" \u2014 expected one of ${He.join(", ")}`),null):n:null}function At({options:r={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||r.workspace,schema:r.schema||t.schema,images:r.images||t.images||[],skills:r.skills||t.skills||[],extraMcpServers:r.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:r.plugins||t.plugins||[]}}function vt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=X.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}A.debug(`[workflow] agent selection: requested=${n}`);let o=X.find(i=>i.getName()===n);if(!o){let i=X.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!o.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return A.debug(`[workflow] using agent: ${o.getName()}`),o}async function Nr(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},o={...e,state:n},i=vt(o),s=n.config||t.config||{},a=n._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,I=It({config:s,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d=!l||l===i.name?a.effort:null,c=Tt({options:t,envEffort:process.env.EFFORT,nodeConfigEffort:d}),h={...t,model:I,...c?{effort:c}:{},...At({options:t,stateView:n,context:e}),config:s},p=r,w=h.skills||[];if(w.length>0&&!t.skipPromptFragments){let m=t.connectedIntegrations;if(!m){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){m={};for(let y of f.split(",").map(M=>M.trim()).filter(Boolean))m[y]=!0}}let b=f=>{let y=f&&f.requiresIntegration;return!y||!m?!0:(Array.isArray(y)?y:[y]).some(R=>m[R]===!0)},_=i.name==="assistant",v=f=>f?.inProcessOnly!==!0||_,g=w.map(f=>{let y=Fe(f);if(!b(y)||!v(y))return null;let M=y?.promptFragment;return typeof M=="function"?M():M}).filter(Boolean);g.length>0&&(p+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${g.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let $=n._currentNodeConfig?.stores;if(Array.isArray($)&&$.length>0&&typeof $[0]=="object"){let m=$.length<=8,b=$.map(_=>{let v=_?.id??_?.storeId??"",g=(_?.name??"").toString().trim()||v,f=_?.type?` \xB7 ${_.type}`:"",y=(_?.description||"").toString().replace(/\s+/g," ").trim(),M=`- ${g} \xB7 ${y||"(no description)"}${f} (id: ${v})`;if(m&&_?.schema&&typeof _.schema=="object"){let R=_.schema.properties&&typeof _.schema.properties=="object"?Object.keys(_.schema.properties):Object.keys(_.schema);R.length&&(M+=`
|
|
6
|
+
fields: ${R.join(", ")}`)}return M});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${b.join(`
|
|
10
|
+
`)}`}let P=n._currentNodeConfig?.extraPromptInstructions?.trim();return P&&(p+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),
|
|
16
|
+
${P}
|
|
17
|
+
`),A.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,h)}var We,X,He,Je=Se(()=>{bt();ce();Ge();We=Symbol.for("@zibby/agent-workflow.strategies");globalThis[We]||(globalThis[We]=[]);X=globalThis[We];He=["low","medium","high","xhigh","max"]});var fr=new Set(["__proto__","constructor","prototype"]);function Pe(r){if(fr.has(r))throw new Error(`Invalid state key: "${r}"`)}var _e=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Pe(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Pe(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Pe(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import Q from"handlebars";var we=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.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:e.trim()})}validate(e){let t=[];for(let[n,o]of Object.entries(this.schema)){if(o.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&o.type){let i=typeof e[n];i!==o.type&&t.push(`Field '${n}' expected ${o.type}, got ${i}`)}if(o.validate&&n in e){let i=o.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};
|
|
19
|
+
`)}`);return e}};ce();import{writeFileSync as qe,readFileSync as $t,existsSync as Ot,mkdirSync as Br}from"node:fs";import{join as Ye,dirname as Cr}from"node:path";import N from"chalk";var gr="__WORKFLOW_GRAPH_LOG__",le=N.gray("\u2502"),mr=N.gray("\u250C"),at=N.gray("\u2514"),xe=N.green("\u25C6"),ct=N.hex("#c084fc")("\u25C6"),lt=N.hex("#2dd4bf")("\u25C6"),Ne=N.red("\u25C6"),ut=`${le} `,dt=2;function pt(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function ft(r,e){return(t,n,o)=>{if(typeof t!="string")return r(t,n,o);let i=process.stdout.columns||120,s="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(s+=ut,e.col=dt,e.lineStart=!1),l===`
|
|
20
20
|
`?(s+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,s+=l):e.inEsc?(s+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,s+=l,e.col>=i&&(s+=`
|
|
21
|
-
${
|
|
21
|
+
${ut}`,e.col=dt))}return r(s,n,o)}}var Be=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=ft(this._origStdoutWrite,e),process.stderr.write=ft(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${
|
|
24
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${gr}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(xe,e):process.stdout.write.bind(process.stdout)(`${le} ${xe} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${le} ${ct} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${le} ${lt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ne,N.red(e)):process.stdout.write.bind(process.stdout)(`${le} ${Ne} ${N.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${mr} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:o}=t;if(o)for(let s of o)this._rawWrite(`${xe} ${s}`);let i=n?N.dim(` ${pt(n)}`):"";this._rawWrite(`${at} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:o}=n,i=o?N.dim(` ${pt(o)}`):"";this._rawWrite(`${Ne} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},D=new Be;var Ee=".zibby/output",ht="sessions",oe=".session-info.json",gt=".zibby-stop";var Pn=Object.freeze(["codebase-memory","code-scan","artifact"]),mt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var yr=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"}),Sr=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]),_r=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),_t=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Ue(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r!="object")return String(r);let e=r;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(n=>typeof n=="string"||typeof n=="number").join(" | ")}function wr(r){if(r&&typeof r=="object"){let t=r.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=_t.exec(Ue(r));return e?e[1].toLowerCase():null}function br(r){if(r&&typeof r=="object"){let n=Number(r.providerErrorStatus);if(Number.isInteger(n)&&n>=100&&n<=599)return n}let e=_t.exec(Ue(r)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function Er(r){let e=Ue(r);if(!e)return"deterministic";for(let o of _r)if(o.test(e))return"deterministic";let t=wr(r);if(t){let o=yr[t];if(o==="transient"||o==="deterministic")return o}let n=br(r);if(n===429||n>=500&&n<=599)return"transient";for(let o of Sr)if(o.test(e))return"transient";return"deterministic"}var yt=2,Ir=5;function Tr(r=process.env){let e=r?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return yt;let t=Number(e);return!Number.isFinite(t)||t<0?yt:Math.min(Ir,Math.floor(t))}var Ce=5e3,wt=3e4;function Ar(r=process.env){let e=r?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Ce;let t=Number(e);return!Number.isFinite(t)||t<0?Ce:Math.min(wt,Math.floor(t))}function St(r,e=Math.random,t=Ce){if(!(t>0))return 0;let n=Math.max(1,Math.floor(Number(r)||1)),o=Math.min(wt,t*2**(n-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(o*i))}function De(r,{env:e=process.env,rand:t=Math.random}={}){let n=Math.max(0,Math.floor(Number(r)||0)),o=Tr(e),i=Ar(e),s=0,a=0;return{get attemptsMade(){return 1+s+a},get transientUsed(){return a},get transientMax(){return o},next(l){let u=Er(l);return s<n?(s+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?St(s,t,i):0,failureClass:u,index:s,of:n}):u==="transient"&&a<o?(a+=1,{retry:!0,paidBy:"transient",delayMs:St(a,t,i),failureClass:u,index:a,of:o}):{retry:!1,delayMs:0,failureClass:u}}}}async function Mt(r,e,t,n){if(!e.retry)return!1;if(n())return A.info(`[workflow] node '${r}': run aborted \u2014 not retrying`),!1;let o=t?.message??String(t??"");return e.paidBy==="transient"?A.warn(`[workflow] node '${r}': TRANSIENT provider failure \u2014 ${o}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):A.info(`[workflow] node '${r}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),n())?(A.info(`[workflow] node '${r}': run aborted during backoff \u2014 not retrying`),!1):!0}Q.helpers.inc||Q.registerHelper("inc",r=>Number(r)+1);Q.helpers.json||Q.registerHelper("json",r=>JSON.stringify(r,null,2));Q.helpers.eq||Q.registerHelper("eq",(r,e)=>r===e);var z=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new we(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return A.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,o=h=>t&&typeof t.get=="function"?t.get(h):e?.[h],i=()=>o("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){A.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let h=De(this.retries),p=null,w=null;for(;;){try{let m=await this.customExecute(e);if(typeof m=="object"&&m!==null&&m.success===!1)w=null,p={success:!1,error:m.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:m.raw||null};else return this.isZodSchema?(A.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(m),raw:null}):{success:!0,output:m,raw:null}}catch(m){A.error(`[workflow] node '${this.name}' failed: ${m.message}`),m.name==="ZodError"&&A.error(`Schema errors: ${JSON.stringify(m.issues||m.errors,null,2)}`),w=m,p={success:!1,error:m.message,raw:null}}let $=w??p?.error,P=h.next($);if(!await Mt(this.name,P,$,i))break}return p&&(p.attempts=h.attemptsMade),p}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=Q.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let a=o("_skillHints");a&&(s=`${a}
|
|
33
33
|
|
|
34
|
-
${s}`);let l=r(),d=l.cwd||process.cwd(),E=l.sessionPath;try{if(E){let _=je(E,X);if(Et(_)){let A=JSON.parse(bt(_,"utf-8"));A.currentNode=this.name,De(_,JSON.stringify(A,null,2),"utf-8")}let p=je(E,"..",X);if(Et(p))try{let A=JSON.parse(bt(p,"utf-8"));A.currentNode=this.name,De(p,JSON.stringify(A,null,2),"utf-8")}catch{}}}catch(_){I.debug(`[workflow] could not update session info: ${_.message}`)}let u=xe(this.retries),c=null;for(;;)try{I.debug(`[workflow] node '${this.name}' attempt ${u.attemptsMade-1}`);let _=r().config||{},p=_.agents||{},A=this.config.agent??p[this.name]??null,v={state:r()};A&&(v.preferredAgent=A);let O={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:E,config:_,nodeName:this.name,timeout:this.config?.timeout||3e5},h=e?._coreInvokeAgent;h||(h=(await Promise.resolve().then(()=>(Ue(),Ce))).invokeAgent);let T=await h(s,v,O),w,y;if(typeof T=="string"?(w=T,y=null):T.structured?(w=T.raw||JSON.stringify(T.structured,null,2),y=T.structured):(w=T.raw||JSON.stringify(T,null,2),y=T.extracted||null),E)try{let m=je(E,this.name,"raw_stream_output.txt");Tn(An(m),{recursive:!0}),De(m,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(m){I.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&y){I.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let m=y;if(typeof this.onComplete=="function")try{m=await this.onComplete(r(),y)}catch(f){I.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:m,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(w);return I.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),P.step("Output parsed"),{success:!0,output:m,raw:w}}return{success:!0,output:w,raw:w}}catch(_){c=_;let p=u.next(_);if(!await It(this.name,p,_,i))break}return{success:!1,error:c.message,raw:null,attempts:u.attemptsMade}}};ne();ne();import{mkdirSync as kn,existsSync as q,statSync as Pt,readdirSync as Nt,rmSync as Rn}from"node:fs";import{spawn as kt}from"node:child_process";import{join as H}from"node:path";import{pathToFileURL as Mn}from"node:url";import{AsyncLocalStorage as Pn}from"node:async_hooks";import{AsyncLocalStorage as $n}from"node:async_hooks";var se=new $n;function Q(){let n=se.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Tt(n,e){let t=se.getStore()||Q(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return se.run(r,e)}function At(n,e,t){let r=se.getStore()||Q(),o=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return se.run(o,t)}var Le=new Map,Fe=new Map,$t=new Map;function vt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(n,e),Fe.set(n,"ready"),$t.set(n,{...t,cachedAt:Date.now()})}function Ot(n,e){Fe.set(n,"failed"),$t.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(n)}function xt(n){return Fe.get(n)==="ready"?Le.get(n):null}function ie(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function Ge(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ae(n,e){return Ge(ie(n,e),n)}function j(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var ge=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Nn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var M=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function me(n,e,t,r="timeout",o=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,o&&(i.subgraphTransportError=o),i}function Bn(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(r===null&&s===null)return null;let a=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,a)}function Cn(n,e){let t=new AbortController,r=!1,o=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),n&&n.removeEventListener("abort",i)}}}var Rt=new Pn,Mt=Promise.resolve();async function Un(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let r=Rt.getStore()===!0,o=null;if(!r){let s=Mt;Mt=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Dn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!r||!o)throw new M("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:o}}async function jn({apiBase:n,authToken:e,body:t}){let r=ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(s){throw new M(j(s)?"begin-timeout":"network",j(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(j(s))throw new M("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new M("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function Z({apiBase:n,authToken:e,payload:t}){let r=ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});o.ok||I.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){I.warn(`[in-process subgraph] finalize ${j(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Ln(n,e){let t=H(e,".ready"),r=H(e,"graph.mjs");if(q(t)&&q(r))return;kn(e,{recursive:!0});let o=H(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(q(t)&&q(r))return;await new Promise(a=>setTimeout(a,100))}throw new M("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let E=Math.ceil(1e4/1e3),u=Math.ceil(ie("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=kt("curl",["-fsSL","--connect-timeout",String(E),"--max-time",String(u),n],{stdio:["ignore","pipe","inherit"]}),_=kt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(_.stdin);let p,A,v=()=>{if(p!==void 0&&A!==void 0){if(p!==0)return d(new Error(`curl exited ${p}`));if(A!==0)return d(new Error(`tar exited ${A}`));l()}};c.on("close",O=>{p=O,v()}),_.on("close",O=>{A=O,v()}),c.on("error",d),_.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new M("bundle-extract-failed",s.message)}}async function Fn(n){let e=H(n,"graph.mjs");if(!q(e))throw new M("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Mn(e).href)}catch(o){throw new M("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new M("entry-class-missing","no buildGraph() class export found");return r}async function Bt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),r;try{r=Dn()}catch(f){throw f}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let o=await jn({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:E,bundleReady:u,nodeConfigs:c}=o,_=Nn();if(s&&s!==_)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("runtime-mismatch",`${_} vs ${s}`);if(!u||!a)throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new M("no-bundle","workflow bundle not built yet");let p=xt(n);if(!p){let f=H(ge,`${E}@${d||"0"}`);try{await Ln(a,f);try{Hn()}catch{}}catch(g){throw g.fallback&&await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason}}}),g}try{p=await Fn(f),vt(n,p,{workflowUuid:E,version:d,runtimeTag:s,cacheDir:f})}catch(g){throw Ot(n,g),await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:g.message,code:g.reason||"IMPORT_FAILED"}}}),g.fallback?g:new M("import-failed",g.message)}}let A=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,O=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...O?{nodeConfigs:c}:{}},T=Bn(e.timeoutMs),w=Cn(e.signal,T),y,m;try{y=await Un(v,async()=>{let g=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Tt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>g.run(e.parentAgent,h,{signal:w.signal}))}),m=y&&typeof y=="object"&&"state"in y?y.state:y}catch(f){let g=w.timedOut();throw await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:g?"timeout":"failed",error:g?{message:`aborted at the declared ${Math.round(T/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-A}}),g?me(n,i,T):f}finally{w.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let f=w.timedOut();if(await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:m,durationMs:Date.now()-A}}),f)throw me(n,i,T);let g=new Error(`Sub-graph '${n}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=i,g}return await Z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-A}}),{finalState:m,executionId:i}}function Gn(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),o;try{o=Pt(r)}catch{continue}if(o.isDirectory()){let i;try{i=Nt(r)}catch{continue}for(let s of i)t.push(H(r,s))}else e+=o.size}return e}function Hn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!q(ge))return{evicted:0,freedBytes:0};let e=Nt(ge),t=[],r=0;for(let a of e){let l=H(ge,a),d;try{d=Pt(l)}catch{continue}let E=d.isDirectory()?Gn(l):d.size;r+=E,t.push({name:a,full:l,size:E,mtimeMs:d.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(n*.7),i=0,s=0;for(let a of t){if(r-i<=o)break;if(!q(H(a.full,".lock")))try{Rn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:r-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Jn=2e3,zn=600*1e3,Yn=new Set(["completed","failed","canceled","timeout"]);var Zn=()=>ae("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function qn(n){let e=ie("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Ge(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Kn(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Vn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Xn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Qn(){return process.env.EXECUTION_ID||null}function Ct(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function Ut(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:zn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:y}=await Bt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),m=Ct(y,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),m}catch(y){if(y instanceof M||y?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Kn(),s=Vn(),a=Xn(),l=Qn(),d=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(n)}/trigger`,E={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let u=Zn(),c;try{c=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(E),signal:u.signal})}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger TIMED OUT ${u.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}if(!c.ok){let y=null,m="";try{y=await c.json(),m=y?.error||y?.message||JSON.stringify(y)}catch{m=await c.text().catch(()=>"")}if(c.status===429){let g=y?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${g.used??"?"}/${g.limit??"?"} on plan ${g.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw $.code="SUBGRAPH_QUOTA_EXCEEDED",$.status=429,$.subgraph=n,$.quotaInfo=g,$}if(c.status===400){let g=new Error(`Sub-graph '${n}' rejected input: ${m}`);throw g.code="SUBGRAPH_INVALID_INPUT",g.status=400,g.subgraph=n,g.validationErrors=y?.validationErrors||null,g.missing=y?.missing||null,g}let f=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${m}`);throw f.code="SUBGRAPH_TRIGGER_FAILED",f.status=c.status,f.subgraph=n,f}let _;try{_=await c.json()}catch(y){if(!j(y))throw y;let m=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${u.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw m.code="SUBGRAPH_TRIGGER_TIMEOUT",m.subgraph=n,m.timedOut=!0,m.cause=y,m}let p=_?.data?.jobId||_?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(_).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let A=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Jn,v=`${i}/executions/${encodeURIComponent(p)}`,O=Date.now()+o,h="accepted",T=0,w=null;for(;Date.now()<O;){await new Promise($=>setTimeout($,A)),T+=1;let y=qn(O),m;try{m=await fetch(v,{headers:{Authorization:`Bearer ${a}`},signal:y.signal})}catch($){w=j($)?`poll TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} could not reach the API (${w}), will retry`);continue}if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let f;try{f=await m.json()}catch($){w=j($)?`poll body read TIMED OUT ${y.label}`:$?.message||String($),I.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${w}), will retry`);continue}let g=f?.data||f?.execution||f;if(h=g?.status||h,Yn.has(h)){if(h!=="completed"){let W=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw W.subgraphJobId=p,W.subgraphStatus=h,W}let $=g?.finalState||g?.state||{},N=Ct($,e.output);return I.info(`[sub-graph] '${n}' (${p}) completed after ${T} polls`),N}}throw me(n,p,o,h,w)}import{existsSync as Dt,readFileSync as er}from"node:fs";import{join as He,dirname as jt}from"node:path";var Se=class{static async loadContext(e,t,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=jt(He(t,e));for(let l of i){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let E=l.replace(/\.[^.]+$/,"").toLowerCase();o[E]=d}}}let s=r.discovery||{};for(let[a,l]of Object.entries(s))try{let d=He(t,l);Dt(d)&&(o[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return o}static async findAndMergeContextFiles(e,t,r){let o=[],i=t;for(;i.startsWith(r);){let s=He(i,e);if(Dt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=jt(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
34
|
+
${s}`);let l=n(),u=l.cwd||process.cwd(),I=l.sessionPath;try{if(I){let h=Ye(I,oe);if(Ot(h)){let w=JSON.parse($t(h,"utf-8"));w.currentNode=this.name,qe(h,JSON.stringify(w,null,2),"utf-8")}let p=Ye(I,"..",oe);if(Ot(p))try{let w=JSON.parse($t(p,"utf-8"));w.currentNode=this.name,qe(p,JSON.stringify(w,null,2),"utf-8")}catch{}}}catch(h){A.debug(`[workflow] could not update session info: ${h.message}`)}let d=De(this.retries),c=null;for(;;)try{A.debug(`[workflow] node '${this.name}' attempt ${d.attemptsMade-1}`);let h=n().config||{},p=h.agents||{},w=this.config.agent??p[this.name]??null,$={state:n()};w&&($.preferredAgent=w);let P={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:I,config:h,nodeName:this.name,timeout:this.config?.timeout||3e5},m=e?._coreInvokeAgent;m||(m=(await Promise.resolve().then(()=>(Je(),ze))).invokeAgent);let b=await m(s,$,P),_,v;if(typeof b=="string"?(_=b,v=null):b.structured?(_=b.raw||JSON.stringify(b.structured,null,2),v=b.structured):(_=b.raw||JSON.stringify(b,null,2),v=b.extracted||null),I)try{let g=Ye(I,this.name,"raw_stream_output.txt");Br(Cr(g),{recursive:!0}),qe(g,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(g){A.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&v){A.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let g=v;if(typeof this.onComplete=="function")try{g=await this.onComplete(n(),v)}catch(f){A.warn(`[workflow] onComplete hook failed: ${f.message}`)}return{success:!0,output:g,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:_}),raw:_}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(_);return A.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),D.step("Output parsed"),{success:!0,output:g,raw:_}}return{success:!0,output:_,raw:_}}catch(h){c=h;let p=d.next(h);if(!await Mt(this.name,p,h,i))break}return{success:!1,error:c.message,raw:null,attempts:d.attemptsMade}}};ce();ce();import{mkdirSync as Fr,existsSync as te,statSync as jt,readdirSync as Lt,rmSync as Gr}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as K}from"node:path";import{pathToFileURL as Wr}from"node:url";import{AsyncLocalStorage as Hr}from"node:async_hooks";import{AsyncLocalStorage as Ur}from"node:async_hooks";var de=new Ur;function se(){let r=de.getStore();return r||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 Rt(r,e){let t=de.getStore()||se(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return de.run(n,e)}function Pt(r,e,t){let n=de.getStore()||se(),o=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return de.run(o,t)}var Ze=new Map,Ke=new Map,kt=new Map;function xt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Ze.set(r,e),Ke.set(r,"ready"),kt.set(r,{...t,cachedAt:Date.now()})}function Nt(r,e){Ke.set(r,"failed"),kt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Ze.delete(r)}function Bt(r){return Ke.get(r)==="ready"?Ze.get(r):null}function pe(r,e,t=process.env){let n=Number(t[r]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):e}function Ie(r,e){return{signal:AbortSignal.timeout(r),label:`after ${r}ms (${e})`}}function fe(r,e){return Ie(pe(r,e),r)}function H(r){return r?.name==="TimeoutError"||r?.name==="AbortError"}function Z(r,e){return e.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(e.reason)):new Promise((t,n)=>{let o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),Promise.resolve(r).then(i=>{e.removeEventListener("abort",o),t(i)},i=>{e.removeEventListener("abort",o),n(i)})})}var Te=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function zr(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var B=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function Ae(r,e,t,n="timeout",o=null){let i=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=n,o&&(i.subgraphTransportError=o),i}function Jr(r,e=process.env,t=process.uptime()){let n=Number.isFinite(r)?Number(r):null,o=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,s=Number.isFinite(o)&&o>0?o-i:null;if(n===null&&s===null)return null;let a=n===null?s:s===null?n:Math.min(n,s);return Math.max(1,a)}function qr(r,e){let t=new AbortController,n=!1,o=null,i=()=>{t.abort(r?.reason)};return r&&(r.aborted?i():r.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(o=setTimeout(()=>{n=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof o.unref=="function"&&o.unref()),{signal:t.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),r&&r.removeEventListener("abort",i)}}}var Ut=new Hr,Dt=Promise.resolve();async function Yr(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let n=Ut.getStore()===!0,o=null;if(!n){let s=Dt;Dt=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return A.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function Zr(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!t||!n||!o)throw new B("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:o}}async function Kr({apiBase:r,authToken:e,body:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.signal})}catch(s){throw new B(H(s)?"begin-timeout":"network",H(s)?`begin TIMED OUT ${n.label}`:`begin fetch failed: ${s.message}`)}let i=null;try{i=await o.json()}catch(s){if(H(s))throw new B("begin-timeout",`begin body read TIMED OUT ${n.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(o.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new B("begin-status",`begin returned ${o.status}`)}return i?.data||i}async function ee({apiBase:r,authToken:e,payload:t}){let n=fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:n.signal});o.ok||A.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){A.warn(`[in-process subgraph] finalize ${H(o)?`TIMED OUT ${n.label}`:`failed: ${o.message}`}`)}}async function Vr(r,e){let t=K(e,".ready"),n=K(e,"graph.mjs");if(te(t)&&te(n))return;Fr(e,{recursive:!0});let o=K(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),l=s(o,"wx");a(l),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(te(t)&&te(n))return;await new Promise(a=>setTimeout(a,100))}throw new B("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let I=Math.ceil(1e4/1e3),d=Math.ceil(pe("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Ct("curl",["-fsSL","--connect-timeout",String(I),"--max-time",String(d),r],{stdio:["ignore","pipe","inherit"]}),h=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(h.stdin);let p,w,$=()=>{if(p!==void 0&&w!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(w!==0)return u(new Error(`tar exited ${w}`));l()}};c.on("close",P=>{p=P,$()}),h.on("close",P=>{w=P,$()}),c.on("error",u),h.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new B("bundle-extract-failed",s.message)}}async function Xr(r){let e=K(r,"graph.mjs");if(!te(e))throw new B("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(Wr(e).href)}catch(o){throw new B("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=t.default||Object.values(t).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new B("entry-class-missing","no buildGraph() class export found");return n}async function Ft(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=se(),n;try{n=Zr()}catch(f){throw f}A.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let o=await Kr({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:I,bundleReady:d,nodeConfigs:c}=o,h=zr();if(s&&s!==h)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new B("runtime-mismatch",`${h} vs ${s}`);if(!d||!a)throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new B("no-bundle","workflow bundle not built yet");let p=Bt(r);if(!p){let f=K(Te,`${I}@${u||"0"}`);try{await Vr(a,f);try{en()}catch{}}catch(y){throw y.fallback&&await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{p=await Xr(f),xt(r,p,{workflowUuid:I,version:u,runtimeTag:s,cacheDir:f})}catch(y){throw Nt(r,y),await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new B("import-failed",y.message)}}let w=Date.now(),$=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,P=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},...P?{nodeConfigs:c}:{}},b=Jr(e.timeoutMs),_=qr(e.signal,b),v,g;try{v=await Yr($,async()=>{let y=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>y.run(e.parentAgent,m,{signal:_.signal}))}),g=v&&typeof v=="object"&&"state"in v?v.state:v}catch(f){let y=_.timedOut();throw await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:y?"timeout":"failed",error:y?{message:`aborted at the declared ${Math.round(b/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:f.message,code:f.code||"CHILD_THREW",stack:f.stack},durationMs:Date.now()-w}}),y?Ae(r,i,b):f}finally{_.dispose()}if(v&&typeof v=="object"&&v.stoppedExternally){let f=_.timedOut();if(await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:f?"timeout":"canceled",finalState:g,durationMs:Date.now()-w}}),f)throw Ae(r,i,b);let y=new Error(`Sub-graph '${r}' canceled by parent abort`);throw y.code="SUBGRAPH_CANCELED",y.subgraphJobId=i,y}return await ee({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-w}}),{finalState:g,executionId:i}}function Qr(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),o;try{o=jt(n)}catch{continue}if(o.isDirectory()){let i;try{i=Lt(n)}catch{continue}for(let s of i)t.push(K(n,s))}else e+=o.size}return e}function en({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!te(Te))return{evicted:0,freedBytes:0};let e=Lt(Te),t=[],n=0;for(let a of e){let l=K(Te,a),u;try{u=jt(l)}catch{continue}let I=u.isDirectory()?Qr(l):u.size;n+=I,t.push({name:a,full:l,size:I,mtimeMs:u.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let o=Math.floor(r*.7),i=0,s=0;for(let a of t){if(n-i<=o)break;if(!te(K(a.full,".lock")))try{Gr(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(l){A.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return s>0&&A.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:n-i}}catch(e){return A.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var rn=2e3,nn=600*1e3,on=new Set(["completed","failed","canceled","cancelled","timeout"]);var Wt=()=>fe("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function sn(r){let e=pe("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,r-Date.now()));return Ie(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ht(){let r=process.env.PROGRESS_API_URL;if(!r)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 r.replace(/\/executions\/?$/,"")}function zt(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function Jt(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function qt(){return process.env.EXECUTION_ID||null}function Gt(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}async function Ve(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=se();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(e.timeoutMs)?e.timeoutMs:nn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async&&!e.participantBindingId)try{A.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g}=await Ft(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:o}),f=Gt(g,e.output);return A.info(`[sub-graph] '${r}' completed in-process`),f}catch(g){if(g instanceof B||g?.fallback)A.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let i=Ht(),s=zt(),a=Jt(),l=qt(),u=e.participantBindingId?"participant":r,I=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(u)}/trigger`,d={input:e.input||{},...l?{parentExecutionId:l}:{},...!e.async&&typeof e.output=="string"&&e.output.trim()?{resultPath:e.output.trim()}:{},...e.conversationId?{conversationId:e.conversationId}:{},...typeof e.idempotencyKey=="string"&&e.idempotencyKey?{idempotencyKey:e.idempotencyKey.slice(0,200)}:{},...e.participantBindingId?{participantBindingId:e.participantBindingId}:{},...e.protocolId?{protocolId:e.protocolId}:{}};A.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let c=Wt(),h;try{h=await Z(fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(d),signal:c.signal}),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' trigger TIMED OUT ${c.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}if(!h.ok){let g=null,f="";try{g=await Z(h.json(),c.signal),f=g?.error||g?.message||JSON.stringify(g)}catch{f=await Z(h.text(),c.signal).catch(()=>"")}if(h.status===429){let M=g?.quotaInfo||{},R=new Error(`Sub-graph '${r}' 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 R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=r,R.quotaInfo=M,R}if(h.status===400){let M=new Error(`Sub-graph '${r}' rejected input: ${f}`);throw M.code="SUBGRAPH_INVALID_INPUT",M.status=400,M.subgraph=r,M.validationErrors=g?.validationErrors||null,M.missing=g?.missing||null,M}let y=new Error(`Sub-graph '${r}' trigger rejected (${h.status}): ${f}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=h.status,y.subgraph=r,y}let p;try{p=await Z(h.json(),c.signal)}catch(g){if(!H(g))throw g;let f=new Error(`Sub-graph '${r}' trigger body read TIMED OUT ${c.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw f.code="SUBGRAPH_TRIGGER_TIMEOUT",f.subgraph=r,f.timedOut=!0,f.cause=g,f}let w=p?.data?.jobId||p?.jobId;if(!w)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(p).slice(0,200)}`);if(e.async)return A.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${w} (not waiting)`),{jobId:w,status:"accepted",workflow:r};let $=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:rn,P=`${i}/executions/${encodeURIComponent(w)}`,m=Date.now()+o,b="accepted",_=0,v=null;for(;Date.now()<m;){await new Promise(R=>setTimeout(R,$)),_+=1;let g=sn(m),f;try{f=await Z(fetch(P,{headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal)}catch(R){v=H(R)?`poll TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${w} could not reach the API (${v}), will retry`);continue}if(!f.ok){if(f.status>=500){A.warn(`[sub-graph] status poll for ${w} returned ${f.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${w}: ${f.status}`)}let y;try{y=await Z(f.json(),g.signal)}catch(R){v=H(R)?`poll body read TIMED OUT ${g.label}`:R?.message||String(R),A.warn(`[sub-graph] status poll for ${w} returned an unreadable body (${v}), will retry`);continue}let M=y?.data||y?.execution||y;if(b=M?.status||b,on.has(b)){if(b!=="completed"){let E=new Error(`Sub-graph '${r}' (${w}) ended in status '${b}'`);throw E.subgraphJobId=w,E.subgraphStatus=b,E}let R=M?.finalState||M?.state||{},O=Gt(R,e.output);return A.info(`[sub-graph] '${r}' (${w}) completed after ${_} polls`),O}}try{let g=Ie(500,"SUBGRAPH_CANCEL_TIMEOUT_MS"),f=await Z(fetch(`${P}/cancel`,{method:"POST",headers:{Authorization:`Bearer ${a}`},signal:g.signal}),g.signal);!f.ok&&f.status!==400&&f.status!==404&&A.warn(`[sub-graph] best-effort cancel for ${w} returned ${f.status}`)}catch(g){A.warn(`[sub-graph] best-effort cancel for ${w} failed: ${g?.message||String(g)}`)}throw Ae(r,w,o,b,v)}async function Yt(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchParticipant: bindingId (string) is required");if(!e.protocolId||typeof e.protocolId!="string")throw new Error("dispatchParticipant: protocolId (string) is required");return Ve("participant",{...e,async:e.async!==!1,participantBindingId:r})}async function Zt(r){if(!r||typeof r!="string")throw new Error("listParticipants: protocolId (string) is required");let e=Ht(),t=zt(),n=Jt(),o=qt();if(!o){let u=new Error("Collaboration requires a running parent execution");throw u.code="PARENT_EXECUTION_REQUIRED",u}let i=`${e}/projects/${encodeURIComponent(t)}/workflows/participant/trigger`,s=Wt(),a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({participantOperation:"list",parentExecutionId:o,protocolId:r}),signal:s.signal})}catch(u){let I=new Error(`Participant roster lookup failed: ${u?.message||String(u)}`);throw I.code=H(u)?"PARTICIPANT_ROSTER_TIMEOUT":"PARTICIPANT_ROSTER_UNAVAILABLE",I.cause=u,I}let l=null;try{l=await a.json()}catch{}if(!a.ok){let u=new Error(l?.error||`Participant roster lookup rejected (${a.status})`);throw u.code=l?.code||"PARTICIPANT_ROSTER_REJECTED",u.status=a.status,u}return Array.isArray(l?.participants)?l.participants:[]}var an=8*6e4,cn=10*6e4,ln=2*6e4;function un(r=process.env,e=process.uptime()){let t=Number(r?.MAX_WORKFLOW_DURATION_MS);return!Number.isFinite(t)||t<=0?null:Math.max(0,t-Math.ceil(Number(e||0)*1e3))}function Kt(r,e,t=Number.MAX_SAFE_INTEGER){let n=Number(r);return Number.isFinite(n)&&n>0?Math.min(Math.floor(n),t):e}function he(r,e,t={}){return{requested:!0,required:r===!0,observed:!1,status:r===!0?"incomplete":"skipped",reason:e,contributions:[],disagreements:[],...t}}function dn(r,e,t){return{participant:r.displayName||r.id,participantId:r.id,vendor:r.vendor||null,phase:e,revision:0,contribution:t}}function Vt(r,e,t){return r.find(n=>Array.isArray(n.roles)&&n.roles.includes(e))||t}var pn=["claims","assumptions","risks","objections","decisions","evidenceGaps","recommendations","artifactRefs"];function fn(r,e,t){let n=r;if(typeof n=="string")try{n=JSON.parse(n)}catch{n=null}if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.phase===e&&n.role===t&&n.contextRevision===0&&typeof n.summary=="string"&&pn.every(i=>Array.isArray(n[i])))){let i=new Error(`Participant returned invalid ${e} protocol output`);throw i.code="PARTICIPANT_OUTPUT_INVALID",i}return n}async function Xt(r={},e={}){let t=String(r.protocolId||"discuss.v1"),n=String(r.objective||"").trim(),o=String(r.context||""),i=r.required===!0,s=Kt(r.timeoutMs,an,cn),a=Kt(r.reserveMs,ln,15*6e4),l=(e.remainingWorkflowTimeMs||un)();if(!n)return he(i,"objective_missing",{protocolId:t});if(l!=null&&l<s+a)return he(i,"insufficient_execution_time",{protocolId:t,remainingMs:l,requiredMs:s+a});let u=e.listParticipants||Zt,I=e.dispatchParticipant||Yt,d;try{d=await u(t)}catch(E){return he(i,E?.code||"participant_roster_unavailable",{protocolId:t,detail:E?.message||String(E)})}let c=d.filter(E=>E?.available===!1),h=d.filter(E=>E&&E.available!==!1&&E.id);if(h.length===0)return he(i,"no_available_participants",{protocolId:t,unavailable:c});let p=Date.now(),w=p+s,$=[],P=[],m=async(E,C,F,ge=[])=>{let ie=w-Date.now();if(ie<1e3){let Y=new Error("Collaboration node exhausted its authored timeout");throw Y.code="COLLABORATION_TIMEOUT",Y}let T=Number(E?.limits?.maxExecutionMinutes)*6e4,S=Number.isFinite(T)&&T>0?Math.min(ie,T):ie,U,j=null;for(let Y=0;Y<2;Y+=1){let ae=Y===1?"Your previous attempt did not satisfy the JSON protocol. Return exactly one valid JSON object with every required array field and no Markdown, preface, trailing commas, or comments.":"",Me=await I(E.id,{async:!1,protocolId:t,timeoutMs:Math.min(S,Math.max(1e3,w-Date.now())),output:"contribute",input:{objective:n,protocolId:t,phase:C,role:F,contextRevision:0,sharedContext:o,priorContributions:ge,...r.instruction||ae?{instruction:[r.instruction,ae].filter(Boolean).join(`
|
|
35
|
+
`).slice(0,4e3)}:{}}});try{U=fn(Me,C,F),j=null;break}catch(me){j=me}}if(j)throw j;let q=dn(E,C,U);return $.push(q),q},b=Vt(h,"draft",h[0]),_;try{_=await m(b,"draft","drafter")}catch(E){P.push({participantId:b.id,phase:"draft",code:E?.code||"PARTICIPANT_FAILED",detail:E?.message||String(E)});let C=he(i,"draft_failed",{protocolId:t,unavailable:c,failures:P,durationMs:Date.now()-p});return i&&(C.status="incomplete"),C}let v=h.filter(E=>E.id!==b.id);v.length===0&&(v=[b]);let g=await Promise.allSettled(v.map(E=>m(E,"critique","critic",[_]))),f=[];g.forEach((E,C)=>{E.status==="fulfilled"?f.push(E.value):P.push({participantId:v[C].id,phase:"critique",code:E.reason?.code||"PARTICIPANT_FAILED",detail:E.reason?.message||String(E.reason)})});let y=Vt(h,"synthesize",b),M=null;try{M=await m(y,"synthesize","synthesizer",[_,...f])}catch(E){P.push({participantId:y.id,phase:"synthesize",code:E?.code||"PARTICIPANT_FAILED",detail:E?.message||String(E)})}let R=f.length>0&&M!=null,O=(M?.contribution?.decisions||[]).filter(E=>E?.status==="unresolved");return{requested:!0,required:i,observed:R,status:R?"completed":"incomplete",reason:R?null:"required_phase_incomplete",protocolId:t,contributions:$,synthesis:M?.contribution||null,disagreements:O,failures:P,unavailable:c,durationMs:Date.now()-p}}import{existsSync as Qt,readFileSync as hn}from"node:fs";import{join as Xe,dirname as er}from"node:path";var $e=class{static async loadContext(e,t,n={}){let o={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=er(Xe(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let I=l.replace(/\.[^.]+$/,"").toLowerCase();o[I]=u}}}let s=n.discovery||{};for(let[a,l]of Object.entries(s))try{let u=Xe(t,l);Qt(u)&&(o[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return o}static async findAndMergeContextFiles(e,t,n){let o=[],i=t;for(;i.startsWith(n);){let s=Xe(i,e);if(Qt(s))try{o.unshift(await this.loadFile(s))}catch(l){console.warn(`[workflow] could not load ${e} from ${s}: ${l.message}`)}let a=er(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
35
36
|
|
|
36
37
|
---
|
|
37
38
|
|
|
38
|
-
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=
|
|
39
|
+
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(e){let t=hn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),o=await import(n(e).href);return o.default||o}return t}};import{mkdirSync as or,existsSync as Qe,writeFileSync as tr,unlinkSync as gn}from"node:fs";import{join as re,resolve as sr}from"node:path";import{config as mn}from"dotenv";import{zodToJsonSchema as rr}from"zod-to-json-schema";import{z as Oe}from"zod";import yn from"handlebars";function Sn({traceFrom:r,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${s} sessionId=${e} source=${n} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let I=(new Error("session trace").stack||"").split(`
|
|
39
40
|
`).slice(2,14).join(`
|
|
40
|
-
`);console.log(`[zibby:session] stack (${
|
|
41
|
-
${E}`)}}function sr(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function ir(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Wt(String(e).trim())}catch{return String(e).trim()}}function ar(){sr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function cr({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function lr(n={}){let e=ut.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,o=n.paths?.sessionPrefix;return o?`${o}_${r}`:r}function ur({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let d=Wt(String(process.env.ZIBBY_SESSION_PATH));d&&(o=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,s="config.sessionId"):(a=lr(e),s="generated")}i=i??Date.now();let E=e.paths?.output||he;o=K(n,E,ct,a)}let l=!We(o);return l&&Ht(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&or({traceFrom:r,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),cr({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var Gt=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof G)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let E=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof s.input=="function"?u=s.input(E):s.input&&typeof s.input=="object"?u=s.input:u={},Ut(s.workflow,{input:u,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(E):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:E?._signal,parentAgent:d?.agent})}},l=new G(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let o=!(t instanceof G)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof G?t:new G(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,r=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&r(s)}t.set(i,2)};this.entryPoint&&r(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,o,i){let s=r;for(let a=e.length-1;a>=0;a--){let l=e[a],d=s;s=()=>l(t,d,o,i)}return s()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let _=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:_,data:{nodeType:_,label:u}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let A=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;A&&(p.description=A);let v=this.nodePrompts.get(u);if(v)p.prompt=v;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(p.prompt=f,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let O=c?.config?.dispatchesWorkflow;if(typeof O=="string"&&O.trim())p.dispatchesWorkflow=O.trim();else if(Array.isArray(O)){let f=[...new Set(O.filter(g=>typeof g=="string").map(g=>g.trim()).filter(Boolean))];f.length&&(p.dispatchesWorkflow=f)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof _e?.toJSONSchema=="function")try{f=_e.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=Ft(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[u];h?.toolIds&&(p.tools=h.toolIds);let T=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;T&&T.length>0&&(p.skills=[...T]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(p.plugins=w.map(f=>f&&typeof f=="object"?{...f}:f));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(p.stores=y.map(f=>f&&typeof f=="object"?{...f}:f));let m=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(m&&m.length>0){let f=new Set,g=[];for(let $ of m){let N=typeof $=="string"?$.trim():"";!N||f.has(N)||(f.add(N),g.push(N))}g.length>0&&(p.uses=g)}Object.keys(p).length>0&&(t[u]=p)}let r=[];for(let[u,c]of this.edges)if(typeof c=="string")r.push({source:u,target:c});else if(Array.isArray(c))for(let _ of c)r.push({source:u,target:_});else if(c.conditional){let _=this.conditionalCodeMap.get(u)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),A=c.labels||{},v=this.nodes.get(u),O=v?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!v,h=u;if(!O){let T=`${u}__branch`;e.push({id:T,type:"decision",data:{nodeType:"decision",label:T}}),r.push({source:u,target:T}),h=T}for(let T of p){let w={source:h,target:T,data:{conditionalCode:_}};A[T]&&(w.label=A[T]),r.push(w)}}let o=u=>{if(!u)return null;if(typeof _e?.toJSONSchema=="function")try{return _e.toJSONSchema(u)}catch{}try{return Ft(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let u of r)if(u.target==="END"){i+=1;let c=`END__${i}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:u,target:c})}let s=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=o(a||this.stateSchema),d=o(this.inputSchema),E=o(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:E}}_topoOrderNodes(e,t){let r=new Map(e.map((u,c)=>[u.id,c])),o=new Map(e.map(u=>[u.id,u])),i=new Map(e.map(u=>[u.id,0])),s=new Map(e.map(u=>[u.id,[]]));for(let u of t)s.has(u.source)&&i.has(u.target)&&(s.get(u.source).push(u.target),i.set(u.target,i.get(u.target)+1));let a=new Set,l=new Set(r.keys()),d=[...l].filter(u=>i.get(u)===0),E=[];for(;E.length<e.length;){let u;if(d.length>0){if(d.sort((c,_)=>r.get(c)-r.get(_)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,_)=>r.get(c)-r.get(_))[0];a.add(u),l.delete(u),E.push(o.get(u));for(let c of s.get(u)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return E}_inferConditionalTargets(e,t){let r=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(r))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&o.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of o)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,E;for(;(E=d.exec(r))!==null;)l.add(E[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");r=e.definitions[o]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,l=i.some(d=>d?.passed!==void 0);r.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(b){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw S.cause=b,S.code=b?.code||"NORMALIZE_INPUT_FAILED",S}let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();nr({path:K(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=K(s,".zibby.config.js");We(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let b=a?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},E=this._runtimeSchema();if(E){let b=E.safeParse(t);if(!b.success){let S=b.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${S.join(", ")}`)}P.step("State validated against schema")}let u=ir(),c=t.sessionPath||u;c||ar();let{sessionPath:_,sessionTimestamp:p,sessionId:A}=ur({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let v=await Se.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&P.step(`Context loaded: ${Object.keys(v).join(", ")}`);let O=t.outputPath;!O&&t.specPath&&(e?.calculateOutputPath?O=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new de({...t,config:a,agentType:l,outputPath:O,sessionPath:_,sessionTimestamp:p,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),T=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(Pe(),mt)),y=a.skills&&typeof a.skills=="object"?a.skills:{},m=Object.values(y).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),f=b=>{for(let S of m)if(S.id===b)return S;return w(b)},g=new Set;for(let[,b]of this.nodes)for(let S of b.config?.skills||[])g.add(S);for(let b of g){let S=f(b);if(typeof S?.middleware=="function")try{let C=await S.middleware();typeof C=="function"&&T.set(b,C)}catch{}}let{backEdges:$,joinDegree:N}=this._analyzeFlow(),W=new Map,ee=[],we=(b,S,C)=>{if(!b||b==="END")return;let L=N.get(b)||0;if(C&&L>1&&!$.has(`${S}->${b}`)){let te=(W.get(b)||0)+1;if(te<L){W.set(b,te);return}W.set(b,0)}ee.includes(b)||ee.push(b)};this.entryPoint&&ee.push(this.entryPoint);let ce=[],Je=a?.recursionLimit??100,Jt=0;try{for(;ee.length>0;){let S=ee.pop();if(!S||S==="END")continue;if(++Jt>Je)throw new Error(`Workflow exceeded recursion limit (${Je}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let C=K(_,lt);if(We(C)){try{tr(C)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
`);console.log(`[zibby:session] stack (${r}):
|
|
42
|
+
${I}`)}}function _n(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function wn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return sr(String(e).trim())}catch{return String(e).trim()}}function bn(){_n()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function En({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function In(r={}){let e=mt.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,o=r.paths?.sessionPrefix;return o?`${o}_${n}`:n}function Tn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let o=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let u=sr(String(process.env.ZIBBY_SESSION_PATH));u&&(o=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,s="config.sessionId"):(a=In(e),s="generated")}i=i??Date.now();let I=e.paths?.output||Ee;o=re(r,I,ht,a)}let l=!Qe(o);return l&&or(o,{recursive:!0}),(l||s!=="initialState.sessionPath")&&Sn({traceFrom:n,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:l}),En({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var nr=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof z)&&t&&typeof t=="object"&&t.collaboration){let s=typeof t.collaboration=="object"?t.collaboration:{},a={name:e,_isCustomCode:!0,collaboration:{protocolId:s.protocolId||"discuss.v1",required:s.required===!0,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs},description:t.description,retries:t.retries,onComplete:t.onComplete,execute:async u=>{let I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d=(h,p="")=>typeof h=="function"?h(I):h??p,c=await Xt({protocolId:s.protocolId,required:s.required,timeoutMs:s.timeoutMs,reserveMs:s.reserveMs,objective:d(s.objective),context:d(s.context),instruction:d(s.instruction)});if(s.required===!0&&c.status!=="completed"){let h=new Error(`Required collaboration did not complete: ${c.reason||c.status}`);throw h.code="COLLABORATION_REQUIRED_INCOMPLETE",h.collaborationResult=c,h}return c}},l=new z(a);return l.name=e,this.nodes.set(e,l),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}if(!(t instanceof z)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async u=>{let I=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof s.input=="function"?d=s.input(I):s.input&&typeof s.input=="object"?d=s.input:d={},Ve(s.workflow,{input:d,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(I):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:I?._signal,parentAgent:u?.agent})}},l=new z(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let o=!(t instanceof z)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof z?t:new z(o?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let o=this.edges.get(e);return o!==void 0&&!o.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(o)?o.join(", "):o}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&n(s)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let o=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||o.set(s,(o.get(s)||0)+1);return{backEdges:e,joinDegree:o}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,o,i){let s=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=s;s=()=>l(t,u,o,i)}return s()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let h=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:h,data:{nodeType:h,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(p.description=w);let $=c?.config?.collaboration;$&&typeof $=="object"&&(p.collaboration={protocolId:$.protocolId||"discuss.v1",required:$.required===!0,...Number.isFinite($.timeoutMs)?{timeoutMs:$.timeoutMs}:{},...Number.isFinite($.reserveMs)?{reserveMs:$.reserveMs}:{}});let P=c?.config?.collaborationAsync;P&&typeof P=="object"&&(p.collaborationAsync={protocolId:P.protocolId||"discuss.v1"});let m=this.nodePrompts.get(d);if(m)p.prompt=m;else if(typeof c.prompt=="function")try{let O=c.prompt({});typeof O=="string"&&O.trim()&&(p.prompt=O,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let b=c?.config?.dispatchesWorkflow;if(typeof b=="string"&&b.trim())p.dispatchesWorkflow=b.trim();else if(Array.isArray(b)){let O=[...new Set(b.filter(E=>typeof E=="string").map(E=>E.trim()).filter(Boolean))];O.length&&(p.dispatchesWorkflow=O)}let _=c?.config?.minimumReadyChildren;if(_!=null){if(!Number.isInteger(_)||_<=0)throw new Error(`Node '${d}' minimumReadyChildren must be a positive integer`);let O=typeof p.dispatchesWorkflow=="string"?1:Array.isArray(p.dispatchesWorkflow)?p.dispatchesWorkflow.length:0;if(_>O)throw new Error(`Node '${d}' minimumReadyChildren (${_}) exceeds its declared dispatch roster (${O})`);p.minimumReadyChildren=_}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let O=null;if(typeof Oe?.toJSONSchema=="function")try{O=Oe.toJSONSchema(c.outputSchema)}catch{}if(!O)try{O=rr(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=O?{jsonSchema:O,variables:this._flattenJsonSchemaToVariables(O)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let v=(this.resolvedToolsMap||{})[d];v?.toolIds&&(p.tools=v.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(p.skills=[...g]);let f=Array.isArray(c?.config?.optionalSkills)?c.config.optionalSkills:Array.isArray(c?.optionalSkills)?c.optionalSkills:null;f&&f.length>0&&(p.optionalSkills=[...f]);let y=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;y&&y.length>0&&(p.plugins=y.map(O=>O&&typeof O=="object"?{...O}:O));let M=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;M&&M.length>0&&(p.stores=M.map(O=>O&&typeof O=="object"?{...O}:O));let R=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(R&&R.length>0){let O=new Set,E=[];for(let C of R){let F=typeof C=="string"?C.trim():"";!F||O.has(F)||(O.add(F),E.push(F))}E.length>0&&(p.uses=E)}Object.keys(p).length>0&&(t[d]=p)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(Array.isArray(c))for(let h of c)n.push({source:d,target:h});else if(c.conditional){let h=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},$=this.nodes.get(d),P=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,m=d;if(!P){let b=`${d}__branch`;e.push({id:b,type:"decision",data:{nodeType:"decision",label:b}}),n.push({source:d,target:b}),m=b}for(let b of p){let _={source:m,target:b,data:{conditionalCode:h}};w[b]&&(_.label=w[b]),n.push(_)}}let o=d=>{if(!d)return null;if(typeof Oe?.toJSONSchema=="function")try{return Oe.toJSONSchema(d)}catch{}try{return rr(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of n)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let s=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=o(a||this.stateSchema),u=o(this.inputSchema),I=o(this.contextSchema);return{nodes:s,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:I}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),o=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),s=new Map(e.map(d=>[d.id,[]]));for(let d of t)s.has(d.source)&&i.has(d.target)&&(s.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>i.get(d)===0),I=[];for(;I.length<e.length;){let d;if(u.length>0){if(u.sort((c,h)=>n.get(c)-n.get(h)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,h)=>n.get(c)-n.get(h))[0];a.add(d),l.delete(d),I.push(o.get(d));for(let c of s.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return I}_inferConditionalTargets(e,t){let n=e.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(n))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&o.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of o)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,I;for(;(I=u.exec(n))!==null;)l.add(I[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let o=e.$ref.replace("#/definitions/","");n=e.definitions[o]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],o=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(o)){let l=t?`${t}.${s}`:s;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[o,i]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);n.push(l?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(T){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw S.cause=T,S.code=T?.code||"NORMALIZE_INPUT_FAILED",S}let o=new AbortController;n.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();mn({path:re(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=re(s,".zibby.config.js");Qe(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},I=this._runtimeSchema();if(I){let T=I.safeParse(t);if(!T.success){let S=T.error.issues.map(U=>`${U.path.join(".")}: ${U.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(U=>console.error(` - ${U}`)),new Error(`State validation failed: ${S.join(", ")}`)}D.step("State validated against schema")}let d=wn(),c=t.sessionPath||d;c||bn();let{sessionPath:h,sessionTimestamp:p,sessionId:w}=Tn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});D.step(`Session ${w}`);let $=await $e.loadContext(t.specPath||"",s,u);Object.keys($).length>0&&D.step(`Context loaded: ${Object.keys($).join(", ")}`);let P=t.outputPath;!P&&t.specPath&&(e?.calculateOutputPath?P=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new _e({...t,config:a,agentType:l,outputPath:P,sessionPath:h,sessionTimestamp:p,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),b=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(Ge(),Et)),v=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(v).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),f=T=>{for(let S of g)if(S.id===T)return S;return _(T)},y=new Set;for(let[,T]of this.nodes)for(let S of T.config?.skills||[])y.add(S);for(let T of y){let S=f(T);if(typeof S?.middleware=="function")try{let U=await S.middleware();typeof U=="function"&&b.set(T,U)}catch{}}let{backEdges:M,joinDegree:R}=this._analyzeFlow(),O=new Map,E=[],C=(T,S,U)=>{if(!T||T==="END")return;let j=R.get(T)||0;if(U&&j>1&&!M.has(`${S}->${T}`)){let q=(O.get(T)||0)+1;if(q<j){O.set(T,q);return}O.set(T,0)}E.includes(T)||E.push(T)};this.entryPoint&&E.push(this.entryPoint);let F=[],ge=a?.recursionLimit??100,ie=0;try{for(;E.length>0;){let S=E.pop();if(!S||S==="END")continue;if(++ie>ge)throw new Error(`Workflow exceeded recursion limit (${ge}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let U=re(h,gt);if(Qe(U)){try{gn(U)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
43
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),D.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:F,stoppedExternally:!0};let j=this.nodes.get(S);if(!j)throw new Error(`Node '${S}' not found in graph`);let q=JSON.stringify({sessionPath:h,sessionTimestamp:p,currentNode:S,createdAt:new Date().toISOString(),config:m.get("config")}),Y=re(h,oe);tr(Y,q,"utf-8");let ae=m.get("config")?.paths?.output||Ee,Me=re(s,ae,oe);or(re(s,ae),{recursive:!0});try{tr(Me,q,"utf-8")}catch{}let me=t.onPipelineProgress;if(typeof me=="function")try{me({cwd:s,sessionPath:h,sessionId:w,outputBase:m.get("config")?.paths?.output||Ee,currentNode:S})}catch{}let ir=(this.resolvedToolsMap||{})[S]||null;m.set("_currentNodeTools",ir);let ar=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",ar[S]||{}),D.nodeStart(S);let et=Date.now(),ye=this.nodePrompts.get(S);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(Je(),ze));this._invokeAgent=x.invokeAgent}let cr=this._invokeAgent,Re={},lr=j.config?.skills||[];for(let x of lr){let L=f(x);if(typeof L?.invokeAgentOptions=="function")try{let k=L.invokeAgentOptions(m.getAll(),{agentType:m.get("agentType"),nodeName:S});k&&typeof k=="object"&&(Re={...Re,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let tt=async(x,L,k={})=>{let G=cr(x,L,{...Re,...k,signal:o.signal});return G.catch(()=>{}),o.signal.aborted?G:Promise.race([G,new Promise((ne,J)=>{let W=()=>{setTimeout(()=>{let ot=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);ot.name="AbortError",J(ot)},i)};o.signal.addEventListener("abort",W,{once:!0})})])},ur=async(x={},L={})=>{let k=L.prompt||"";if(ye){let G=this._compiledPrompts.get(S);G||(G=yn.compile(ye,{noEscape:!0}),this._compiledPrompts.set(S,G));try{k=G(x)}catch(ne){throw console.error(`\u274C Template rendering failed for node '${S}':`,ne.message),new Error(`Template rendering failed: ${ne.message}`,{cause:ne})}}else if(!k)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return tt(k,{state:m.getAll(),images:L.images||[]},{model:L.model||m.get("model"),workspace:m.get("workspace"),schema:L.schema,...L,signal:o.signal,nodeName:S})},rt=m.getAll(),dr=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of dr)Object.prototype.hasOwnProperty.call(rt,x)&&console.warn(`[workflow] node "${S}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let nt={...rt,state:m,invokeAgent:ur,_coreInvokeAgent:tt,agent:e,nodeId:S,promptTemplate:ye,getPromptTemplate:()=>ye};try{let x=(j.config?.skills||[]).map(W=>b.get(W)).filter(Boolean),L=[...this.middleware,...x],k;k=await Pt(e,o.signal,async()=>L.length>0?this._composeMiddleware(L,S,async()=>j.execute(nt,m),m.getAll(),m):j.execute(nt,m));let G=Date.now()-et;if(F.push({node:S,success:k.success,duration:G,timestamp:new Date().toISOString()}),!k.success){if(o.signal.aborted)return D.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:F,stoppedExternally:!0};m.append("errors",{node:S,error:k.error});let W=Number.isInteger(k.attempts)&&k.attempts>0?k.attempts:(j.config?.retries||0)+1;throw D.nodeFailed(S,k.error,{duration:G}),new Error(`Node '${S}' failed after ${W} attempt(s): ${k.error}`)}m.update({[S]:k.output});let ne=this._summarizeNodeOutput(S,k.output);D.nodeComplete(S,{duration:G,details:ne});let J=this.edges.get(S);if(J)if(J.conditional){let W=J.routes(m.getAll());D.route(S,W),C(W,S,!1)}else if(Array.isArray(J))for(let W=J.length-1;W>=0;W--)C(J[W],S,!0);else C(J,S,!0)}catch(x){throw D.isInsideNode&&D.nodeFailed(S,x.message,{duration:Date.now()-et}),m.set("failed",!0),m.set("failedAt",S),x}}D.graphComplete();let T={success:!0,state:m.getAll(),executionLog:F};return e&&typeof e.onComplete=="function"&&await e.onComplete(T),T}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(T){console.warn(`[workflow] agent.cleanup() failed: ${T.message}`)}}}};export{nr as WorkflowGraph,bn as clearInheritedSessionEnvForFreshRun,In as generateWorkflowSessionId,wn as readPinnedSessionPathFromEnv,Tn as resolveWorkflowSession,_n as shouldTrustInheritedSessionEnv,En as syncProcessEnvToSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as ae,existsSync as w,statSync as V,readdirSync as L,rmSync as ie}from"node:fs";import{spawn as q}from"node:child_process";import{join as y}from"node:path";import{pathToFileURL as ce}from"node:url";import{AsyncLocalStorage as ue}from"node:async_hooks";var N=()=>{},ee={debug:N,info:N,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},U=Symbol.for("@zibby/agent-workflow.logger");globalThis[U]||(globalThis[U]={impl:ee});var B=globalThis[U];var b={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{AsyncLocalStorage as te}from"node:async_hooks";var $=new te;function C(){let e=$.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 H(e,t){let r=$.getStore()||C(),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 $.run(n,t)}var k=new Map,P=new Map,j=new Map;function F(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");k.set(e,t),P.set(e,"ready"),j.set(e,{...r,cachedAt:Date.now()})}function z(e,t){P.set(e,"failed"),j.set(e,{error:t?.message||String(t),failedAt:Date.now()}),k.delete(e)}function J(e){return P.get(e)==="ready"?k.get(e):null}function G(e,t,r=process.env){let n=Number(r[e]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):t}function re(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function D(e,t){return re(G(e,t),e)}function x(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}var E=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function le(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=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 W(e,t,r,n="timeout",s=null){let a=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(r/1e3)}s (last status: ${n})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return a.code="SUBGRAPH_TIMEOUT",a.subgraphJobId=t,a.subgraphStatus=n,s&&(a.subgraphTransportError=s),a}function de(e,t=process.env,r=process.uptime()){let n=Number.isFinite(e)?Number(e):null,s=Number(t&&t.MAX_WORKFLOW_DURATION_MS),a=Number.isFinite(r)&&r>0?r*1e3:0,o=Number.isFinite(s)&&s>0?s-a:null;if(n===null&&o===null)return null;let i=n===null?o:o===null?n:Math.min(n,o);return Math.max(1,i)}function pe(e,t){let r=new AbortController,n=!1,s=null,a=()=>{r.abort(e?.reason)};return e&&(e.aborted?a():e.addEventListener("abort",a,{once:!0})),t!=null&&!r.signal.aborted&&(s=setTimeout(()=>{n=!0,r.abort(new Error("sub-graph deadline exceeded"))},t),typeof s.unref=="function"&&s.unref()),{signal:r.signal,timedOut:()=>n,dispose(){s&&(clearTimeout(s),s=null),e&&e.removeEventListener("abort",a)}}}var X=new ue,Y=Promise.resolve();async function fe(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([o,i])=>typeof o=="string"&&o&&typeof i=="string"):[];if(r.length===0)return t();let n=X.getStore()===!0,s=null;if(!n){let o=Y;Y=new Promise(i=>{s=i}),await o}let a=new Map;try{for(let[o,i]of r)a.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=i;return b.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await X.run(!0,t)}finally{for(let[o,i]of a)i===void 0?delete process.env[o]:process.env[o]=i;s&&s()}}function he(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!r||!n||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:s}}async function ge({apiBase:e,authToken:t,body:r}){let n=D("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r),signal:n.signal})}catch(o){throw new l(x(o)?"begin-timeout":"network",x(o)?`begin TIMED OUT ${n.label}`:`begin fetch failed: ${o.message}`)}let a=null;try{a=await s.json()}catch(o){if(x(o))throw new l("begin-timeout",`begin body read TIMED OUT ${n.label}`)}if(!s.ok){if(s.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(s.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(s.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 l("begin-status",`begin returned ${s.status}`)}return a?.data||a}async function T({apiBase:e,authToken:t,payload:r}){let n=D("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r),signal:n.signal});s.ok||b.warn(`[in-process subgraph] finalize returned ${s.status} for ${r.childExecutionId}`)}catch(s){b.warn(`[in-process subgraph] finalize ${x(s)?`TIMED OUT ${n.label}`:`failed: ${s.message}`}`)}}async function ye(e,t){let r=y(t,".ready"),n=y(t,"graph.mjs");if(w(r)&&w(n))return;ae(t,{recursive:!0});let s=y(t,".lock"),a=!1;try{let{openSync:o,closeSync:i}=await import("node:fs"),d=o(s,"wx");i(d),a=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!a){let o=Date.now()+3e4;for(;Date.now()<o;){if(w(r)&&w(n))return;await new Promise(i=>setTimeout(i,100))}throw new l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let I=Math.ceil(1e4/1e3),R=Math.ceil(G("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),h=q("curl",["-fsSL","--connect-timeout",String(I),"--max-time",String(R),e],{stdio:["ignore","pipe","inherit"]}),_=q("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(_.stdin);let f,m,v=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(m!==0)return p(new Error(`tar exited ${m}`));d()}};h.on("close",S=>{f=S,v()}),_.on("close",S=>{m=S,v()}),h.on("error",p),_.on("error",p)});let{writeFileSync:o,unlinkSync:i}=await import("node:fs");o(r,"");try{i(s)}catch{}}catch(o){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new l("bundle-extract-failed",o.message)}}async function me(e){let t=y(e,"graph.mjs");if(!w(t))throw new l("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(ce(t).href)}catch(s){throw new l("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=r.default||Object.values(r).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new l("entry-class-missing","no buildGraph() class export found");return n}async function Re(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=C(),n;try{n=he()}catch(u){throw u}b.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await ge({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:a,runtimeTag:o,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:I,bundleReady:R,nodeConfigs:h}=s,_=le();if(o&&o!==_)throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,discard:!0}}),new l("runtime-mismatch",`${_} vs ${o}`);if(!R||!i)throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let f=J(e);if(!f){let u=y(E,`${I}@${p||"0"}`);try{await ye(i,u);try{be()}catch{}}catch(c){throw c.fallback&&await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{f=await me(u),F(e,f,{workflowUuid:I,version:p,runtimeTag:o,cacheDir:u})}catch(c){throw z(e,c),await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new l("import-failed",c.message)}}let m=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,S=h&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,Q={...t.input||{},...S?{nodeConfigs:h}:{}},M=de(t.timeoutMs),O=pe(t.signal,M),g,A;try{g=await fe(v,async()=>{let c=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return H({executionId:a,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,Q,{signal:O.signal}))}),A=g&&typeof g=="object"&&"state"in g?g.state:g}catch(u){let c=O.timedOut();throw await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(M/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:u.message,code:u.code||"CHILD_THREW",stack:u.stack},durationMs:Date.now()-m}}),c?W(e,a,M):u}finally{O.dispose()}if(g&&typeof g=="object"&&g.stoppedExternally){let u=O.timedOut();if(await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:u?"timeout":"canceled",finalState:A,durationMs:Date.now()-m}}),u)throw W(e,a,M);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=a,c}return await T({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"completed",finalState:A,durationMs:Date.now()-m}}),{finalState:A,executionId:a}}function Ue(){try{if(!w(E))return{bytes:0,entries:0};let e=L(E),t=0;for(let r of e)try{t+=Z(y(E,r))}catch{}return{bytes:t,entries:e.length}}catch{return{bytes:0,entries:0}}}function Z(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),s;try{s=V(n)}catch{continue}if(s.isDirectory()){let a;try{a=L(n)}catch{continue}for(let o of a)r.push(y(n,o))}else t+=s.size}return t}function be({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!w(E))return{evicted:0,freedBytes:0};let t=L(E),r=[],n=0;for(let i of t){let d=y(E,i),p;try{p=V(d)}catch{continue}let I=p.isDirectory()?Z(d):p.size;n+=I,r.push({name:i,full:d,size:I,mtimeMs:p.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),a=0,o=0;for(let i of r){if(n-a<=s)break;if(!w(y(i.full,".lock")))try{ie(i.full,{recursive:!0,force:!0}),a+=i.size,o+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return o>0&&b.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(a/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:a,totalBytes:n-a}}catch(t){return b.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,be as evictCacheIfOver,Ue as getCacheStats,de as resolveChildTimeoutMs,Re as runInProcessSubgraph,W as subgraphTimeoutError,pe as withChildDeadline};
|
|
1
|
+
import{mkdirSync as ae,existsSync as w,statSync as V,readdirSync as D,rmSync as ie}from"node:fs";import{spawn as q}from"node:child_process";import{join as y}from"node:path";import{pathToFileURL as ce}from"node:url";import{AsyncLocalStorage as ue}from"node:async_hooks";var N=()=>{},ee={debug:N,info:N,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},U=Symbol.for("@zibby/agent-workflow.logger");globalThis[U]||(globalThis[U]={impl:ee});var B=globalThis[U];var b={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{AsyncLocalStorage as te}from"node:async_hooks";var P=new te;function $(){let e=P.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 H(e,t){let r=P.getStore()||$(),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 P.run(n,t)}var C=new Map,k=new Map,j=new Map;function F(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");C.set(e,t),k.set(e,"ready"),j.set(e,{...r,cachedAt:Date.now()})}function z(e,t){k.set(e,"failed"),j.set(e,{error:t?.message||String(t),failedAt:Date.now()}),C.delete(e)}function J(e){return k.get(e)==="ready"?C.get(e):null}function G(e,t,r=process.env){let n=Number(r[e]);return Number.isFinite(n)&&n>0?Math.min(12e4,Math.max(1e3,Math.floor(n))):t}function re(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function L(e,t){return re(G(e,t),e)}function v(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}var E=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function le(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=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 W(e,t,r,n="timeout",s=null){let a=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(r/1e3)}s (last status: ${n})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return a.code="SUBGRAPH_TIMEOUT",a.subgraphJobId=t,a.subgraphStatus=n,s&&(a.subgraphTransportError=s),a}function de(e,t=process.env,r=process.uptime()){let n=Number.isFinite(e)?Number(e):null,s=Number(t&&t.MAX_WORKFLOW_DURATION_MS),a=Number.isFinite(r)&&r>0?r*1e3:0,o=Number.isFinite(s)&&s>0?s-a:null;if(n===null&&o===null)return null;let i=n===null?o:o===null?n:Math.min(n,o);return Math.max(1,i)}function pe(e,t){let r=new AbortController,n=!1,s=null,a=()=>{r.abort(e?.reason)};return e&&(e.aborted?a():e.addEventListener("abort",a,{once:!0})),t!=null&&!r.signal.aborted&&(s=setTimeout(()=>{n=!0,r.abort(new Error("sub-graph deadline exceeded"))},t),typeof s.unref=="function"&&s.unref()),{signal:r.signal,timedOut:()=>n,dispose(){s&&(clearTimeout(s),s=null),e&&e.removeEventListener("abort",a)}}}var X=new ue,Y=Promise.resolve();async function fe(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([o,i])=>typeof o=="string"&&o&&typeof i=="string"):[];if(r.length===0)return t();let n=X.getStore()===!0,s=null;if(!n){let o=Y;Y=new Promise(i=>{s=i}),await o}let a=new Map;try{for(let[o,i]of r)a.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=i;return b.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await X.run(!0,t)}finally{for(let[o,i]of a)i===void 0?delete process.env[o]:process.env[o]=i;s&&s()}}function he(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!r||!n||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:s}}async function ge({apiBase:e,authToken:t,body:r}){let n=L("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r),signal:n.signal})}catch(o){throw new l(v(o)?"begin-timeout":"network",v(o)?`begin TIMED OUT ${n.label}`:`begin fetch failed: ${o.message}`)}let a=null;try{a=await s.json()}catch(o){if(v(o))throw new l("begin-timeout",`begin body read TIMED OUT ${n.label}`)}if(!s.ok){if(s.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(s.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(s.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 l("begin-status",`begin returned ${s.status}`)}return a?.data||a}async function I({apiBase:e,authToken:t,payload:r}){let n=L("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r),signal:n.signal});s.ok||b.warn(`[in-process subgraph] finalize returned ${s.status} for ${r.childExecutionId}`)}catch(s){b.warn(`[in-process subgraph] finalize ${v(s)?`TIMED OUT ${n.label}`:`failed: ${s.message}`}`)}}async function ye(e,t){let r=y(t,".ready"),n=y(t,"graph.mjs");if(w(r)&&w(n))return;ae(t,{recursive:!0});let s=y(t,".lock"),a=!1;try{let{openSync:o,closeSync:i}=await import("node:fs"),d=o(s,"wx");i(d),a=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!a){let o=Date.now()+3e4;for(;Date.now()<o;){if(w(r)&&w(n))return;await new Promise(i=>setTimeout(i,100))}throw new l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let T=Math.ceil(1e4/1e3),R=Math.ceil(G("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),h=q("curl",["-fsSL","--connect-timeout",String(T),"--max-time",String(R),e],{stdio:["ignore","pipe","inherit"]}),_=q("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(_.stdin);let f,m,x=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(m!==0)return p(new Error(`tar exited ${m}`));d()}};h.on("close",S=>{f=S,x()}),_.on("close",S=>{m=S,x()}),h.on("error",p),_.on("error",p)});let{writeFileSync:o,unlinkSync:i}=await import("node:fs");o(r,"");try{i(s)}catch{}}catch(o){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new l("bundle-extract-failed",o.message)}}async function me(e){let t=y(e,"graph.mjs");if(!w(t))throw new l("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(ce(t).href)}catch(s){throw new l("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=r.default||Object.values(r).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new l("entry-class-missing","no buildGraph() class export found");return n}async function Re(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=$(),n;try{n=he()}catch(u){throw u}b.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await ge({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:a,runtimeTag:o,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:T,bundleReady:R,nodeConfigs:h}=s,_=le();if(o&&o!==_)throw await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,discard:!0}}),new l("runtime-mismatch",`${_} vs ${o}`);if(!R||!i)throw await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let f=J(e);if(!f){let u=y(E,`${T}@${p||"0"}`);try{await ye(i,u);try{be()}catch{}}catch(c){throw c.fallback&&await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{f=await me(u),F(e,f,{workflowUuid:T,version:p,runtimeTag:o,cacheDir:u})}catch(c){throw z(e,c),await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new l("import-failed",c.message)}}let m=Date.now(),x=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,S=h&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,Q={...t.input||{},...S?{nodeConfigs:h}:{}},M=de(t.timeoutMs),O=pe(t.signal,M),g,A;try{g=await fe(x,async()=>{let c=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return H({executionId:a,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,Q,{signal:O.signal}))}),A=g&&typeof g=="object"&&"state"in g?g.state:g}catch(u){let c=O.timedOut();throw await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(M/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:u.message,code:u.code||"CHILD_THREW",stack:u.stack},durationMs:Date.now()-m}}),c?W(e,a,M):u}finally{O.dispose()}if(g&&typeof g=="object"&&g.stoppedExternally){let u=O.timedOut();if(await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:u?"timeout":"canceled",finalState:A,durationMs:Date.now()-m}}),u)throw W(e,a,M);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=a,c}return await I({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"completed",finalState:A,durationMs:Date.now()-m}}),{finalState:A,executionId:a}}function Ue(){try{if(!w(E))return{bytes:0,entries:0};let e=D(E),t=0;for(let r of e)try{t+=Z(y(E,r))}catch{}return{bytes:t,entries:e.length}}catch{return{bytes:0,entries:0}}}function Z(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),s;try{s=V(n)}catch{continue}if(s.isDirectory()){let a;try{a=D(n)}catch{continue}for(let o of a)r.push(y(n,o))}else t+=s.size}return t}function be({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!w(E))return{evicted:0,freedBytes:0};let t=D(E),r=[],n=0;for(let i of t){let d=y(E,i),p;try{p=V(d)}catch{continue}let T=p.isDirectory()?Z(d):p.size;n+=T,r.push({name:i,full:d,size:T,mtimeMs:p.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),a=0,o=0;for(let i of r){if(n-a<=s)break;if(!w(y(i.full,".lock")))try{ie(i.full,{recursive:!0,force:!0}),a+=i.size,o+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return o>0&&b.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(a/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:a,totalBytes:n-a}}catch(t){return b.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,be as evictCacheIfOver,Ue as getCacheStats,de as resolveChildTimeoutMs,Re as runInProcessSubgraph,W as subgraphTimeoutError,pe as withChildDeadline};
|
package/dist/index.d.ts
CHANGED
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
* const result = await graph.run(null, { agentType: 'my-agent', cwd: process.cwd() });
|
|
26
26
|
*/
|
|
27
27
|
export { WorkflowGraph, WorkflowGraph as Graph } from './graph.js';
|
|
28
|
-
export { dispatchSubgraph } from './sub-graph-executor.js';
|
|
28
|
+
export { dispatchSubgraph, dispatchParticipant, listParticipants } from './sub-graph-executor.js';
|
|
29
|
+
export { runCollaboration, remainingWorkflowTimeMs } from './collaboration.js';
|
|
29
30
|
export { generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession, } from './graph.js';
|
|
30
31
|
export { Node } from './node.js';
|
|
31
32
|
export { classifyFailure, isTransientFailure, formatProviderError, providerErrorKindOf, providerErrorStatusOf, createAttemptBudget, transientRetryBudget, transientBackoffMs, transientBackoffBaseMs, PROVIDER_ERROR_KIND_CLASS, TRANSIENT_MESSAGE_PATTERNS, DEFAULT_TRANSIENT_RETRIES, MAX_TRANSIENT_RETRIES, DEFAULT_TRANSIENT_BACKOFF_MS, MAX_TRANSIENT_BACKOFF_MS, } from './failure-class.js';
|