@zibby/agent-workflow 2.0.2 → 2.0.4
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/code-generator.js +15 -15
- package/dist/graph-compiler.js +18 -18
- package/dist/graph.js +15 -15
- package/dist/in-process-subgraph.d.ts +1 -1
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +33 -33
- package/dist/logger.d.ts +26 -0
- package/dist/logger.js +1 -1
- package/dist/node-registry.js +9 -9
- package/dist/node.d.ts +1 -11
- package/dist/node.js +16 -16
- package/dist/strategy-registry.js +8 -8
- package/dist/sub-graph-executor.js +1 -1
- package/dist/tool-resolver.js +1 -1
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var Lt=Object.defineProperty;var
|
|
1
|
+
var Lt=Object.defineProperty;var oe=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Ge=(r,e)=>{for(var t in e)Lt(r,t,{get:e[t],enumerable:!0})};var He,Wt,Se,ce,$,Q=oe(()=>{He=()=>{},Wt={debug:He,info:He,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},Se=Symbol.for("@zibby/agent-workflow.logger");globalThis[Se]||(globalThis[Se]={impl:Wt});ce=globalThis[Se],$={debug:(...r)=>ce.impl.debug?.(...r),info:(...r)=>ce.impl.info?.(...r),warn:(...r)=>ce.impl.warn?.(...r),error:(...r)=>ce.impl.error?.(...r)}});var tt=oe(()=>{});var nt={};Ge(nt,{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(W.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).`)}}W.set(s,Object.freeze({...r})),t===void 0?te.delete(s):te.set(s,t)}function $e(r){return W.get(r)||null}function Jt(r){return W.has(r)}function zt(r){return te.get(r)||null}function Yt(){return new Map(W)}function Zt(){return Array.from(W.keys())}function qt(){W.clear(),te.clear()}var Ie,Ee,W,te,ve=oe(()=>{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);W=globalThis[Ie],te=globalThis[Ee]});var Te={};Ge(Te,{getAgentStrategy:()=>ot,invokeAgent:()=>Xt,listStrategies:()=>Vt,registerStrategy:()=>Kt,resolveInvocationExtras:()=>st,resolveInvocationModel:()=>rt});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 rt({config:r={},options:e={},strategyName:t,envModel:n,nodeConfigModel:s}={}){let o=r.models||{},i=typeof s=="string"&&s.trim()?s.trim():null,a=e.nodeName&&o[e.nodeName]||null,u=o.default||null,d=r.agent?.[t]?.model||null,I=(typeof n=="string"?n.trim():"")||null;return i||a||u||d||e.model||I||null}function st({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 ot(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=ot(s),i=n.config||t.config||{},a=n._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===o.name?a.model:null,I=rt({config:i,options:t,strategyName:o.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:I,...st({options:t,stateView:n,context:e}),config:i},c=r,p=l.skills||[];if(p.length>0&&!t.skipPromptFragments){let T=t.connectedIntegrations;if(!T){let h=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof h=="string"&&h.trim()!==""){T={};for(let g of h.split(",").map(m=>m.trim()).filter(Boolean))T[g]=!0}}let v=h=>{let g=h&&h.requiresIntegration;return!g||!T?!0:(Array.isArray(g)?g:[g]).some(E=>T[E]===!0)},f=o.name==="assistant",_=h=>h?.inProcessOnly!==!0||f,S=p.map(h=>{let g=$e(h);if(!v(g)||!_(g))return null;let m=g?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);S.length>0&&(c+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${S.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${E.join(", ")}`)}return
|
|
5
|
+
`)}`)}let w=n._currentNodeConfig?.stores;if(Array.isArray(w)&&w.length>0&&typeof w[0]=="object"){let T=w.length<=8,v=w.map(f=>{let _=f?.id??f?.storeId??"",S=(f?.name??"").toString().trim()||_,h=f?.type?` \xB7 ${f.type}`:"",g=(f?.description||"").toString().replace(/\s+/g," ").trim(),m=`- ${S} \xB7 ${g||"(no description)"}${h} (id: ${_})`;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&&(m+=`
|
|
6
|
+
fields: ${E.join(", ")}`)}return m});c+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${v.join(`
|
|
10
|
-
`)}`}let A=n._currentNodeConfig?.extraPromptInstructions?.trim();return A&&(
|
|
10
|
+
`)}`}let A=n._currentNodeConfig?.extraPromptInstructions?.trim();return A&&(c+=`
|
|
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
16
|
${A}
|
|
17
|
-
`),$.debug(`[workflow] prompt length: ${
|
|
17
|
+
`),$.debug(`[workflow] prompt length: ${c.length} chars`),o.invoke(c,l)}var Ae,F,ke=oe(()=>{tt();Q();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Ut=new Set(["__proto__","constructor","prototype"]);function ye(r){if(Ut.has(r))throw new Error(`Invalid state key: "${r}"`)}var ie=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){ye(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)ye(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){ye(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 ae=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}};Q();import{writeFileSync as Oe,readFileSync as
|
|
19
|
+
`)}`);return e}};Q();import{writeFileSync as Oe,readFileSync as it,existsSync as at,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"),Je=x.gray("\u2514"),we=x.green("\u25C6"),ze=x.hex("#c084fc")("\u25C6"),Ye=x.hex("#2dd4bf")("\u25C6"),_e=x.red("\u25C6"),Ze=`${ee} `,qe=2;function Ke(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ve(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+=Ze,e.col=qe,e.lineStart=!1),u===`
|
|
20
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
|
-
${
|
|
21
|
+
${Ze}`,e.col=qe))}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=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(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
24
|
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Ft}${JSON.stringify(e)}
|
|
@@ -26,17 +26,17 @@ ${Ye}`,e.col=Ze))}return r(i,n,s)}}var be=class{constructor(){this._currentNode=
|
|
|
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
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(
|
|
30
|
-
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ze,e):process.stdout.write.bind(process.stdout)(`${ee} ${ze} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Ye,t):process.stdout.write.bind(process.stdout)(`${ee} ${Ye} ${t}
|
|
31
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(` ${
|
|
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(` ${Ke(n)}`):"";this._rawWrite(`${Je} ${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(` ${Ke(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${Je} ${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 le=".zibby/output",Xe="sessions",Z=".session-info.json",Qe=".zibby-stop";var Fn=Object.freeze(["codebase-memory","code-scan","artifact"]),et=["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 ae(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=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){$.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let l=null;for(let c=0;c<=this.retries;c++){try{let p=await this.customExecute(e);if(typeof p=="object"&&p!==null&&p.success===!1)l={success:!1,error:p.error||"Node execution failed",raw:p.raw||null};else return this.isZodSchema?($.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(p),raw:null}):{success:!0,output:p,raw:null}}catch(p){$.error(`[workflow] node '${this.name}' failed: ${p.message}`),p.name==="ZodError"&&$.error(`Schema errors: ${JSON.stringify(p.issues||p.errors,null,2)}`),l={success:!1,error:p.message,raw:null}}c<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return l}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
|
-
${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(`
|
|
34
|
+
${o}`);let a=n(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=xe(d,Z);if(at(l)){let p=JSON.parse(it(l,"utf-8"));p.currentNode=this.name,Oe(l,JSON.stringify(p,null,2),"utf-8")}let c=xe(d,"..",Z);if(at(c))try{let p=JSON.parse(it(c,"utf-8"));p.currentNode=this.name,Oe(c,JSON.stringify(p,null,2),"utf-8")}catch{}}}catch(l){$.debug(`[workflow] could not update session info: ${l.message}`)}let I=null;for(let l=0;l<=this.retries;l++)try{$.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=n().config||{},p=c.agents||{},w=this.config.agent??p[this.name]??null,A={state:n()};w&&(A.preferredAgent=w);let T={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},v=e?._coreInvokeAgent;v||(v=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await v(o,A,T),_,S;if(typeof f=="string"?(_=f,S=null):f.structured?(_=f.raw||JSON.stringify(f.structured,null,2),S=f.structured):(_=f.raw||JSON.stringify(f,null,2),S=f.extracted||null),d)try{let h=xe(d,this.name,"raw_stream_output.txt");Qt(en(h),{recursive:!0}),Oe(h,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(h){$.debug(`[workflow] could not save raw output: ${h.message}`)}if(this.isZodSchema&&S){$.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let h=S;if(typeof this.onComplete=="function")try{h=await this.onComplete(n(),S)}catch(g){$.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:h,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:_}),raw:_}}catch(h){throw new Error(`onComplete failed: ${h.message}`,{cause:h})}if(this.parser){let h=this.parser.parse(_);return $.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(h,null,2)}`),P.step("Output parsed"),{success:!0,output:h,raw:_}}return{success:!0,output:_,raw:_}}catch(c){I=c,l<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:I.message,raw:null}}};Q();Q();import{mkdirSync as rn,existsSync as J,statSync as yt,readdirSync as St,rmSync as sn}from"node:fs";import{spawn as ht}from"node:child_process";import{join as U}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 ct(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 lt(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,ut=new Map;function dt(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"),ut.set(r,{...t,cachedAt:Date.now()})}function pt(r,e){Ne.set(r,"failed"),ut.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function ft(r){return Ne.get(r)==="ready"?Pe.get(r):null}var ue=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",s=null){let o=new Error(`Sub-graph '${r}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${n})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return o.code="SUBGRAPH_TIMEOUT",o.subgraphJobId=e,o.subgraphStatus=n,s&&(o.subgraphTransportError=s),o}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 gt=new an,mt=Promise.resolve();async function dn(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=gt.getStore()===!0,s=null;if(!n){let i=mt;mt=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 gt.run(!0,e)}finally{for(let[i,a]of o)a===void 0?delete process.env[i]:process.env[i]=a;s&&s()}}function pn(){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=U(e,".ready"),n=U(e,"graph.mjs");if(J(t)&&J(n))return;rn(e,{recursive:!0});let s=U(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,d)=>{let I=ht("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),l=ht("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});I.stdout.pipe(l.stdin);let c,p,w=()=>{if(c!==void 0&&p!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(p!==0)return d(new Error(`tar exited ${p}`));u()}};I.on("close",A=>{c=A,w()}),l.on("close",A=>{p=A,w()}),I.on("error",d),l.on("error",d)});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=U(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 wt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=pn()}catch(m){throw m}$.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:d,workflowUuid:I,bundleReady:l,nodeConfigs:c}=s,p=cn();if(i&&i!==p)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,discard:!0}}),new N("runtime-mismatch",`${p} vs ${i}`);if(!l||!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 w=ft(r);if(!w){let m=U(ue,`${I}@${d||"0"}`);try{await hn(a,m);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{w=await gn(m),dt(r,w,{workflowUuid:I,version:d,runtimeTag:i,cacheDir:m})}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=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...v?{nodeConfigs:c}:{}},_=ln(e.timeoutMs),S=un(e.signal,_),h,g;try{h=await dn(T,async()=>{let E=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return ct({executionId:o,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,f,{signal:S.signal}))}),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){let E=S.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(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-A}}),E?de(r,o,_):m}finally{S.dispose()}if(h&&typeof h=="object"&&h.stoppedExternally){let m=S.timedOut();if(await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:o,status:m?"timeout":"canceled",finalState:g,durationMs:Date.now()-A}}),m)throw de(r,o,_);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:g,durationMs:Date.now()-A}}),{finalState:g,executionId:o}}function mn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=yt(n)}catch{continue}if(s.isDirectory()){let o;try{o=St(n)}catch{continue}for(let i of o)t.push(U(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(ue))return{evicted:0,freedBytes:0};let e=St(ue),t=[],n=0;for(let a of e){let u=U(ue,a),d;try{d=yt(u)}catch{continue}let I=d.isDirectory()?mn(u):d.size;n+=I,t.push({name:a,full:u,size:I,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),o=0,i=0;for(let a of t){if(n-o<=s)break;if(!J(U(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 _t(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 bt(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:S}=await wt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),h=_t(S,e.output);return $.info(`[sub-graph] '${r}' completed in-process`),h}catch(S){if(S instanceof N||S?.fallback)$.info(`[sub-graph] in-process fallback for '${r}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let o=bn(),i=In(),a=En(),u=$n(),d=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,I={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 l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(I)});if(!l.ok){let S=null,h="";try{S=await l.json(),h=S?.error||S?.message||JSON.stringify(S)}catch{h=await l.text().catch(()=>"")}if(l.status===429){let m=S?.quotaInfo||{},E=new Error(`Sub-graph '${r}' blocked by execution quota (${m.used??"?"}/${m.limit??"?"} on plan ${m.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw E.code="SUBGRAPH_QUOTA_EXCEEDED",E.status=429,E.subgraph=r,E.quotaInfo=m,E}if(l.status===400){let m=new Error(`Sub-graph '${r}' rejected input: ${h}`);throw m.code="SUBGRAPH_INVALID_INPUT",m.status=400,m.subgraph=r,m.validationErrors=S?.validationErrors||null,m.missing=S?.missing||null,m}let g=new Error(`Sub-graph '${r}' trigger rejected (${l.status}): ${h}`);throw g.code="SUBGRAPH_TRIGGER_FAILED",g.status=l.status,g.subgraph=r,g}let c=await l.json(),p=c?.data?.jobId||c?.jobId;if(!p)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:r};let w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Sn,A=`${o}/executions/${encodeURIComponent(p)}`,T=Date.now()+s,v="accepted",f=0,_=null;for(;Date.now()<T;){await new Promise(m=>setTimeout(m,w)),f+=1;let S;try{S=await fetch(A,{headers:{Authorization:`Bearer ${a}`}})}catch(m){_=m?.message||String(m),$.warn(`[sub-graph] status poll for ${p} could not reach the API (${_}), will retry`);continue}if(!S.ok){if(S.status>=500){$.warn(`[sub-graph] status poll for ${p} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${S.status}`)}let h;try{h=await S.json()}catch(m){_=m?.message||String(m),$.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${_}), will retry`);continue}let g=h?.data||h?.execution||h;if(v=g?.status||v,_n.has(v)){if(v!=="completed"){let K=new Error(`Sub-graph '${r}' (${p}) ended in status '${v}'`);throw K.subgraphJobId=p,K.subgraphStatus=v,K}let m=g?.finalState||g?.state||{},E=_t(m,e.output);return $.info(`[sub-graph] '${r}' (${p}) completed after ${f} polls`),E}}throw de(r,p,s,v,_)}import{existsSync as It,readFileSync as vn}from"node:fs";import{join as Re,dirname as Et}from"node:path";var pe=class{static async loadContext(e,t,n={}){let s={},o=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Et(Re(t,e));for(let u of o){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let I=u.replace(/\.[^.]+$/,"").toLowerCase();s[I]=d}}}let i=n.discovery||{};for(let[a,u]of Object.entries(i))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=[],o=t;for(;o.startsWith(n);){let i=Re(o,e);if(It(i))try{s.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=Et(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(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
|
|
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 Tt,existsSync as Be,writeFileSync as $t,unlinkSync as An}from"node:fs";import{join as z,resolve as kt}from"node:path";import{config as Tn}from"dotenv";import{zodToJsonSchema as vt}from"zod-to-json-schema";import{z as fe}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 I=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
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(
|
|
41
|
+
${I}`)}}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 kt(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=et.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 d=kt(String(process.env.ZIBBY_SESSION_PATH));d&&(s=d,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),o==null&&(o=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,i="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,i="config.sessionId"):(a=Bn(e),i="generated")}o=o??Date.now();let I=e.paths?.output||le;s=z(r,I,Xe,a)}let u=!Be(s);return u&&Tt(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 At=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 d=>{let I=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof i.input=="function"?l=i.input(I):i.input&&typeof i.input=="object"?l=i.input:l={},bt(i.workflow,{input:l,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(I):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:I?._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,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],d=i;i=()=>u(t,d,s,o)}return i()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let p=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:p,data:{nodeType:p,label:l}});let w={};c._isCustomCode&&typeof c.execute=="function"&&(w.customCode=c.execute.toString());let A=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;A&&(w.description=A);let T=this.nodePrompts.get(l);if(T)w.prompt=T;else if(typeof c.prompt=="function")try{let g=c.prompt({});typeof g=="string"&&g.trim()&&(w.prompt=g,w.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(w.executeCode=c.customExecute.toString());let v=c?.config?.dispatchesWorkflow;if(typeof v=="string"&&v.trim())w.dispatchesWorkflow=v.trim();else if(Array.isArray(v)){let g=[...new Set(v.filter(m=>typeof m=="string").map(m=>m.trim()).filter(Boolean))];g.length&&(w.dispatchesWorkflow=g)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(w.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let g=null;if(typeof fe?.toJSONSchema=="function")try{g=fe.toJSONSchema(c.outputSchema)}catch{}if(!g)try{g=vt(c.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:c.outputSchema}}else w.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[l];f?.toolIds&&(w.tools=f.toolIds);let _=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;_&&_.length>0&&(w.skills=[..._]);let S=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;S&&S.length>0&&(w.plugins=S.map(g=>g&&typeof g=="object"?{...g}:g));let h=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;h&&h.length>0&&(w.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),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 p of c)n.push({source:l,target:p});else if(c.conditional){let p=this.conditionalCodeMap.get(l)||c.routes.toString(),w=this._inferConditionalTargets(c.routes,c.labels),A=c.labels||{},T=this.nodes.get(l),v=T?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!T,f=l;if(!v){let _=`${l}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),n.push({source:l,target:_}),f=_}for(let _ of w){let S={source:f,target:_,data:{conditionalCode:p}};A[_]&&(S.label=A[_]),n.push(S)}}let s=l=>{if(!l)return null;if(typeof fe?.toJSONSchema=="function")try{return fe.toJSONSchema(l)}catch{}try{return vt(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 o=0;for(let l of n)if(l.target==="END"){o+=1;let c=`END__${o}`;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)){o+=1;let c=`END__${o}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:l,target:c})}let i=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),d=s(this.inputSchema),I=s(this.contextSchema);return{nodes:i,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:I}}_topoOrderNodes(e,t){let n=new Map(e.map((l,c)=>[l.id,c])),s=new Map(e.map(l=>[l.id,l])),o=new Map(e.map(l=>[l.id,0])),i=new Map(e.map(l=>[l.id,[]]));for(let l of t)i.has(l.source)&&o.has(l.target)&&(i.get(l.source).push(l.target),o.set(l.target,o.get(l.target)+1));let a=new Set,u=new Set(n.keys()),d=[...u].filter(l=>o.get(l)===0),I=[];for(;I.length<e.length;){let l;if(d.length>0){if(d.sort((c,p)=>n.get(c)-n.get(p)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,p)=>n.get(c)-n.get(p))[0];a.add(l),u.delete(l),I.push(s.get(l));for(let c of i.get(l)||[])o.set(c,o.get(c)-1),o.get(c)<=0&&!a.has(c)&&d.push(c)}return I}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,o=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=o.exec(n))!==null;){let d=i[2]!==void 0?i[2]:i[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,I;for(;(I=d.exec(n))!==null;)u.add(I[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(d=>d?.passed===!0).length,u=o.some(d=>d?.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(b){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw y.cause=b,y.code=b?.code||"NORMALIZE_INPUT_FAILED",y}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 b=z(i,".zibby.config.js");Be(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let b=a?.agent;b?.provider?u=b.provider:b?.gemini?u="gemini":b?.claude?u="claude":b?.cursor?u="cursor":b?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},I=this._runtimeSchema();if(I){let b=I.safeParse(t);if(!b.success){let y=b.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${y.join(", ")}`)}P.step("State validated against schema")}let l=Pn(),c=t.sessionPath||l;c||Nn();let{sessionPath:p,sessionTimestamp:w,sessionId:A}=Cn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${A}`);let T=await pe.loadContext(t.specPath||"",i,d);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 ie({...t,config:a,agentType:u,outputPath:v,sessionPath:p,sessionTimestamp:w,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ve(),nt)),h=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(h).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),m=b=>{for(let y of g)if(y.id===b)return y;return S(b)},E=new Set;for(let[,b]of this.nodes)for(let y of b.config?.skills||[])E.add(y);for(let b of E){let y=m(b);if(typeof y?.middleware=="function")try{let B=await y.middleware();typeof B=="function"&&_.set(b,B)}catch{}}let{backEdges:K,joinDegree:Ot}=this._analyzeFlow(),he=new Map,V=[],ge=(b,y,B)=>{if(!b||b==="END")return;let j=Ot.get(b)||0;if(B&&j>1&&!K.has(`${y}->${b}`)){let X=(he.get(b)||0)+1;if(X<j){he.set(b,X);return}he.set(b,0)}V.includes(b)||V.push(b)};this.entryPoint&&V.push(this.entryPoint);let re=[],Ce=a?.recursionLimit??100,xt=0;try{for(;V.length>0;){let y=V.pop();if(!y||y==="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 B=z(p,Qe);if(Be(B)){try{An(B)}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(y);if(!j)throw new Error(`Node '${y}' not found in graph`);let X=JSON.stringify({sessionPath:p,sessionTimestamp:w,currentNode:y,createdAt:new Date().toISOString(),config:f.get("config")}),Pt=z(p,Z);$t(Pt,X,"utf-8");let Me=f.get("config")?.paths?.output||le,Nt=z(i,Me,Z);Tt(z(i,Me),{recursive:!0});try{$t(Nt,X,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:i,sessionPath:p,sessionId:A,outputBase:f.get("config")?.paths?.output||le,currentNode:y})}catch{}let Rt=(this.resolvedToolsMap||{})[y]||null;f.set("_currentNodeTools",Rt);let Bt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Bt[y]||{}),P.nodeStart(y);let De=Date.now(),se=this.nodePrompts.get(y);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=O.invokeAgent}let Ct=this._invokeAgent,me={},Mt=j.config?.skills||[];for(let O of Mt){let R=m(O);if(typeof R?.invokeAgentOptions=="function")try{let k=R.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:y});k&&typeof k=="object"&&(me={...me,...k})}catch(k){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${k.message}`)}}let Le=async(O,R,k={})=>{let C=Ct(O,R,{...me,...k,signal:s.signal});return C.catch(()=>{}),s.signal.aborted?C:Promise.race([C,new Promise((Y,D)=>{let M=()=>{setTimeout(()=>{let Fe=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${o}ms`);Fe.name="AbortError",D(Fe)},o)};s.signal.addEventListener("abort",M,{once:!0})})])},jt=async(O={},R={})=>{let k=R.prompt||"";if(se){let C=this._compiledPrompts.get(y);C||(C=kn.compile(se,{noEscape:!0}),this._compiledPrompts.set(y,C));try{k=C(O)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${y}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!k)throw new Error(`No prompt template configured for node '${y}' 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,nodeName:y})},Ue=f.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let O of Dt)Object.prototype.hasOwnProperty.call(Ue,O)&&console.warn(`[workflow] node "${y}": state key "${O}" is shadowed by the engine context prop; read it via context.state.get('${O}')`);let We={...Ue,state:f,invokeAgent:jt,_coreInvokeAgent:Le,agent:e,nodeId:y,promptTemplate:se,getPromptTemplate:()=>se};try{let O=(j.config?.skills||[]).map(M=>_.get(M)).filter(Boolean),R=[...this.middleware,...O],k;k=await lt(e,s.signal,async()=>R.length>0?this._composeMiddleware(R,y,async()=>j.execute(We,f),f.getAll(),f):j.execute(We,f));let C=Date.now()-De;if(re.push({node:y,success:k.success,duration:C,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:y,error:k.error});let M=(j.config?.retries||0)+1;throw P.nodeFailed(y,k.error,{duration:C}),new Error(`Node '${y}' failed after ${M} attempt(s): ${k.error}`)}f.update({[y]:k.output});let Y=this._summarizeNodeOutput(y,k.output);P.nodeComplete(y,{duration:C,details:Y});let D=this.edges.get(y);if(D)if(D.conditional){let M=D.routes(f.getAll());P.route(y,M),ge(M,y,!1)}else if(Array.isArray(D))for(let M=D.length-1;M>=0;M--)ge(D[M],y,!0);else ge(D,y,!0)}catch(O){throw P.isInsideNode&&P.nodeFailed(y,O.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",y),O}}P.graphComplete();let b={success:!0,state:f.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};export{At as WorkflowGraph,Nn as clearInheritedSessionEnvForFreshRun,Bn as generateWorkflowSessionId,Pn as readPinnedSessionPathFromEnv,Cn as resolveWorkflowSession,xn as shouldTrustInheritedSessionEnv,Rn as syncProcessEnvToSession};
|
|
@@ -61,7 +61,7 @@ export declare class SubgraphFallback extends Error {
|
|
|
61
61
|
* board-runner lane does) behaves differently depending on a routing decision
|
|
62
62
|
* it never made. Two places that must agree ⇒ one constructor.
|
|
63
63
|
*/
|
|
64
|
-
export declare function subgraphTimeoutError(workflowName: any, jobId: any, timeoutMs: any, lastStatus?: string): any;
|
|
64
|
+
export declare function subgraphTimeoutError(workflowName: any, jobId: any, timeoutMs: any, lastStatus?: string, lastTransportError?: string | null): any;
|
|
65
65
|
/**
|
|
66
66
|
* How long an IN-PROCESS child may run, in ms — or `null` for "no deadline".
|
|
67
67
|
*
|
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
import{mkdirSync as Q,existsSync as m,statSync as J,readdirSync as P,rmSync as ee}from"node:fs";import{spawn as N}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as te}from"node:url";import{AsyncLocalStorage as ne}from"node:async_hooks";var M=()=>{},K={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k=Symbol.for("@zibby/agent-workflow.logger");globalThis[k]||(globalThis[k]={impl:K});var B=globalThis[k];var b={debug:(...e)=>B.impl.debug?.(...e),info:(...e)=>B.impl.info?.(...e),warn:(...e)=>B.impl.warn?.(...e),error:(...e)=>B.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var $=new V;function O(){let e=$.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function U(e,r){let n=$.getStore()||O(),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 $.run(t,r)}var C=new Map,R=new Map,D=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");C.set(e,r),R.set(e,"ready"),D.set(e,{...n,cachedAt:Date.now()})}function L(e,r){R.set(e,"failed"),D.set(e,{error:r?.message||String(r),failedAt:Date.now()}),C.delete(e)}function z(e){return R.get(e)==="ready"?C.get(e):null}var T=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function re(){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 G(e,r,n,t="timeout",s=null){let o=new Error(`Sub-graph '${e}' (${r}) timed out after ${Math.round(n/1e3)}s (last status: ${t})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return o.code="SUBGRAPH_TIMEOUT",o.subgraphJobId=r,o.subgraphStatus=t,s&&(o.subgraphTransportError=s),o}function oe(e,r=process.env,n=process.uptime()){let t=Number.isFinite(e)?Number(e):null,s=Number(r&&r.MAX_WORKFLOW_DURATION_MS),o=Number.isFinite(n)&&n>0?n*1e3:0,a=Number.isFinite(s)&&s>0?s-o: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 se(e,r){let n=new AbortController,t=!1,s=null,o=()=>{n.abort(e?.reason)};return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),r!=null&&!n.signal.aborted&&(s=setTimeout(()=>{t=!0,n.abort(new Error("sub-graph deadline exceeded"))},r),typeof s.unref=="function"&&s.unref()),{signal:n.signal,timedOut:()=>t,dispose(){s&&(clearTimeout(s),s=null),e&&e.removeEventListener("abort",o)}}}var H=new ne,F=Promise.resolve();async function ae(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=H.getStore()===!0,s=null;if(!t){let a=F;F=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 b.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${t?" (nested)":""}`),await H.run(!0,r)}finally{for(let[a,i]of o)i===void 0?delete process.env[a]:process.env[a]=i;s&&s()}}function ie(){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 ce({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||b.warn(`[in-process subgraph] finalize returned ${t.status} for ${n.childExecutionId}`)}catch(t){b.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function ue(e,r){let n=w(r,".ready"),t=w(r,"graph.mjs");if(m(n)&&m(t))return;Q(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(m(n)&&m(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"]}),x=N("tar",["-xzf","-","-C",r],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(x.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()}),x.on("close",v=>{I=v,h()}),g.on("error",p),x.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 le(e){let r=w(e,"graph.mjs");if(!m(r))throw new l("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(te(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 Ee(e,r={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=O(),t;try{t=ie()}catch(u){throw u}b.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let s=await ce({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:x,nodeConfigs:f}=s,I=re();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(!x||!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=z(e);if(!h){let u=w(T,`${g}@${p||"0"}`);try{await ue(i,u);try{de()}catch{}}catch(c){throw c.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{h=await le(u),j(e,h,{workflowUuid:g,version:p,runtimeTag:a,cacheDir:u})}catch(c){throw L(e,c),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new l("import-failed",c.message)}}let v=Date.now(),W=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,X=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,Y={...r.input||{},...X?{nodeConfigs:f}:{}},S=oe(r.timeoutMs),A=se(r.signal,S),y,_;try{y=await ae(W,async()=>{let c=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return U({executionId:o,parentExecutionId:n.executionId,conversationId:r.conversationId!==void 0?r.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(r.parentAgent,Y,{signal:A.signal}))}),_=y&&typeof y=="object"&&"state"in y?y.state:y}catch(u){let c=A.timedOut();throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,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?G(e,o,S):u}finally{A.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let u=A.timedOut();if(await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:u?"timeout":"canceled",finalState:_,durationMs:Date.now()-v}}),u)throw G(e,o,S);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:_,durationMs:Date.now()-v}}),{finalState:_,executionId:o}}function Te(){try{if(!m(T))return{bytes:0,entries:0};let e=P(T),r=0;for(let n of e)try{r+=q(w(T,n))}catch{}return{bytes:r,entries:e.length}}catch{return{bytes:0,entries:0}}}function q(e){let r=0,n=[e];for(;n.length;){let t=n.pop(),s;try{s=J(t)}catch{continue}if(s.isDirectory()){let o;try{o=P(t)}catch{continue}for(let a of o)n.push(w(t,a))}else r+=s.size}return r}function de({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!m(T))return{evicted:0,freedBytes:0};let r=P(T),n=[],t=0;for(let i of r){let d=w(T,i),p;try{p=J(d)}catch{continue}let g=p.isDirectory()?q(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(!m(w(i.full,".lock")))try{ee(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&b.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 b.debug(`[sub-graph cache] evict failed: ${r.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,de as evictCacheIfOver,Te as getCacheStats,oe as resolveChildTimeoutMs,Ee as runInProcessSubgraph,G as subgraphTimeoutError,se as withChildDeadline};
|