@zibby/agent-workflow 2.0.0 → 2.0.1
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/graph-compiler.js +24 -24
- package/dist/graph.js +21 -21
- package/dist/in-process-subgraph.d.ts +75 -0
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +31 -31
- package/dist/sub-graph-executor.d.ts +7 -1
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Lt=Object.defineProperty;var ie=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Fe=(r,e)=>{for(var t in e)Lt(r,t,{get:e[t],enumerable:!0})};var Ge,Ut,le,$,Q=ie(()=>{Ge=()=>{},Ut={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},le={impl:Ut},$={debug:(...r)=>le.impl.debug?.(...r),info:(...r)=>le.impl.info?.(...r),warn:(...r)=>le.impl.warn?.(...r),error:(...r)=>le.impl.error?.(...r)}});var et=ie(()=>{});var tt={};Fe(tt,{clearSkills:()=>qt,getAllSkills:()=>Yt,getSkill:()=>$e,getSkillSource:()=>zt,hasSkill:()=>Jt,listSkillIds:()=>Zt,registerSkill:()=>Ht});function Ht(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,s=r.id;if(U.has(s)&&!n){let o=te.get(s);if(!(o===t)){let a=o||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} 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).`)}}U.set(s,Object.freeze({...r})),t===void 0?te.delete(s):te.set(s,t)}function $e(r){return U.get(r)||null}function Jt(r){return U.has(r)}function zt(r){return te.get(r)||null}function Yt(){return new Map(U)}function Zt(){return Array.from(U.keys())}function qt(){U.clear(),te.clear()}var Ie,Ee,U,te,ve=ie(()=>{Ie=Symbol.for("@zibby/agent-workflow.skills"),Ee=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ie]||(globalThis[Ie]=new Map);globalThis[Ee]||(globalThis[Ee]=new Map);U=globalThis[Ie],te=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>st,invokeAgent:()=>Xt,listStrategies:()=>Vt,registerStrategy:()=>Kt,resolveInvocationExtras:()=>rt,resolveInvocationModel:()=>nt});function Kt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=F.findIndex(t=>t.getName()===r.getName());e>=0?F[e]=r:F.push(r)}function Vt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let o=r.models||{},i=typeof s=="string"&&s.trim()&&s.trim()!=="auto"?s.trim():null,a=e.nodeName&&o[e.nodeName]||null,u=o.default||null,p=r.agent?.[t]?.model||null,w=(typeof n=="string"?n.trim():"")||null;return i||a||u||p||e.model||w||null}function rt({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 st(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let o=F.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${o}`)}$.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(o=>o.getName()===n);if(!s){let o=F.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${o}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return $.debug(`[workflow] using agent: ${s.getName()}`),s}async function Xt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},o=st(s),i=n.config||t.config||{},a=n._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",p=!u||u===o.name?a.model:null,w=nt({config:i,options:t,strategyName:o.name,envModel:process.env.MODEL,nodeConfigModel:p}),c={...t,model:w,...rt({options:t,stateView:n,context:e}),config:i},l=r,m=c.skills||[];if(m.length>0&&!t.skipPromptFragments){let T=t.connectedIntegrations;if(!T){let d=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof d=="string"&&d.trim()!==""){T={};for(let b of d.split(",").map(I=>I.trim()).filter(Boolean))T[b]=!0}}let v=d=>{let b=d&&d.requiresIntegration;return!b||!T?!0:(Array.isArray(b)?b:[b]).some(E=>T[E]===!0)},f=o.name==="assistant",h=d=>d?.inProcessOnly!==!0||f,_=m.map(d=>{let b=$e(d);if(!v(b)||!h(b))return null;let I=b?.promptFragment;return typeof I=="function"?I():I}).filter(Boolean);_.length>0&&(l+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${_.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let S=n._currentNodeConfig?.stores;if(Array.isArray(S)&&S.length>0&&typeof S[0]=="object"){let T=S.length<=8,v=S.map(f=>{let h=f?.id??f?.storeId??"",_=(f?.name??"").toString().trim()||h,d=f?.type?` \xB7 ${f.type}`:"",b=(f?.description||"").toString().replace(/\s+/g," ").trim(),I=`- ${_} \xB7 ${b||"(no description)"}${d} (id: ${h})`;if(T&&f?.schema&&typeof f.schema=="object"){let E=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);E.length&&(I+=`
|
|
6
|
+
fields: ${E.join(", ")}`)}return I});l+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${v.join(`
|
|
10
|
+
`)}`}let A=n._currentNodeConfig?.extraPromptInstructions?.trim();return A&&(l+=`
|
|
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
|
+
${A}
|
|
17
|
+
`),$.debug(`[workflow] prompt length: ${l.length} chars`),o.invoke(l,c)}var Ae,F,ke=ie(()=>{et();Q();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Wt=new Set(["__proto__","constructor","prototype"]);function Se(r){if(Wt.has(r))throw new Error(`Invalid state key: "${r}"`)}var ae=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){Se(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Se(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Se(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 G from"handlebars";var ce=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(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(o){if(!(o instanceof SyntaxError))throw o}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let o=typeof e[n];o!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${o}`)}if(s.validate&&n in e){let o=s.validate(e[n]);o&&t.push(`Field '${n}': ${o}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};
|
|
20
|
-
`?(
|
|
21
|
-
${Ye}`,e.col=Ze))}return r(
|
|
19
|
+
`)}`);return e}};Q();import{writeFileSync as Oe,readFileSync as ot,existsSync as it,mkdirSync as Qt}from"node:fs";import{join as xe,dirname as en}from"node:path";import x from"chalk";var Ft="__WORKFLOW_GRAPH_LOG__",ee=x.gray("\u2502"),Gt=x.gray("\u250C"),He=x.gray("\u2514"),we=x.green("\u25C6"),Je=x.hex("#c084fc")("\u25C6"),ze=x.hex("#2dd4bf")("\u25C6"),_e=x.red("\u25C6"),Ye=`${ee} `,Ze=2;function qe(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ke(r,e){return(t,n,s)=>{if(typeof t!="string")return r(t,n,s);let o=process.stdout.columns||120,i="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(i+=Ye,e.col=Ze,e.lineStart=!1),u===`
|
|
20
|
+
`?(i+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,i+=u):e.inEsc?(i+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,i+=u,e.col>=o&&(i+=`
|
|
21
|
+
${Ye}`,e.col=Ze))}return r(i,n,s)}}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=Ke(this._origStdoutWrite,e),process.stderr.write=Ke(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=`${Ft}${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(we,e):process.stdout.write.bind(process.stdout)(`${
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Je,e):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(_e,x.red(e)):process.stdout.write.bind(process.stdout)(`${
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(we,e):process.stdout.write.bind(process.stdout)(`${ee} ${we} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Je,e):process.stdout.write.bind(process.stdout)(`${ee} ${Je} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${ee} ${ze} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(_e,x.red(e)):process.stdout.write.bind(process.stdout)(`${ee} ${_e} ${x.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Gt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let i of s)this._rawWrite(`${we} ${i}`);let o=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,o=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${x.red("failed")}${o}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new be;var ue=".zibby/output",Ve="sessions",Z=".session-info.json",Xe=".zibby-stop";var Fn=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];G.helpers.inc||G.registerHelper("inc",r=>Number(r)+1);G.helpers.json||G.registerHelper("json",r=>JSON.stringify(r,null,2));G.helpers.eq||G.registerHelper("eq",(r,e)=>r===e);var L=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 ce(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 $.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,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){$.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?($.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return $.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&$.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let o;typeof this.prompt=="function"?o=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),o=this._compiledPrompt(n())):o=this.prompt;let i=s("_skillHints");i&&(o=`${i}
|
|
33
33
|
|
|
34
|
-
${i}`);let a=n(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Oe(d,Z);if(it(l)){let I=JSON.parse(ot(l,"utf-8"));I.currentNode=this.name,xe(l,JSON.stringify(I,null,2),"utf-8")}let c=Oe(d,"..",Z);if(it(c))try{let I=JSON.parse(ot(c,"utf-8"));I.currentNode=this.name,xe(c,JSON.stringify(I,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let m=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=n().config||{},I=c.agents||{},w=this.config.agent??I[this.name]??null,v={state:n()};w&&(v.preferredAgent=w);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await $(i,v,A),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),d)try{let p=Oe(d,this.name,"raw_stream_output.txt");Xt(Qt(p),{recursive:!0}),xe(p,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),y)}catch(_){b.warn(`[workflow] onComplete hook failed: ${_.message}`)}return{success:!0,output:p,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(g);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:g}}return{success:!0,output:g,raw:g}}catch(c){m=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as nn,existsSync as J,statSync as mt,readdirSync as yt,rmSync as rn}from"node:fs";import{spawn as ft}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as sn}from"node:url";import{AsyncLocalStorage as on}from"node:async_hooks";import{AsyncLocalStorage as en}from"node:async_hooks";var re=new en;function q(){let r=re.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 at(r,e){let t=re.getStore()||q(),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 re.run(n,e)}function ct(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,lt=new Map;function ut(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");Pe.set(r,e),Ne.set(r,"ready"),lt.set(r,{...t,cachedAt:Date.now()})}function pt(r,e){Ne.set(r,"failed"),lt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function dt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var de=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function an(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=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"}},ht=new on,gt=Promise.resolve();async function cn(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ht.getStore()===!0,s=null;if(!n){let o=gt;gt=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ht.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function ln(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function un({apiBase:r,authToken:e,body:t}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new N("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new N("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function H({apiBase:r,authToken:e,payload:t}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||b.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){b.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function pn(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;nn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),u=o(s,"wx");a(u),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let m=ft("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),l=ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(l.stdin);let c,I,w=()=>{if(c!==void 0&&I!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(I!==0)return d(new Error(`tar exited ${I}`));u()}};m.on("close",v=>{c=v,w()}),l.on("close",v=>{I=v,w()}),m.on("error",d),l.on("error",d)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new N("bundle-extract-failed",o.message)}}async function dn(r){let e=W(r,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(sn(e).href)}catch(s){throw new N("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function St(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=ln()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await un({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:m,bundleReady:l,nodeConfigs:c}=s,I=an();if(o&&o!==I)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${I} vs ${o}`);if(!l||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let w=dt(r);if(!w){let p=W(de,`${m}@${d||"0"}`);try{await pn(a,p);try{hn()}catch{}}catch(_){throw _.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{w=await dn(p),ut(r,w,{workflowUuid:m,version:d,runtimeTag:o,cacheDir:p})}catch(_){throw pt(r,_),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new N("import-failed",_.message)}}let v=Date.now(),A=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...$?{nodeConfigs:c}:{}},g,y;try{g=await cn(A,async()=>{let _=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return at({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(p){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-v}}),p}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-v}});let p=new Error(`Sub-graph '${r}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:i}}function fn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=mt(n)}catch{continue}if(s.isDirectory()){let i;try{i=yt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function hn({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(de))return{evicted:0,freedBytes:0};let e=yt(de),t=[],n=0;for(let a of e){let u=W(de,a),d;try{d=mt(u)}catch{continue}let m=d.isDirectory()?fn(u):d.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:d.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(r*.7),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{rn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&b.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var gn=2e3,mn=600*1e3,yn=new Set(["completed","failed","canceled","timeout"]);function Sn(){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 wn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function _n(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function In(){return process.env.EXECUTION_ID||null}function wt(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 _t(r,e={}){if(!r||typeof r!="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 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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{b.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await St(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=wt(y,e.output);return b.info(`[sub-graph] '${r}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)b.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=Sn(),i=wn(),o=_n(),a=In(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(d)});if(!m.ok){let y=null,p="";try{y=await m.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await m.text().catch(()=>"")}if(m.status===429){let E=y?.quotaInfo||{},P=new Error(`Sub-graph '${r}' blocked by execution quota (${E.used??"?"}/${E.limit??"?"} on plan ${E.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw P.code="SUBGRAPH_QUOTA_EXCEEDED",P.status=429,P.subgraph=r,P.quotaInfo=E,P}if(m.status===400){let E=new Error(`Sub-graph '${r}' rejected input: ${p}`);throw E.code="SUBGRAPH_INVALID_INPUT",E.status=400,E.subgraph=r,E.validationErrors=y?.validationErrors||null,E.missing=y?.missing||null,E}let _=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${p}`);throw _.code="SUBGRAPH_TRIGGER_FAILED",_.status=m.status,_.subgraph=r,_}let l=await m.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return b.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:r};let I=Number.isFinite(e.timeoutMs)?e.timeoutMs:mn,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:gn,v=`${s}/executions/${encodeURIComponent(c)}`,A=Date.now()+I,$="accepted",f=0;for(;Date.now()<A;){await new Promise(E=>setTimeout(E,w)),f+=1;let y=await fetch(v,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),_=p?.data||p?.execution||p;if($=_?.status||$,yn.has($)){if($!=="completed"){let K=new Error(`Sub-graph '${r}' (${c}) ended in status '${$}'`);throw K.subgraphJobId=c,K.subgraphStatus=$,K}let E=_?.finalState||_?.state||{},P=wt(E,e.output);return b.info(`[sub-graph] '${r}' (${c}) completed after ${f} polls`),P}}let g=new Error(`Sub-graph '${r}' (${c}) timed out after ${Math.round(I/1e3)}s (last status: ${$})`);throw g.subgraphJobId=c,g.subgraphStatus=$,g}import{existsSync as It,readFileSync as bn}from"node:fs";import{join as Re,dirname as bt}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=bt(Re(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=d}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let d=Re(t,u);It(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(It(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=bt(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
|
|
34
|
+
${o}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=xe(p,Z);if(it(c)){let m=JSON.parse(ot(c,"utf-8"));m.currentNode=this.name,Oe(c,JSON.stringify(m,null,2),"utf-8")}let l=xe(p,"..",Z);if(it(l))try{let m=JSON.parse(ot(l,"utf-8"));m.currentNode=this.name,Oe(l,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(c){$.debug(`[workflow] could not update session info: ${c.message}`)}let w=null;for(let c=0;c<=this.retries;c++)try{$.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},m=l.agents||{},S=this.config.agent??m[this.name]??null,A={state:n()};S&&(A.preferredAgent=S);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},v=e?._coreInvokeAgent;v||(v=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await v(o,A,T),h,_;if(typeof f=="string"?(h=f,_=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),_=f.structured):(h=f.raw||JSON.stringify(f,null,2),_=f.extracted||null),p)try{let d=xe(p,this.name,"raw_stream_output.txt");Qt(en(d),{recursive:!0}),Oe(d,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(d){$.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&_){$.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let d=_;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),_)}catch(b){$.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:d,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:h}),raw:h}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(h);return $.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),P.step("Output parsed"),{success:!0,output:d,raw:h}}return{success:!0,output:h,raw:h}}catch(l){w=l,c<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:w.message,raw:null}}};Q();Q();import{mkdirSync as rn,existsSync as J,statSync as mt,readdirSync as yt,rmSync as sn}from"node:fs";import{spawn as ft}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as on}from"node:url";import{AsyncLocalStorage as an}from"node:async_hooks";import{AsyncLocalStorage as tn}from"node:async_hooks";var ne=new tn;function q(){let r=ne.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 at(r,e){let t=ne.getStore()||q(),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 ne.run(n,e)}function ct(r,e,t){let n=ne.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return ne.run(s,t)}var Pe=new Map,Ne=new Map,lt=new Map;function ut(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");Pe.set(r,e),Ne.set(r,"ready"),lt.set(r,{...t,cachedAt:Date.now()})}function pt(r,e){Ne.set(r,"failed"),lt.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function dt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function cn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=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 de(r,e,t,n="timeout"){let s=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`);return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=e,s.subgraphStatus=n,s}function ln(r,e=process.env,t=process.uptime()){let n=Number.isFinite(r)?Number(r):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),o=Number.isFinite(t)&&t>0?t*1e3:0,i=Number.isFinite(s)&&s>0?s-o:null;if(n===null&&i===null)return null;let a=n===null?i:i===null?n:Math.min(n,i);return Math.max(1,a)}function un(r,e){let t=new AbortController,n=!1,s=null,o=()=>{t.abort(r?.reason)};return r&&(r.aborted?o():r.addEventListener("abort",o,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{n=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>n,dispose(){s&&(clearTimeout(s),s=null),r&&r.removeEventListener("abort",o)}}}var ht=new an,gt=Promise.resolve();async function pn(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([i,a])=>typeof i=="string"&&i&&typeof a=="string"):[];if(t.length===0)return e();let n=ht.getStore()===!0,s=null;if(!n){let i=gt;gt=new Promise(a=>{s=a}),await i}let o=new Map;try{for(let[i,a]of t)o.set(i,Object.prototype.hasOwnProperty.call(process.env,i)?process.env[i]:void 0),process.env[i]=a;return $.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ht.run(!0,e)}finally{for(let[i,a]of o)a===void 0?delete process.env[i]:process.env[i]=a;s&&s()}}function dn(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function fn({apiBase:r,authToken:e,body:t}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(o){throw new N("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let o=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(n.status===429){let o=s?.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(n.status===400&&s?.validationErrors){let o=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=s.validationErrors,o.missing=s.missing,o}throw new N("begin-status",`begin returned ${n.status}`)}return s?.data||s}async function H({apiBase:r,authToken:e,payload:t}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||$.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){$.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function hn(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;rn(e,{recursive:!0});let s=W(e,".lock"),o=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),u=i(s,"wx");a(u),o=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!o){let i=Date.now()+3e4;for(;Date.now()<i;){if(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let w=ft("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});w.stdout.pipe(c.stdin);let l,m,S=()=>{if(l!==void 0&&m!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(m!==0)return p(new Error(`tar exited ${m}`));u()}};w.on("close",A=>{l=A,S()}),c.on("close",A=>{m=A,S()}),w.on("error",p),c.on("error",p)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(t,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new N("bundle-extract-failed",i.message)}}async function gn(r){let e=W(r,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(on(e).href)}catch(s){throw new N("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function St(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=dn()}catch(I){throw I}$.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await fn({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:o,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:w,bundleReady:c,nodeConfigs:l}=s,m=cn();if(i&&i!==m)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new N("runtime-mismatch",`${m} vs ${i}`);if(!c||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let S=dt(r);if(!S){let I=W(pe,`${w}@${p||"0"}`);try{await hn(a,I);try{yn()}catch{}}catch(E){throw E.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{S=await gn(I),ut(r,S,{workflowUuid:w,version:p,runtimeTag:i,cacheDir:I})}catch(E){throw pt(r,E),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new N("import-failed",E.message)}}let A=Date.now(),T=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,v=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...v?{nodeConfigs:l}:{}},h=ln(e.timeoutMs),_=un(e.signal,h),d,b;try{d=await pn(T,async()=>{let E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return at({executionId:o,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,f,{signal:_.signal}))}),b=d&&typeof d=="object"&&"state"in d?d.state:d}catch(I){let E=_.timedOut();throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:E?"timeout":"failed",error:E?{message:`aborted at the declared ${Math.round(h/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:I.message,code:I.code||"CHILD_THREW",stack:I.stack},durationMs:Date.now()-A}}),E?de(r,o,h):I}finally{_.dispose()}if(d&&typeof d=="object"&&d.stoppedExternally){let I=_.timedOut();if(await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:I?"timeout":"canceled",finalState:b,durationMs:Date.now()-A}}),I)throw de(r,o,h);let E=new Error(`Sub-graph '${r}' canceled by parent abort`);throw E.code="SUBGRAPH_CANCELED",E.subgraphJobId=o,E}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:"completed",finalState:b,durationMs:Date.now()-A}}),{finalState:b,executionId:o}}function mn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=mt(n)}catch{continue}if(s.isDirectory()){let o;try{o=yt(n)}catch{continue}for(let i of o)t.push(W(n,i))}else e+=s.size}return e}function yn({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=yt(pe),t=[],n=0;for(let a of e){let u=W(pe,a),p;try{p=mt(u)}catch{continue}let w=p.isDirectory()?mn(u):p.size;n+=w,t.push({name:a,full:u,size:w,mtimeMs:p.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(r*.7),o=0,i=0;for(let a of t){if(n-o<=s)break;if(!J(W(a.full,".lock")))try{sn(a.full,{recursive:!0,force:!0}),o+=a.size,i+=1}catch(u){$.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return i>0&&$.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:o,totalBytes:n-o}}catch(e){return $.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Sn=2e3,wn=600*1e3,_n=new Set(["completed","failed","canceled","timeout"]);function bn(){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 In(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function En(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function $n(){return process.env.EXECUTION_ID||null}function wt(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 _t(r,e={}){if(!r||typeof r!="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 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 s=Number.isFinite(e.timeoutMs)?e.timeoutMs:wn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{$.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:h}=await St(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),_=wt(h,e.output);return $.info(`[sub-graph] '${r}' completed in-process`),_}catch(h){if(h instanceof N||h?.fallback)$.info(`[sub-graph] in-process fallback for '${r}': ${h.reason||"unknown"} \u2014 using HTTP`);else throw h}let o=bn(),i=In(),a=En(),u=$n(),p=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,w={input:e.input||{},...u?{parentExecutionId:u}:{},...e.conversationId?{conversationId:e.conversationId}:{}};$.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${u||"<none>"}`);let c=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(w)});if(!c.ok){let h=null,_="";try{h=await c.json(),_=h?.error||h?.message||JSON.stringify(h)}catch{_=await c.text().catch(()=>"")}if(c.status===429){let b=h?.quotaInfo||{},I=new Error(`Sub-graph '${r}' blocked by execution quota (${b.used??"?"}/${b.limit??"?"} on plan ${b.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw I.code="SUBGRAPH_QUOTA_EXCEEDED",I.status=429,I.subgraph=r,I.quotaInfo=b,I}if(c.status===400){let b=new Error(`Sub-graph '${r}' rejected input: ${_}`);throw b.code="SUBGRAPH_INVALID_INPUT",b.status=400,b.subgraph=r,b.validationErrors=h?.validationErrors||null,b.missing=h?.missing||null,b}let d=new Error(`Sub-graph '${r}' trigger rejected (${c.status}): ${_}`);throw d.code="SUBGRAPH_TRIGGER_FAILED",d.status=c.status,d.subgraph=r,d}let l=await c.json(),m=l?.data?.jobId||l?.jobId;if(!m)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${m} (not waiting)`),{jobId:m,status:"accepted",workflow:r};let S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Sn,A=`${o}/executions/${encodeURIComponent(m)}`,T=Date.now()+s,v="accepted",f=0;for(;Date.now()<T;){await new Promise(b=>setTimeout(b,S)),f+=1;let h=await fetch(A,{headers:{Authorization:`Bearer ${a}`}});if(!h.ok){if(h.status>=500){$.warn(`[sub-graph] status poll for ${m} returned ${h.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${m}: ${h.status}`)}let _=await h.json(),d=_?.data||_?.execution||_;if(v=d?.status||v,_n.has(v)){if(v!=="completed"){let E=new Error(`Sub-graph '${r}' (${m}) ended in status '${v}'`);throw E.subgraphJobId=m,E.subgraphStatus=v,E}let b=d?.finalState||d?.state||{},I=wt(b,e.output);return $.info(`[sub-graph] '${r}' (${m}) completed after ${f} polls`),I}}throw de(r,m,s,v)}import{existsSync as bt,readFileSync as vn}from"node:fs";import{join as Re,dirname as It}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},o=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=It(Re(t,e));for(let u of o){let p=await this.findAndMergeContextFiles(u,a,t);if(p){let w=u.replace(/\.[^.]+$/,"").toLowerCase();s[w]=p}}}let i=n.discovery||{};for(let[a,u]of Object.entries(i))try{let p=Re(t,u);bt(p)&&(s[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],o=t;for(;o.startsWith(n);){let i=Re(o,e);if(bt(i))try{s.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=It(o);if(a===o)break;o=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):s.every(
|
|
38
|
+
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=vn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as At,existsSync as Be,writeFileSync as Et,unlinkSync as An}from"node:fs";import{join as z,resolve as Tt}from"node:path";import{config as Tn}from"dotenv";import{zodToJsonSchema as $t}from"zod-to-json-schema";import{z as he}from"zod";import kn from"handlebars";function On({traceFrom:r,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${i} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let w=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
41
|
-
${m}`)}}function Tn(){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 kn(){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 Tt(String(e).trim())}catch{return String(e).trim()}}function xn(){Tn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function On({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 Pn(r={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${n}`:n}function Nn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let d=Tt(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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,o="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,o="config.sessionId"):(a=Pn(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ve,a)}let u=!Be(s);return u&&At(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&An({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),On({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var vt=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async d=>{let m=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof o.input=="function"?l=o.input(m):o.input&&typeof o.input=="object"?l=o.input:l={},_t(o.workflow,{input:l,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:d?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...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 s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). 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 o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],d=o;o=()=>u(t,d,s,i)}return o()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let I=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:I,data:{nodeType:I,label:l}});let w={};c._isCustomCode&&typeof c.execute=="function"&&(w.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(w.description=v);let A=this.nodePrompts.get(l);if(A)w.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(w.prompt=p,w.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(w.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(w.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=$t(c.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else w.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[l];$?.toolIds&&(w.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(w.skills=[...f]);let g=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;g&&g.length>0&&(w.plugins=g.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(w.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(w).length>0&&(t[l]=w)}let n=[];for(let[l,c]of this.edges)if(typeof c=="string")n.push({source:l,target:c});else if(Array.isArray(c))for(let I of c)n.push({source:l,target:I});else if(c.conditional){let I=this.conditionalCodeMap.get(l)||c.routes.toString(),w=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},A=this.nodes.get(l),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!$){let g=`${l}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:l,target:g}),f=g}for(let g of w){let y={source:f,target:g,data:{conditionalCode:I}};v[g]&&(y.label=v[g]),n.push(y)}}let s=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return $t(l,{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 l of n)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:l,target:c})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((l,c)=>[l.id,c])),s=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),o=new Map(e.map(l=>[l.id,[]]));for(let l of t)o.has(l.source)&&i.has(l.target)&&(o.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(n.keys()),d=[...u].filter(l=>i.get(l)===0),m=[];for(;m.length<e.length;){let l;if(d.length>0){if(d.sort((c,I)=>n.get(c)-n.get(I)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,I)=>n.get(c)-n.get(I))[0];a.add(l),u.delete(l),m.push(s.get(l));for(let c of o.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let d=o[2]!==void 0?o[2]:o[3];d!==void 0&&d!==""&&s.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 u=new Set;for(let d of s)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=d.exec(n))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}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[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} 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(S){let h=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw h.cause=S,h.code=S?.code||"NORMALIZE_INPUT_FAILED",h}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();$n({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=z(o,".zibby.config.js");Be(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let S=m.safeParse(t);if(!S.success){let h=S.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let l=kn(),c=t.sessionPath||l;c||xn();let{sessionPath:I,sessionTimestamp:w,sessionId:v}=Nn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${v}`);let A=await fe.loadContext(t.specPath||"",o,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:$,sessionPath:I,sessionTimestamp:w,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},_=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),E=S=>{for(let h of _)if(h.id===S)return h;return y(S)},P=new Set;for(let[,S]of this.nodes)for(let h of S.config?.skills||[])P.add(h);for(let S of P){let h=E(S);if(typeof h?.middleware=="function")try{let C=await h.middleware();typeof C=="function"&&g.set(S,C)}catch{}}let{backEdges:K,joinDegree:kt}=this._analyzeFlow(),ge=new Map,V=[],me=(S,h,C)=>{if(!S||S==="END")return;let j=kt.get(S)||0;if(C&&j>1&&!K.has(`${h}->${S}`)){let X=(ge.get(S)||0)+1;if(X<j){ge.set(S,X);return}ge.set(S,0)}V.includes(S)||V.push(S)};this.entryPoint&&V.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,xt=0;try{for(;V.length>0;){let h=V.pop();if(!h||h==="END")continue;if(++xt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \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=z(I,Xe);if(Be(C)){try{En(C)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
${w}`)}}function xn(){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 Pn(){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 Tt(String(e).trim())}catch{return String(e).trim()}}function Nn(){xn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Rn({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 Bn(r={}){let e=Qe.map(o=>process.env[o]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${n}`:n}function Cn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,o=t.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=Tt(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),o==null&&(o=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,i="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Bn(e),i="generated")}o=o??Date.now();let w=e.paths?.output||ue;s=z(r,w,Ve,a)}let u=!Be(s);return u&&At(s,{recursive:!0}),(u||i!=="initialState.sessionPath")&&On({traceFrom:n,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:u}),Rn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:o}}var vt=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let i=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:i.workflow,retries:i.retries,onComplete:i.onComplete,execute:async p=>{let w=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof i.input=="function"?c=i.input(w):i.input&&typeof i.input=="object"?c=i.input:c={},_t(i.workflow,{input:c,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(w):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:w?._signal,parentAgent:p?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,o=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return o.name=e,this.nodes.set(e,o),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 s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). 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=o=>{t.set(o,1);for(let i of this._simpleTargets(o)){if(!i||i==="END")continue;let a=t.get(i)||0;a===1?e.add(`${o}->${i}`):a===0&&n(i)}t.set(o,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[o]of this.edges)for(let i of this._simpleTargets(o))!i||i==="END"||e.has(`${o}->${i}`)||s.set(i,(s.get(i)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,o){let i=n;for(let a=e.length-1;a>=0;a--){let u=e[a],p=i;i=()=>u(t,p,s,o)}return i()}serialize(){let e=[],t={};for(let[c,l]of this.nodes){let m=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:m,data:{nodeType:m,label:c}});let S={};l._isCustomCode&&typeof l.execute=="function"&&(S.customCode=l.execute.toString());let A=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;A&&(S.description=A);let T=this.nodePrompts.get(c);if(T)S.prompt=T;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(S.prompt=d,S.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(S.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),typeof l?.config?.agent=="string"&&l.config.agent.trim()&&(S.agent=l.config.agent.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof he?.toJSONSchema=="function")try{d=he.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=$t(l.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else S.outputSchema={schema:l.outputSchema};let v=(this.resolvedToolsMap||{})[c];v?.toolIds&&(S.tools=v.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(S.skills=[...f]);let h=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;h&&h.length>0&&(S.plugins=h.map(d=>d&&typeof d=="object"?{...d}:d));let _=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;_&&_.length>0&&(S.stores=_.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(S).length>0&&(t[c]=S)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(Array.isArray(l))for(let m of l)n.push({source:c,target:m});else if(l.conditional){let m=this.conditionalCodeMap.get(c)||l.routes.toString(),S=this._inferConditionalTargets(l.routes,l.labels),A=l.labels||{},T=this.nodes.get(c),v=T?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!T,f=c;if(!v){let h=`${c}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),n.push({source:c,target:h}),f=h}for(let h of S){let _={source:f,target:h,data:{conditionalCode:m}};A[h]&&(_.label=A[h]),n.push(_)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return $t(c,{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 o=0;for(let c of n)if(c.target==="END"){o+=1;let l=`END__${o}`;c.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){o+=1;let l=`END__${o}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let i=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),w=s(this.contextSchema);return{nodes:i,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:p,contextSchema:w}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id,0])),i=new Map(e.map(c=>[c.id,[]]));for(let c of t)i.has(c.source)&&o.has(c.target)&&(i.get(c.source).push(c.target),o.set(c.target,o.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>o.get(c)===0),w=[];for(;w.length<e.length;){let c;if(p.length>0){if(p.sort((l,m)=>n.get(l)-n.get(m)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,m)=>n.get(l)-n.get(m))[0];a.add(c),u.delete(c),w.push(s.get(c));for(let l of i.get(c)||[])o.set(l,o.get(l)-1),o.get(l)<=0&&!a.has(l)&&p.push(l)}return w}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,o=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=o.exec(n))!==null;){let p=i[2]!==void 0?i[2]:i[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(t&&typeof t=="object")for(let p of Object.keys(t))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,w;for(;(w=p.exec(n))!==null;)u.add(w[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},o=e.required||[];for(let[i,a]of Object.entries(s)){let u=t?`${t}.${i}`:i;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!o.includes(i)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}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[s,o]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof o=="string"&&o.length<=80)n.push(`${s}: ${o}`);else if(Array.isArray(o)){let i=o.length,a=o.filter(p=>p?.passed===!0).length,u=o.some(p=>p?.passed!==void 0);n.push(u?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} 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(y){let g=new Error(`agent.normalizeInput() rejected the trigger input: ${y?.message||y}`);throw g.cause=y,g.code=y?.code||"NORMALIZE_INPUT_FAILED",g}let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let o=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,i=t.cwd||process.cwd();Tn({path:z(i,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let y=z(i,".zibby.config.js");Be(y)&&(a=(await import(y)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let y=a?.agent;y?.provider?u=y.provider:y?.gemini?u="gemini":y?.claude?u="claude":y?.cursor?u="cursor":y?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},w=this._runtimeSchema();if(w){let y=w.safeParse(t);if(!y.success){let g=y.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),g.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${g.join(", ")}`)}P.step("State validated against schema")}let c=Pn(),l=t.sessionPath||c;l||Nn();let{sessionPath:m,sessionTimestamp:S,sessionId:A}=Cn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let T=await fe.loadContext(t.specPath||"",i,p);Object.keys(T).length>0&&P.step(`Context loaded: ${Object.keys(T).join(", ")}`);let v=t.outputPath;!v&&t.specPath&&(e?.calculateOutputPath?v=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ae({...t,config:a,agentType:u,outputPath:v,sessionPath:m,sessionTimestamp:S,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:_}=await Promise.resolve().then(()=>(ve(),tt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},b=Object.values(d).filter(y=>y&&typeof y=="object"&&typeof y.id=="string"),I=y=>{for(let g of b)if(g.id===y)return g;return _(y)},E=new Set;for(let[,y]of this.nodes)for(let g of y.config?.skills||[])E.add(g);for(let y of E){let g=I(y);if(typeof g?.middleware=="function")try{let C=await g.middleware();typeof C=="function"&&h.set(y,C)}catch{}}let{backEdges:kt,joinDegree:Ot}=this._analyzeFlow(),ge=new Map,K=[],me=(y,g,C)=>{if(!y||y==="END")return;let j=Ot.get(y)||0;if(C&&j>1&&!kt.has(`${g}->${y}`)){let V=(ge.get(y)||0)+1;if(V<j){ge.set(y,V);return}ge.set(y,0)}K.includes(y)||K.push(y)};this.entryPoint&&K.push(this.entryPoint);let re=[],Ce=a?.recursionLimit??100,xt=0;try{for(;K.length>0;){let g=K.pop();if(!g||g==="END")continue;if(++xt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \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=z(m,Xe);if(Be(C)){try{An(C)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:re,stoppedExternally:!0};let j=this.nodes.get(g);if(!j)throw new Error(`Node '${g}' not found in graph`);let V=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:g,createdAt:new Date().toISOString(),config:f.get("config")}),Pt=z(m,Z);Et(Pt,V,"utf-8");let Me=f.get("config")?.paths?.output||ue,Nt=z(i,Me,Z);At(z(i,Me),{recursive:!0});try{Et(Nt,V,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:i,sessionPath:m,sessionId:A,outputBase:f.get("config")?.paths?.output||ue,currentNode:g})}catch{}let Rt=(this.resolvedToolsMap||{})[g]||null;f.set("_currentNodeTools",Rt);let Bt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Bt[g]||{}),P.nodeStart(g);let De=Date.now(),se=this.nodePrompts.get(g);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=O.invokeAgent}let Ct=this._invokeAgent,ye={},Mt=j.config?.skills||[];for(let O of Mt){let R=I(O);if(typeof R?.invokeAgentOptions=="function")try{let k=R.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:g});k&&typeof k=="object"&&(ye={...ye,...k})}catch(k){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${k.message}`)}}let Le=async(O,R,k={})=>{let M=Ct(O,R,{...ye,...k,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((Y,D)=>{let B=()=>{setTimeout(()=>{let X=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${o}ms`);X.name="AbortError",D(X)},o)};s.signal.addEventListener("abort",B,{once:!0})})])},jt=async(O={},R={})=>{let k=R.prompt||"";if(se){let M=this._compiledPrompts.get(g);M||(M=kn.compile(se,{noEscape:!0}),this._compiledPrompts.set(g,M));try{k=M(O)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${g}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!k)throw new Error(`No prompt template configured for node '${g}' and no prompt provided in options`);return Le(k,{state:f.getAll(),images:R.images||[]},{model:R.model||f.get("model"),workspace:f.get("workspace"),schema:R.schema,...R,signal:s.signal})},We=f.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let O of Dt)Object.prototype.hasOwnProperty.call(We,O)&&console.warn(`[workflow] node "${g}": state key "${O}" is shadowed by the engine context prop; read it via context.state.get('${O}')`);let Ue={...We,state:f,invokeAgent:jt,_coreInvokeAgent:Le,agent:e,nodeId:g,promptTemplate:se,getPromptTemplate:()=>se};try{let O=(j.config?.skills||[]).map(B=>h.get(B)).filter(Boolean),R=[...this.middleware,...O],k;k=await ct(e,s.signal,async()=>R.length>0?this._composeMiddleware(R,g,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let M=Date.now()-De;if(re.push({node:g,success:k.success,duration:M,timestamp:new Date().toISOString()}),!k.success){if(s.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:re,stoppedExternally:!0};f.append("errors",{node:g,error:k.error});let B=j.config?.retries||0,X=`${g}_retries`,oe=f.getAll()[X]||0;if(oe<B){P.stepInfo(`Retrying (attempt ${oe+1}/${B})`),f.update({[X]:oe+1,[`${g}_raw`]:k.raw});continue}throw P.nodeFailed(g,k.error,{duration:M}),new Error(`Node '${g}' failed after ${oe} attempts: ${k.error}`)}f.update({[g]:k.output});let Y=this._summarizeNodeOutput(g,k.output);P.nodeComplete(g,{duration:M,details:Y});let D=this.edges.get(g);if(D)if(D.conditional){let B=D.routes(f.getAll());P.route(g,B),me(B,g,!1)}else if(Array.isArray(D))for(let B=D.length-1;B>=0;B--)me(D[B],g,!0);else me(D,g,!0)}catch(O){throw P.isInsideNode&&P.nodeFailed(g,O.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",g),O}}P.graphComplete();let y={success:!0,state:f.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete(y),y}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(y){console.warn(`[workflow] agent.cleanup() failed: ${y.message}`)}}}};export{vt as WorkflowGraph,Nn as clearInheritedSessionEnvForFreshRun,Bn as generateWorkflowSessionId,Pn as readPinnedSessionPathFromEnv,Cn as resolveWorkflowSession,xn as shouldTrustInheritedSessionEnv,Rn as syncProcessEnvToSession};
|
|
@@ -50,6 +50,74 @@ export declare class SubgraphFallback extends Error {
|
|
|
50
50
|
reason?: any;
|
|
51
51
|
constructor(reason: any, detail: any);
|
|
52
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* The error a sync sub-graph dispatch throws when it outlives its budget.
|
|
55
|
+
*
|
|
56
|
+
* ONE shape for BOTH dispatch paths. The HTTP path stops POLLING at the
|
|
57
|
+
* deadline (the child keeps running in its own task); the in-process path
|
|
58
|
+
* ABORTS the child (it is this process). What the PARENT sees — the message,
|
|
59
|
+
* `.code`, `.subgraphJobId`, `.subgraphStatus` — must be identical either
|
|
60
|
+
* way, or a `Promise.allSettled` fleet that classifies its rejections (every
|
|
61
|
+
* board-runner lane does) behaves differently depending on a routing decision
|
|
62
|
+
* it never made. Two places that must agree ⇒ one constructor.
|
|
63
|
+
*/
|
|
64
|
+
export declare function subgraphTimeoutError(workflowName: any, jobId: any, timeoutMs: any, lastStatus?: string): any;
|
|
65
|
+
/**
|
|
66
|
+
* How long an IN-PROCESS child may run, in ms — or `null` for "no deadline".
|
|
67
|
+
*
|
|
68
|
+
* Two inputs, and the SMALLER wins:
|
|
69
|
+
*
|
|
70
|
+
* 1. `timeoutMs` — the budget the dispatch DECLARED. On the HTTP path this
|
|
71
|
+
* has always been honoured (it bounds the poll loop). In-process it was
|
|
72
|
+
* dropped on the floor: `dispatchSubgraph` forwarded input/conversationId/
|
|
73
|
+
* signal/parentAgent and nothing else, so `childGraph.run()` ran with no
|
|
74
|
+
* deadline of its own and a wedged child burned the PARENT's whole
|
|
75
|
+
* container budget. That is the defect this function closes — a declared
|
|
76
|
+
* knob that the engine parsed and did not honour.
|
|
77
|
+
*
|
|
78
|
+
* 2. The parent's REMAINING wall clock. `MAX_WORKFLOW_DURATION_MS` is
|
|
79
|
+
* injected into every run container by workflow-executor.js and is the
|
|
80
|
+
* in-container watchdog's own number (it `process.exit(124)`s at it), so
|
|
81
|
+
* it is the truth about when this container dies. `process.uptime()` is a
|
|
82
|
+
* LOWER bound on the real run age (container start + image pull happen
|
|
83
|
+
* before node does), which makes `remaining` an UPPER bound — erring, as
|
|
84
|
+
* it must, toward "the child gets slightly less than it asked for".
|
|
85
|
+
* Same convention as frontend-specialist's `runtimeBudget()`.
|
|
86
|
+
*
|
|
87
|
+
* Why clamp at all: a child that asks for 40 minutes when 5 remain cannot get
|
|
88
|
+
* 40. Without the clamp the watchdog SIGKILLs the whole container and the
|
|
89
|
+
* child's execution row is left `running` until a reaper finds it. With it,
|
|
90
|
+
* the child aborts, `finalize` books it `timeout`, and the parent's own
|
|
91
|
+
* remaining nodes at least get to observe that.
|
|
92
|
+
*
|
|
93
|
+
* `null` (no cap declared AND no budget injected — a local `zibby test`, an
|
|
94
|
+
* older platform) means NO deadline: this function exists to honour a declared
|
|
95
|
+
* bound, never to invent one where nobody declared any.
|
|
96
|
+
*
|
|
97
|
+
* @param {number} [timeoutMs] the dispatch's declared budget, ms.
|
|
98
|
+
* @param {object} [env] defaults to process.env.
|
|
99
|
+
* @param {number} [uptimeSeconds] defaults to process.uptime().
|
|
100
|
+
* @returns {number|null} ms until the child must be aborted, or null.
|
|
101
|
+
*/
|
|
102
|
+
export declare function resolveChildTimeoutMs(timeoutMs?: any, env?: any, uptimeSeconds?: number): number;
|
|
103
|
+
/**
|
|
104
|
+
* Derive the signal the child actually runs under: the parent's abort
|
|
105
|
+
* (cancel from the UI, parent failure) OR our own deadline, whichever
|
|
106
|
+
* fires first.
|
|
107
|
+
*
|
|
108
|
+
* Hand-rolled rather than `AbortSignal.any()` because this package's
|
|
109
|
+
* `engines` is `>=18` and `AbortSignal.any` landed in 20.3 — a child that
|
|
110
|
+
* silently lost its parent-cancel wiring on an older runtime would be a
|
|
111
|
+
* worse bug than the one we're fixing.
|
|
112
|
+
*
|
|
113
|
+
* `timedOut()` is how the caller tells the two apart AFTER the run settles:
|
|
114
|
+
* parent-abort ⇒ `canceled`, our deadline ⇒ `timeout`.
|
|
115
|
+
*/
|
|
116
|
+
export declare function withChildDeadline(parentSignal: any, timeoutMs: any): {
|
|
117
|
+
signal: any;
|
|
118
|
+
timedOut: () => boolean;
|
|
119
|
+
dispose: () => void;
|
|
120
|
+
};
|
|
53
121
|
/**
|
|
54
122
|
* Run `workflowName` in-process inside the parent's Fargate task.
|
|
55
123
|
*
|
|
@@ -68,6 +136,13 @@ export declare class SubgraphFallback extends Error {
|
|
|
68
136
|
* The agent shell from the parent's run. Passed verbatim into the
|
|
69
137
|
* child's `graph.run(agent, ...)` so the child sees the same agent
|
|
70
138
|
* strategy + onComplete hooks; child workflows can override per-node.
|
|
139
|
+
* @param {number} [options.timeoutMs]
|
|
140
|
+
* The DECLARED budget for this child, in ms — the same knob the HTTP
|
|
141
|
+
* path uses to bound its poll loop. Here it bounds the child's own
|
|
142
|
+
* run: at the deadline the child is ABORTED and finalized `timeout`,
|
|
143
|
+
* and the dispatch rejects with `subgraphTimeoutError`. Clamped down to
|
|
144
|
+
* the parent's remaining wall clock (resolveChildTimeoutMs). Omit for
|
|
145
|
+
* "no deadline of its own" — `dispatchSubgraph` always supplies one.
|
|
71
146
|
* @param {string | function} [options.output]
|
|
72
147
|
* Same shape as the HTTP path's `output:`. We don't resolve it here
|
|
73
148
|
* — the caller (`sub-graph-executor.js`) does that on the finalState
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as Y,existsSync as b,statSync as G,readdirSync as C,rmSync as W}from"node:fs";import{spawn as U}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as Z}from"node:url";import{AsyncLocalStorage as K}from"node:async_hooks";var O=()=>{},q={debug:O,info:O,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},T={impl:q};var m={debug:(...e)=>T.impl.debug?.(...e),info:(...e)=>T.impl.info?.(...e),warn:(...e)=>T.impl.warn?.(...e),error:(...e)=>T.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var B=new V;function _(){let e=B.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 R(e,r){let n=B.getStore()||_(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return B.run(t,r)}var A=new Map,$=new Map,P=new Map;function j(e,r,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof r!="function")throw new Error("subgraph-registry.register: factory must be a function");A.set(e,r),$.set(e,"ready"),P.set(e,{...n,cachedAt:Date.now()})}function D(e,r){$.set(e,"failed"),P.set(e,{error:r?.message||String(r),failedAt:Date.now()}),A.delete(e)}function M(e){return $.get(e)==="ready"?A.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Q(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(r,n){super(`in-process sub-graph fallback: ${r}${n?` (${n})`:""}`),this.fallback=!0,this.reason=r,this.detail=n||null,this.name="SubgraphFallback"}},z=new K,L=Promise.resolve();async function ee(e,r){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(n.length===0)return r();let t=z.getStore()===!0,s=null;if(!t){let a=L;L=new Promise(i=>{s=i}),await a}let o=new Map;try{for(let[a,i]of n)o.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return m.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${t?" (nested)":""}`),await z.run(!0,r)}finally{for(let[a,i]of o)i===void 0?delete process.env[a]:process.env[a]=i;s&&s()}}function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),r=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||r,t=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!n||!t||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:t,authToken:s}}async function ne({apiBase:e,authToken:r,body:n}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)})}catch(o){throw new l("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await t.json()}catch{}if(!t.ok){if(t.status===404){let o=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(t.status===429){let o=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(t.status===400&&s?.validationErrors){let o=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=s.validationErrors,o.missing=s.missing,o}throw new l("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function E({apiBase:e,authToken:r,payload:n}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)});t.ok||m.warn(`[in-process subgraph] finalize returned ${t.status} for ${n.childExecutionId}`)}catch(t){m.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function re(e,r){let n=w(r,".ready"),t=w(r,"graph.mjs");if(b(n)&&b(t))return;Y(r,{recursive:!0});let s=w(r,".lock"),o=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),d=a(s,"wx");i(d),o=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!o){let a=Date.now()+3e4;for(;Date.now()<a;){if(b(n)&&b(t))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 g=U("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=U("tar",["-xzf","-","-C",r],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(S.stdin);let f,I,h=()=>{if(f!==void 0&&I!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(I!==0)return p(new Error(`tar exited ${I}`));d()}};g.on("close",v=>{f=v,h()}),S.on("close",v=>{I=v,h()}),g.on("error",p),S.on("error",p)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new l("bundle-extract-failed",a.message)}}async function oe(e){let r=w(e,"graph.mjs");if(!b(r))throw new l("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Z(r).href)}catch(s){throw new l("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let t=n.default||Object.values(n).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ye(e,r={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=_(),t;try{t=te()}catch(c){throw c}m.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let s=await ne({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:r.input||{},...r.conversationId?{conversationId:r.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:g,bundleReady:S,nodeConfigs:f}=s,I=Q();if(a&&a!==I)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,discard:!0}}),new l("runtime-mismatch",`${I} vs ${a}`);if(!S||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let h=M(e);if(!h){let c=w(x,`${g}@${p||"0"}`);try{await re(i,c);try{ae()}catch{}}catch(u){throw u.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{h=await oe(c),j(e,h,{workflowUuid:g,version:p,runtimeTag:a,cacheDir:c})}catch(u){throw D(e,u),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new l("import-failed",u.message)}}let v=Date.now(),N=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,F=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,J={...r.input||{},...F?{nodeConfigs:f}:{}},y,k;try{y=await ee(N,async()=>{let u=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return R({executionId:o,parentExecutionId:n.executionId,conversationId:r.conversationId!==void 0?r.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>u.run(r.parentAgent,J,{signal:r.signal}))}),k=y&&typeof y=="object"&&"state"in y?y.state:y}catch(c){throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(y&&typeof y=="object"&&y.stoppedExternally){await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:k,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:k,durationMs:Date.now()-v}}),{finalState:k,executionId:o}}function we(){try{if(!b(x))return{bytes:0,entries:0};let e=C(x),r=0;for(let n of e)try{r+=H(w(x,n))}catch{}return{bytes:r,entries:e.length}}catch{return{bytes:0,entries:0}}}function H(e){let r=0,n=[e];for(;n.length;){let t=n.pop(),s;try{s=G(t)}catch{continue}if(s.isDirectory()){let o;try{o=C(t)}catch{continue}for(let a of o)n.push(w(t,a))}else r+=s.size}return r}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!b(x))return{evicted:0,freedBytes:0};let r=C(x),n=[],t=0;for(let i of r){let d=w(x,i),p;try{p=G(d)}catch{continue}let g=p.isDirectory()?H(d):p.size;t+=g,n.push({name:i,full:d,size:g,mtimeMs:p.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};n.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let i of n){if(t-o<=s)break;if(!b(w(i.full,".lock")))try{W(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){m.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&m.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:t-o}}catch(r){return m.debug(`[sub-graph cache] evict failed: ${r.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,ae as evictCacheIfOver,we as getCacheStats,ye as runInProcessSubgraph};
|
|
1
|
+
import{mkdirSync as Z,existsSync as b,statSync as F,readdirSync as R,rmSync as Q}from"node:fs";import{spawn as N}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as ee}from"node:url";import{AsyncLocalStorage as te}from"node:async_hooks";var P=()=>{},V={debug:P,info:P,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},B={impl:V};var m={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 Y}from"node:async_hooks";var k=new Y;function $(){let e=k.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function M(e,r){let n=k.getStore()||$(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return k.run(t,r)}var O=new Map,C=new Map,U=new Map;function D(e,r,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof r!="function")throw new Error("subgraph-registry.register: factory must be a function");O.set(e,r),C.set(e,"ready"),U.set(e,{...n,cachedAt:Date.now()})}function j(e,r){C.set(e,"failed"),U.set(e,{error:r?.message||String(r),failedAt:Date.now()}),O.delete(e)}function L(e){return C.get(e)==="ready"?O.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ne(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(r,n){super(`in-process sub-graph fallback: ${r}${n?` (${n})`:""}`),this.fallback=!0,this.reason=r,this.detail=n||null,this.name="SubgraphFallback"}};function z(e,r,n,t="timeout"){let o=new Error(`Sub-graph '${e}' (${r}) timed out after ${Math.round(n/1e3)}s (last status: ${t})`);return o.code="SUBGRAPH_TIMEOUT",o.subgraphJobId=r,o.subgraphStatus=t,o}function re(e,r=process.env,n=process.uptime()){let t=Number.isFinite(e)?Number(e):null,o=Number(r&&r.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(n)&&n>0?n*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(t===null&&a===null)return null;let i=t===null?a:a===null?t:Math.min(t,a);return Math.max(1,i)}function oe(e,r){let n=new AbortController,t=!1,o=null,s=()=>{n.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),r!=null&&!n.signal.aborted&&(o=setTimeout(()=>{t=!0,n.abort(new Error("sub-graph deadline exceeded"))},r),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>t,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var G=new te,H=Promise.resolve();async function se(e,r){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(n.length===0)return r();let t=G.getStore()===!0,o=null;if(!t){let a=H;H=new Promise(i=>{o=i}),await a}let s=new Map;try{for(let[a,i]of n)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return m.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${t?" (nested)":""}`),await G.run(!0,r)}finally{for(let[a,i]of s)i===void 0?delete process.env[a]:process.env[a]=i;o&&o()}}function ae(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),r=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||r,t=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!t||!o)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:t,authToken:o}}async function ie({apiBase:e,authToken:r,body:n}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)})}catch(s){throw new l("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await t.json()}catch{}if(!t.ok){if(t.status===404){let s=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(t.status===429){let s=o?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(t.status===400&&o?.validationErrors){let s=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=o.validationErrors,s.missing=o.missing,s}throw new l("begin-status",`begin returned ${t.status}`)}return o?.data||o}async function E({apiBase:e,authToken:r,payload:n}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)});t.ok||m.warn(`[in-process subgraph] finalize returned ${t.status} for ${n.childExecutionId}`)}catch(t){m.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function ce(e,r){let n=w(r,".ready"),t=w(r,"graph.mjs");if(b(n)&&b(t))return;Z(r,{recursive:!0});let o=w(r,".lock"),s=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),d=a(o,"wx");i(d),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(b(n)&&b(t))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 g=N("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),T=N("tar",["-xzf","-","-C",r],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(T.stdin);let f,I,h=()=>{if(f!==void 0&&I!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(I!==0)return p(new Error(`tar exited ${I}`));d()}};g.on("close",v=>{f=v,h()}),T.on("close",v=>{I=v,h()}),g.on("error",p),T.on("error",p)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(o)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new l("bundle-extract-failed",a.message)}}async function ue(e){let r=w(e,"graph.mjs");if(!b(r))throw new l("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(ee(r).href)}catch(o){throw new l("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let t=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ve(e,r={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=$(),t;try{t=ae()}catch(u){throw u}m.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await ie({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:r.input||{},...r.conversationId?{conversationId:r.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:g,bundleReady:T,nodeConfigs:f}=o,I=ne();if(a&&a!==I)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,discard:!0}}),new l("runtime-mismatch",`${I} vs ${a}`);if(!T||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let h=L(e);if(!h){let u=w(x,`${g}@${p||"0"}`);try{await ce(i,u);try{le()}catch{}}catch(c){throw c.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{h=await ue(u),D(e,h,{workflowUuid:g,version:p,runtimeTag:a,cacheDir:u})}catch(c){throw j(e,c),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new l("import-failed",c.message)}}let v=Date.now(),q=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,W=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,X={...r.input||{},...W?{nodeConfigs:f}:{}},S=re(r.timeoutMs),_=oe(r.signal,S),y,A;try{y=await se(q,async()=>{let c=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return M({executionId:s,parentExecutionId:n.executionId,conversationId:r.conversationId!==void 0?r.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(r.parentAgent,X,{signal:_.signal}))}),A=y&&typeof y=="object"&&"state"in y?y.state:y}catch(u){let c=_.timedOut();throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(S/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:u.message,code:u.code||"CHILD_THREW",stack:u.stack},durationMs:Date.now()-v}}),c?z(e,s,S):u}finally{_.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let u=_.timedOut();if(await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:u?"timeout":"canceled",finalState:A,durationMs:Date.now()-v}}),u)throw z(e,s,S);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=s,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:s,status:"completed",finalState:A,durationMs:Date.now()-v}}),{finalState:A,executionId:s}}function Ee(){try{if(!b(x))return{bytes:0,entries:0};let e=R(x),r=0;for(let n of e)try{r+=J(w(x,n))}catch{}return{bytes:r,entries:e.length}}catch{return{bytes:0,entries:0}}}function J(e){let r=0,n=[e];for(;n.length;){let t=n.pop(),o;try{o=F(t)}catch{continue}if(o.isDirectory()){let s;try{s=R(t)}catch{continue}for(let a of s)n.push(w(t,a))}else r+=o.size}return r}function le({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!b(x))return{evicted:0,freedBytes:0};let r=R(x),n=[],t=0;for(let i of r){let d=w(x,i),p;try{p=F(d)}catch{continue}let g=p.isDirectory()?J(d):p.size;t+=g,n.push({name:i,full:d,size:g,mtimeMs:p.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};n.sort((i,d)=>i.mtimeMs-d.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let i of n){if(t-s<=o)break;if(!b(w(i.full,".lock")))try{Q(i.full,{recursive:!0,force:!0}),s+=i.size,a+=1}catch(d){m.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&m.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:t-s}}catch(r){return m.debug(`[sub-graph cache] evict failed: ${r.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,le as evictCacheIfOver,Ee as getCacheStats,re as resolveChildTimeoutMs,ve as runInProcessSubgraph,z as subgraphTimeoutError,oe as withChildDeadline};
|