@zibby/agent-workflow 2.0.4 → 2.0.5
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/fetch-deadline.d.ts +78 -0
- package/dist/fetch-deadline.js +1 -0
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.js +22 -22
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +31 -31
- package/dist/sub-graph-executor.d.ts +2 -0
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Tn=Object.defineProperty;var Re=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var be=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var yt=(n,e)=>{for(var t in e)Tn(n,t,{get:e[t],enumerable:!0})};function An(n){le.impl={...St,...n}}var wt,St,Me,le,v,H=be(()=>{wt=()=>{},St={debug:wt,info:wt,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},Me=Symbol.for("@zibby/agent-workflow.logger");globalThis[Me]||(globalThis[Me]={impl:St});le=globalThis[Me];v={debug:(...n)=>le.impl.debug?.(...n),info:(...n)=>le.impl.info?.(...n),warn:(...n)=>le.impl.warn?.(...n),error:(...n)=>le.impl.error?.(...n)}});var Ge,Fe=be(()=>{Ge=class{constructor(e,t,o=0){this.name=e,this.description=t,this.priority=o}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var Ct={};yt(Ct,{clearSkills:()=>Rt,getAllSkills:()=>Nt,getSkill:()=>te,getSkillSource:()=>xt,hasSkill:()=>Ot,listSkillIds:()=>Pt,registerSkill:()=>kt});function kt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:o=!1}=e,s=n.id;if(Z.has(s)&&!o){let i=pe.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${l} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}Z.set(s,Object.freeze({...n})),t===void 0?pe.delete(s):pe.set(s,t)}function te(n){return Z.get(n)||null}function Ot(n){return Z.has(n)}function xt(n){return pe.get(n)||null}function Nt(){return new Map(Z)}function Pt(){return Array.from(Z.keys())}function Rt(){Z.clear(),pe.clear()}var We,He,Z,pe,fe=be(()=>{We=Symbol.for("@zibby/agent-workflow.skills"),He=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[We]||(globalThis[We]=new Map);globalThis[He]||(globalThis[He]=new Map);Z=globalThis[We],pe=globalThis[He]});var he={};yt(he,{getAgentStrategy:()=>Ze,invokeAgent:()=>Dt,listStrategies:()=>Bt,registerStrategy:()=>Mt,resolveInvocationExtras:()=>Ye,resolveInvocationModel:()=>Je});function Mt(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=K.findIndex(t=>t.getName()===n.getName());e>=0?K[e]=n:K.push(n)}function Bt(){return K.map(n=>n.getName())}function Je({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:s}={}){let i=n.models||{},r=typeof s=="string"&&s.trim()?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,y=(typeof o=="string"?o.trim():"")||null;return r||a||l||u||e.model||y||null}function Ye({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function Ze(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let i=K.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}v.debug(`[workflow] agent selection: requested=${o}`);let s=K.find(i=>i.getName()===o);if(!s){let i=K.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!s.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${s.getName()}`),s}async function Dt(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:o},i=Ze(s),r=o.config||t.config||{},a=o._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,y=Je({config:r,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),d={...t,model:y,...Ye({options:t,stateView:o,context:e}),config:r},c=n,g=d.skills||[];if(g.length>0&&!t.skipPromptFragments){let $=t.connectedIntegrations;if(!$){let f=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof f=="string"&&f.trim()!==""){$={};for(let S of f.split(",").map(m=>m.trim()).filter(Boolean))$[S]=!0}}let T=f=>{let S=f&&f.requiresIntegration;return!S||!$?!0:(Array.isArray(S)?S:[S]).some(w=>$[w]===!0)},h=i.name==="assistant",E=f=>f?.inProcessOnly!==!0||h,A=g.map(f=>{let S=te(f);if(!T(S)||!E(S))return null;let m=S?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);A.length>0&&(c+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${A.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let p=o._currentNodeConfig?.stores;if(Array.isArray(p)&&p.length>0&&typeof p[0]=="object"){let $=p.length<=8,T=p.map(h=>{let E=h?.id??h?.storeId??"",A=(h?.name??"").toString().trim()||E,f=h?.type?` \xB7 ${h.type}`:"",S=(h?.description||"").toString().replace(/\s+/g," ").trim(),m=`- ${A} \xB7 ${S||"(no description)"}${f} (id: ${E})`;if($&&h?.schema&&typeof h.schema=="object"){let w=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);w.length&&(m+=`
|
|
6
|
+
fields: ${w.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
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${T.join(`
|
|
10
|
+
`)}`}let I=o._currentNodeConfig?.extraPromptInstructions?.trim();return I&&(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
|
-
${
|
|
17
|
-
`)
|
|
16
|
+
${I}
|
|
17
|
+
`),v.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,d)}var ze,K,ne=be(()=>{Fe();H();fe();ze=Symbol.for("@zibby/agent-workflow.strategies");globalThis[ze]||(globalThis[ze]=[]);K=globalThis[ze]});var vn=new Set(["__proto__","constructor","prototype"]);function Ce(n){if(vn.has(n))throw new Error(`Invalid state key: "${n}"`)}var ae=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Ce(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Ce(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Ce(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 V from"handlebars";var ce=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let o=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of o)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&s.type){let i=typeof e[o];i!==s.type&&t.push(`Field '${o}' expected ${s.type}, got ${i}`)}if(s.validate&&o in e){let i=s.validate(e[o]);i&&t.push(`Field '${o}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}}
|
|
19
|
+
`)}`);return e}},$n={string:(n=!0)=>({type:"string",required:n}),number:(n=!0)=>({type:"number",required:n}),boolean:(n=!0)=>({type:"boolean",required:n}),array:(n=!0)=>({type:"object",required:n,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(n,e=!0)=>({type:"string",required:e,validate:t=>n.includes(t)?null:`must be one of: ${n.join(", ")}`})};H();import{writeFileSync as Ke,readFileSync as jt,existsSync as Ut,mkdirSync as Rn}from"node:fs";import{join as Ve,dirname as Cn}from"node:path";import N from"chalk";var At="__WORKFLOW_GRAPH_LOG__",ue=N.gray("\u2502"),kn=N.gray("\u250C"),_t=N.gray("\u2514"),Be=N.green("\u25C6"),Et=N.hex("#c084fc")("\u25C6"),bt=N.hex("#2dd4bf")("\u25C6"),De=N.red("\u25C6"),It=`${ue} `,Tt=2;function vt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function $t(n,e){return(t,o,s)=>{if(typeof t!="string")return n(t,o,s);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=It,e.col=Tt,e.lineStart=!1),l===`
|
|
20
20
|
`?(r+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,r+=l):e.inEsc?(r+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,r+=l,e.col>=i&&(r+=`
|
|
21
|
-
${
|
|
21
|
+
${It}`,e.col=Tt))}return n(r,o,s)}}var Ie=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=$t(this._origStdoutWrite,e),process.stderr.write=$t(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${
|
|
24
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${At}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(Be,e):process.stdout.write.bind(process.stdout)(`${ue} ${Be} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Et,e):process.stdout.write.bind(process.stdout)(`${ue} ${Et} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(bt,t):process.stdout.write.bind(process.stdout)(`${ue} ${bt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(De,N.red(e)):process.stdout.write.bind(process.stdout)(`${ue} ${De} ${N.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${kn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:s}=t;if(s)for(let r of s)this._rawWrite(`${Be} ${r}`);let i=o?N.dim(` ${vt(o)}`):"";this._rawWrite(`${_t} ${N.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:s}=o,i=s?N.dim(` ${vt(s)}`):"";this._rawWrite(`${De} ${N.red(t)}`),this._rawWrite(`${_t} ${N.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new Ie;var de=".zibby/output",je="sessions",Y=".session-info.json",Ue=".zibby-stop",On="result.json",xn="raw_stream_output.txt",Nn="events.json",Pn=Object.freeze(["codebase-memory","code-scan","artifact"]),Le=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];V.helpers.inc||V.registerHelper("inc",n=>Number(n)+1);V.helpers.json||V.registerHelper("json",n=>JSON.stringify(n,null,2));V.helpers.eq||V.registerHelper("eq",(n,e)=>n===e);var F=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ce(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return v.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){v.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let d=null;for(let c=0;c<=this.retries;c++){try{let g=await this.customExecute(e);if(typeof g=="object"&&g!==null&&g.success===!1)d={success:!1,error:g.error||"Node execution failed",raw:g.raw||null};else return this.isZodSchema?(v.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(g),raw:null}):{success:!0,output:g,raw:null}}catch(g){v.error(`[workflow] node '${this.name}' failed: ${g.message}`),g.name==="ZodError"&&v.error(`Schema errors: ${JSON.stringify(g.issues||g.errors,null,2)}`),d={success:!1,error:g.message,raw:null}}c<this.retries&&v.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return d}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=V.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let r=s("_skillHints");r&&(i=`${r}
|
|
33
33
|
|
|
34
|
-
${i}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=ze(u,G);if(Ct(d)){let p=JSON.parse(Pt(d,"utf-8"));p.currentNode=this.name,He(d,JSON.stringify(p,null,2),"utf-8")}let c=ze(u,"..",G);if(Ct(c))try{let p=JSON.parse(Pt(c,"utf-8"));p.currentNode=this.name,He(c,JSON.stringify(p,null,2),"utf-8")}catch{}}}catch(d){$.debug(`[workflow] could not update session info: ${d.message}`)}let g=null;for(let d=0;d<=this.retries;d++)try{$.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=o().config||{},p=c.agents||{},f=this.config.agent??p[this.name]??null,v={state:o()};f&&(v.preferredAgent=f);let k={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(X(),ue))).invokeAgent);let h=await I(i,v,k),_,b;if(typeof h=="string"?(_=h,b=null):h.structured?(_=h.raw||JSON.stringify(h.structured,null,2),b=h.structured):(_=h.raw||JSON.stringify(h,null,2),b=h.extracted||null),u)try{let m=ze(u,this.name,"raw_stream_output.txt");An(xn(m),{recursive:!0}),He(m,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(m){$.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&b){$.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(b,null,2)}`);let m=b;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),b)}catch(y){$.warn(`[workflow] onComplete hook failed: ${y.message}`)}return{success:!0,output:m,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:_}),raw:_}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(_);return $.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),O.step("Output parsed"),{success:!0,output:m,raw:_}}return{success:!0,output:_,raw:_}}catch(c){g=c,d<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:g.message,raw:null}}};U();U();import{mkdirSync as Pn,existsSync as Z,statSync as Gt,readdirSync as Ht,rmSync as Cn}from"node:fs";import{spawn as Ft}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as Rn}from"node:url";import{AsyncLocalStorage as Mn}from"node:async_hooks";import{AsyncLocalStorage as Nn}from"node:async_hooks";var pe=new Nn;function Q(){let n=pe.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Rt(n,e){let t=pe.getStore()||Q(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return pe.run(o,e)}function Mt(n,e,t){let o=pe.getStore()||Q(),s=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return pe.run(s,t)}var Je=new Map,Ye=new Map,jt=new Map;function Bt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Je.set(n,e),Ye.set(n,"ready"),jt.set(n,{...t,cachedAt:Date.now()})}function Dt(n,e){Ye.set(n,"failed"),jt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Je.delete(n)}function Lt(n){return Ye.get(n)==="ready"?Je.get(n):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function jn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=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 _e(n,e,t,o="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=o,s&&(i.subgraphTransportError=s),i}function Bn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,r=Number.isFinite(s)&&s>0?s-i:null;if(o===null&&r===null)return null;let a=o===null?r:r===null?o:Math.min(o,r);return Math.max(1,a)}function Dn(n,e){let t=new AbortController,o=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>o,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var Ut=new Mn,Wt=Promise.resolve();async function Ln(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let o=Ut.getStore()===!0,s=null;if(!o){let r=Wt;Wt=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return $.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Fn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!o||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:s}}async function Un({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(o.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function Y({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||$.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){$.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function Wn(n,e){let t=W(e,".ready"),o=W(e,"graph.mjs");if(Z(t)&&Z(o))return;Pn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Z(t)&&Z(o))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let g=Ft("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),d=Ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(d.stdin);let c,p,f=()=>{if(c!==void 0&&p!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(p!==0)return u(new Error(`tar exited ${p}`));l()}};g.on("close",v=>{c=v,f()}),d.on("close",v=>{p=v,f()}),g.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",r.message)}}async function Gn(n){let e=W(n,"graph.mjs");if(!Z(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Rn(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new P("entry-class-missing","no buildGraph() class export found");return o}async function zt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),o;try{o=Fn()}catch(w){throw w}$.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await Un({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:g,bundleReady:d,nodeConfigs:c}=s,p=jn();if(r&&r!==p)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${p} vs ${r}`);if(!d||!a)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let f=Lt(n);if(!f){let w=W(Se,`${g}@${u||"0"}`);try{await Wn(a,w);try{zn()}catch{}}catch(T){throw T.fallback&&await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:T.message,code:T.reason}}}),T}try{f=await Gn(w),Bt(n,f,{workflowUuid:g,version:u,runtimeTag:r,cacheDir:w})}catch(T){throw Dt(n,T),await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:T.message,code:T.reason||"IMPORT_FAILED"}}}),T.fallback?T:new P("import-failed",T.message)}}let v=Date.now(),k=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},_=Bn(e.timeoutMs),b=Dn(e.signal,_),m,y;try{m=await Ln(k,async()=>{let T=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>T.run(e.parentAgent,h,{signal:b.signal}))}),y=m&&typeof m=="object"&&"state"in m?m.state:m}catch(w){let T=b.timedOut();throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:T?"timeout":"failed",error:T?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:w.message,code:w.code||"CHILD_THREW",stack:w.stack},durationMs:Date.now()-v}}),T?_e(n,i,_):w}finally{b.dispose()}if(m&&typeof m=="object"&&m.stoppedExternally){let w=b.timedOut();if(await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:w?"timeout":"canceled",finalState:y,durationMs:Date.now()-v}}),w)throw _e(n,i,_);let T=new Error(`Sub-graph '${n}' canceled by parent abort`);throw T.code="SUBGRAPH_CANCELED",T.subgraphJobId=i,T}return await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:i}}function Hn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),s;try{s=Gt(o)}catch{continue}if(s.isDirectory()){let i;try{i=Ht(o)}catch{continue}for(let r of i)t.push(W(o,r))}else e+=s.size}return e}function zn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(Se))return{evicted:0,freedBytes:0};let e=Ht(Se),t=[],o=0;for(let a of e){let l=W(Se,a),u;try{u=Gt(l)}catch{continue}let g=u.isDirectory()?Hn(l):u.size;o+=g,t.push({name:a,full:l,size:g,mtimeMs:u.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,r=0;for(let a of t){if(o-i<=s)break;if(!Z(W(a.full,".lock")))try{Cn(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){$.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&$.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:o-i}}catch(e){return $.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Jn=2e3,Yn=600*1e3,Zn=new Set(["completed","failed","canceled","timeout"]);function Kn(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function Vn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function qn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Xn(){return process.env.EXECUTION_ID||null}function Jt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function Ze(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:Yn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{$.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:b}=await zt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),m=Jt(b,e.output);return $.info(`[sub-graph] '${n}' completed in-process`),m}catch(b){if(b instanceof P||b?.fallback)$.info(`[sub-graph] in-process fallback for '${n}': ${b.reason||"unknown"} \u2014 using HTTP`);else throw b}let i=Kn(),r=Vn(),a=qn(),l=Xn(),u=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(n)}/trigger`,g={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};$.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let d=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(g)});if(!d.ok){let b=null,m="";try{b=await d.json(),m=b?.error||b?.message||JSON.stringify(b)}catch{m=await d.text().catch(()=>"")}if(d.status===429){let w=b?.quotaInfo||{},T=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw T.code="SUBGRAPH_QUOTA_EXCEEDED",T.status=429,T.subgraph=n,T.quotaInfo=w,T}if(d.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${m}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=b?.validationErrors||null,w.missing=b?.missing||null,w}let y=new Error(`Sub-graph '${n}' trigger rejected (${d.status}): ${m}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=d.status,y.subgraph=n,y}let c=await d.json(),p=c?.data?.jobId||c?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let f=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Jn,v=`${i}/executions/${encodeURIComponent(p)}`,k=Date.now()+s,I="accepted",h=0,_=null;for(;Date.now()<k;){await new Promise(w=>setTimeout(w,f)),h+=1;let b;try{b=await fetch(v,{headers:{Authorization:`Bearer ${a}`}})}catch(w){_=w?.message||String(w),$.warn(`[sub-graph] status poll for ${p} could not reach the API (${_}), will retry`);continue}if(!b.ok){if(b.status>=500){$.warn(`[sub-graph] status poll for ${p} returned ${b.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${b.status}`)}let m;try{m=await b.json()}catch(w){_=w?.message||String(w),$.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${_}), will retry`);continue}let y=m?.data||m?.execution||m;if(I=y?.status||I,Zn.has(I)){if(I!=="completed"){let te=new Error(`Sub-graph '${n}' (${p}) ended in status '${I}'`);throw te.subgraphJobId=p,te.subgraphStatus=I,te}let w=y?.finalState||y?.state||{},T=Jt(w,e.output);return $.info(`[sub-graph] '${n}' (${p}) completed after ${h} polls`),T}}throw _e(n,p,s,I,_)}import{existsSync as Yt,readFileSync as Qn}from"node:fs";import{join as Ke,dirname as Zt}from"node:path";var fe=class{static async loadContext(e,t,o={}){let s={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Zt(Ke(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let g=l.replace(/\.[^.]+$/,"").toLowerCase();s[g]=u}}}let r=o.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ke(t,l);Yt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],i=t;for(;i.startsWith(o);){let r=Ke(i,e);if(Yt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Zt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
|
|
34
|
+
${i}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Ve(u,Y);if(Ut(d)){let g=JSON.parse(jt(d,"utf-8"));g.currentNode=this.name,Ke(d,JSON.stringify(g,null,2),"utf-8")}let c=Ve(u,"..",Y);if(Ut(c))try{let g=JSON.parse(jt(c,"utf-8"));g.currentNode=this.name,Ke(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(d){v.debug(`[workflow] could not update session info: ${d.message}`)}let y=null;for(let d=0;d<=this.retries;d++)try{v.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=o().config||{},g=c.agents||{},p=this.config.agent??g[this.name]??null,I={state:o()};p&&(I.preferredAgent=p);let $={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},T=e?._coreInvokeAgent;T||(T=(await Promise.resolve().then(()=>(ne(),he))).invokeAgent);let h=await T(i,I,$),E,A;if(typeof h=="string"?(E=h,A=null):h.structured?(E=h.raw||JSON.stringify(h.structured,null,2),A=h.structured):(E=h.raw||JSON.stringify(h,null,2),A=h.extracted||null),u)try{let f=Ve(u,this.name,"raw_stream_output.txt");Rn(Cn(f),{recursive:!0}),Ke(f,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(f){v.debug(`[workflow] could not save raw output: ${f.message}`)}if(this.isZodSchema&&A){v.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(A,null,2)}`);let f=A;if(typeof this.onComplete=="function")try{f=await this.onComplete(o(),A)}catch(S){v.warn(`[workflow] onComplete hook failed: ${S.message}`)}return{success:!0,output:f,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:E}),raw:E}}catch(f){throw new Error(`onComplete failed: ${f.message}`,{cause:f})}if(this.parser){let f=this.parser.parse(E);return v.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(f,null,2)}`),P.step("Output parsed"),{success:!0,output:f,raw:E}}return{success:!0,output:E,raw:E}}catch(c){y=c,d<this.retries&&v.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:y.message,raw:null}}};H();H();import{mkdirSync as Un,existsSync as X,statSync as Kt,readdirSync as Vt,rmSync as Ln}from"node:fs";import{spawn as Jt}from"node:child_process";import{join as z}from"node:path";import{pathToFileURL as Gn}from"node:url";import{AsyncLocalStorage as Fn}from"node:async_hooks";import{AsyncLocalStorage as Mn}from"node:async_hooks";var ge=new Mn;function oe(){let n=ge.getStore();return n||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function Lt(n,e){let t=ge.getStore()||oe(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ge.run(o,e)}function Gt(n,e,t){let o=ge.getStore()||oe(),s=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ge.run(s,t)}var qe=new Map,Xe=new Map,Ft=new Map;function Wt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");qe.set(n,e),Xe.set(n,"ready"),Ft.set(n,{...t,cachedAt:Date.now()})}function Ht(n,e){Xe.set(n,"failed"),Ft.set(n,{error:e?.message||String(e),failedAt:Date.now()}),qe.delete(n)}function zt(n){return Xe.get(n)==="ready"?qe.get(n):null}function me(n,e,t=process.env){let o=Number(t[n]);return Number.isFinite(o)&&o>0?Math.min(12e4,Math.max(1e3,Math.floor(o))):e}function Qe(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ye(n,e){return Qe(me(n,e),n)}function U(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var Te=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Wn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var R=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 ve(n,e,t,o="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=o,s&&(i.subgraphTransportError=s),i}function Hn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,r=Number.isFinite(s)&&s>0?s-i:null;if(o===null&&r===null)return null;let a=o===null?r:r===null?o:Math.min(o,r);return Math.max(1,a)}function zn(n,e){let t=new AbortController,o=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>o,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var Yt=new Fn,Zt=Promise.resolve();async function Jn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let o=Yt.getStore()===!0,s=null;if(!o){let r=Zt;Zt=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await Yt.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Yn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!o||!s)throw new R("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:s}}async function Zn({apiBase:n,authToken:e,body:t}){let o=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal})}catch(r){throw new R(U(r)?"begin-timeout":"network",U(r)?`begin TIMED OUT ${o.label}`:`begin fetch failed: ${r.message}`)}let i=null;try{i=await s.json()}catch(r){if(U(r))throw new R("begin-timeout",`begin body read TIMED OUT ${o.label}`)}if(!s.ok){if(s.status===404){let r=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw r.code="SUBGRAPH_NOT_FOUND",r.status=404,r}if(s.status===429){let r=i?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${r.used??"?"}/${r.limit??"?"} on ${r.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=r,a}if(s.status===400&&i?.validationErrors){let r=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw r.code="SUBGRAPH_INVALID_INPUT",r.status=400,r.validationErrors=i.validationErrors,r.missing=i.missing,r}throw new R("begin-status",`begin returned ${s.status}`)}return i?.data||i}async function q({apiBase:n,authToken:e,payload:t}){let o=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:o.signal});s.ok||v.warn(`[in-process subgraph] finalize returned ${s.status} for ${t.childExecutionId}`)}catch(s){v.warn(`[in-process subgraph] finalize ${U(s)?`TIMED OUT ${o.label}`:`failed: ${s.message}`}`)}}async function Kn(n,e){let t=z(e,".ready"),o=z(e,"graph.mjs");if(X(t)&&X(o))return;Un(e,{recursive:!0});let s=z(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(X(t)&&X(o))return;await new Promise(a=>setTimeout(a,100))}throw new R("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let y=Math.ceil(1e4/1e3),d=Math.ceil(me("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=Jt("curl",["-fsSL","--connect-timeout",String(y),"--max-time",String(d),n],{stdio:["ignore","pipe","inherit"]}),g=Jt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(g.stdin);let p,I,$=()=>{if(p!==void 0&&I!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(I!==0)return u(new Error(`tar exited ${I}`));l()}};c.on("close",T=>{p=T,$()}),g.on("close",T=>{I=T,$()}),c.on("error",u),g.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new R("bundle-extract-failed",r.message)}}async function Vn(n){let e=z(n,"graph.mjs");if(!X(e))throw new R("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Gn(e).href)}catch(s){throw new R("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new R("entry-class-missing","no buildGraph() class export found");return o}async function qt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),o;try{o=Yn()}catch(m){throw m}v.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await Zn({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:y,bundleReady:d,nodeConfigs:c}=s,g=Wn();if(r&&r!==g)throw await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new R("runtime-mismatch",`${g} vs ${r}`);if(!d||!a)throw await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new R("no-bundle","workflow bundle not built yet");let p=zt(n);if(!p){let m=z(Te,`${y}@${u||"0"}`);try{await Kn(a,m);try{Xn()}catch{}}catch(w){throw w.fallback&&await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{p=await Vn(m),Wt(n,p,{workflowUuid:y,version:u,runtimeTag:r,cacheDir:m})}catch(w){throw Ht(n,w),await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new R("import-failed",w.message)}}let I=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,T=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...T?{nodeConfigs:c}:{}},E=Hn(e.timeoutMs),A=zn(e.signal,E),f,S;try{f=await Jn($,async()=>{let w=await(typeof p=="function"&&p.prototype?.buildGraph?new p:p).buildGraph();return Lt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>w.run(e.parentAgent,h,{signal:A.signal}))}),S=f&&typeof f=="object"&&"state"in f?f.state:f}catch(m){let w=A.timedOut();throw await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:w?"timeout":"failed",error:w?{message:`aborted at the declared ${Math.round(E/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-I}}),w?ve(n,i,E):m}finally{A.dispose()}if(f&&typeof f=="object"&&f.stoppedExternally){let m=A.timedOut();if(await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:m?"timeout":"canceled",finalState:S,durationMs:Date.now()-I}}),m)throw ve(n,i,E);let w=new Error(`Sub-graph '${n}' canceled by parent abort`);throw w.code="SUBGRAPH_CANCELED",w.subgraphJobId=i,w}return await q({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:S,durationMs:Date.now()-I}}),{finalState:S,executionId:i}}function qn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),s;try{s=Kt(o)}catch{continue}if(s.isDirectory()){let i;try{i=Vt(o)}catch{continue}for(let r of i)t.push(z(o,r))}else e+=s.size}return e}function Xn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!X(Te))return{evicted:0,freedBytes:0};let e=Vt(Te),t=[],o=0;for(let a of e){let l=z(Te,a),u;try{u=Kt(l)}catch{continue}let y=u.isDirectory()?qn(l):u.size;o+=y,t.push({name:a,full:l,size:y,mtimeMs:u.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,r=0;for(let a of t){if(o-i<=s)break;if(!X(z(a.full,".lock")))try{Ln(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&v.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:o-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var eo=2e3,to=600*1e3,no=new Set(["completed","failed","canceled","timeout"]);var oo=()=>ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function ro(n){let e=me("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return Qe(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function so(){let n=process.env.PROGRESS_API_URL;if(!n)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return n.replace(/\/executions\/?$/,"")}function io(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function ao(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function co(){return process.env.EXECUTION_ID||null}function Xt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function et(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:to;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{v.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:f}=await qt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),S=Xt(f,e.output);return v.info(`[sub-graph] '${n}' completed in-process`),S}catch(f){if(f instanceof R||f?.fallback)v.info(`[sub-graph] in-process fallback for '${n}': ${f.reason||"unknown"} \u2014 using HTTP`);else throw f}let i=so(),r=io(),a=ao(),l=co(),u=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(n)}/trigger`,y={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};v.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let d=oo(),c;try{c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(y),signal:d.signal})}catch(f){if(!U(f))throw f;let S=new Error(`Sub-graph '${n}' trigger TIMED OUT ${d.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw S.code="SUBGRAPH_TRIGGER_TIMEOUT",S.subgraph=n,S.timedOut=!0,S.cause=f,S}if(!c.ok){let f=null,S="";try{f=await c.json(),S=f?.error||f?.message||JSON.stringify(f)}catch{S=await c.text().catch(()=>"")}if(c.status===429){let w=f?.quotaInfo||{},k=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw k.code="SUBGRAPH_QUOTA_EXCEEDED",k.status=429,k.subgraph=n,k.quotaInfo=w,k}if(c.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${S}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=f?.validationErrors||null,w.missing=f?.missing||null,w}let m=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${S}`);throw m.code="SUBGRAPH_TRIGGER_FAILED",m.status=c.status,m.subgraph=n,m}let g;try{g=await c.json()}catch(f){if(!U(f))throw f;let S=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${d.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw S.code="SUBGRAPH_TRIGGER_TIMEOUT",S.subgraph=n,S.timedOut=!0,S.cause=f,S}let p=g?.data?.jobId||g?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(g).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let I=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:eo,$=`${i}/executions/${encodeURIComponent(p)}`,T=Date.now()+s,h="accepted",E=0,A=null;for(;Date.now()<T;){await new Promise(k=>setTimeout(k,I)),E+=1;let f=ro(T),S;try{S=await fetch($,{headers:{Authorization:`Bearer ${a}`},signal:f.signal})}catch(k){A=U(k)?`poll TIMED OUT ${f.label}`:k?.message||String(k),v.warn(`[sub-graph] status poll for ${p} could not reach the API (${A}), will retry`);continue}if(!S.ok){if(S.status>=500){v.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 m;try{m=await S.json()}catch(k){A=U(k)?`poll body read TIMED OUT ${f.label}`:k?.message||String(k),v.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${A}), will retry`);continue}let w=m?.data||m?.execution||m;if(h=w?.status||h,no.has(h)){if(h!=="completed"){let J=new Error(`Sub-graph '${n}' (${p}) ended in status '${h}'`);throw J.subgraphJobId=p,J.subgraphStatus=h,J}let k=w?.finalState||w?.state||{},W=Xt(k,e.output);return v.info(`[sub-graph] '${n}' (${p}) completed after ${E} polls`),W}}throw ve(n,p,s,h,A)}import{existsSync as Qt,readFileSync as lo}from"node:fs";import{join as tt,dirname as en}from"node:path";var we=class{static async loadContext(e,t,o={}){let s={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=en(tt(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let y=l.replace(/\.[^.]+$/,"").toLowerCase();s[y]=u}}}let r=o.discovery||{};for(let[a,l]of Object.entries(r))try{let u=tt(t,l);Qt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],i=t;for(;i.startsWith(o);){let r=tt(i,e);if(Qt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=en(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=
|
|
38
|
+
`):s.every(r=>typeof r=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=lo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(e).href);return s.default||s}return t}};import{mkdirSync as on,existsSync as nt,writeFileSync as tn,unlinkSync as uo}from"node:fs";import{join as Q,resolve as rn}from"node:path";import{config as po}from"dotenv";import{zodToJsonSchema as nn}from"zod-to-json-schema";import{z as Ae}from"zod";import fo from"handlebars";function ho({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${n} pid=${process.pid} ppid=${r} sessionId=${e} source=${o} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let y=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${n}):
|
|
41
|
-
${g}`)}}function Qt(){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 en(){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 Xt(String(e).trim())}catch{return String(e).trim()}}function tn(){Qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function nn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function on(n={}){let e=Me.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${o}`:o}function rn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Xt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=on(e),r="generated")}i=i??Date.now();let g=e.paths?.output||ce;s=K(n,g,Ce,a)}let l=!Ve(s);return l&&qt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&oo({traceFrom:o,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),nn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ee=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,o={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let g=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(g):r.input&&typeof r.input=="object"?d=r.input:d={},Ze(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(g):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:g?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.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:o}={}){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:o}),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,o=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&o(r)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,s,i){let r=o;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let p=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(f.description=v);let k=this.nodePrompts.get(d);if(k)f.prompt=k;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(f.prompt=y,f.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString());let I=c?.config?.dispatchesWorkflow;if(typeof I=="string"&&I.trim())f.dispatchesWorkflow=I.trim();else if(Array.isArray(I)){let y=[...new Set(I.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];y.length&&(f.dispatchesWorkflow=y)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(f.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof be?.toJSONSchema=="function")try{y=be.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=Vt(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[d];h?.toolIds&&(f.tools=h.toolIds);let _=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;_&&_.length>0&&(f.skills=[..._]);let b=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;b&&b.length>0&&(f.plugins=b.map(y=>y&&typeof y=="object"?{...y}:y));let m=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;m&&m.length>0&&(f.stores=m.map(y=>y&&typeof y=="object"?{...y}:y)),Object.keys(f).length>0&&(t[d]=f)}let o=[];for(let[d,c]of this.edges)if(typeof c=="string")o.push({source:d,target:c});else if(Array.isArray(c))for(let p of c)o.push({source:d,target:p});else if(c.conditional){let p=this.conditionalCodeMap.get(d)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},k=this.nodes.get(d),I=k?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!k,h=d;if(!I){let _=`${d}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),o.push({source:d,target:_}),h=_}for(let _ of f){let b={source:h,target:_,data:{conditionalCode:p}};v[_]&&(b.label=v[_]),o.push(b)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Vt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of o)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:d,target:c})}let r=this._topoOrderNodes(e,o),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),g=s(this.contextSchema);return{nodes:r,edges:o,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:g}}_topoOrderNodes(e,t){let o=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(o.keys()),u=[...l].filter(d=>i.get(d)===0),g=[];for(;g.length<e.length;){let d;if(u.length>0){if(u.sort((c,p)=>o.get(c)-o.get(p)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,p)=>o.get(c)-o.get(p))[0];a.add(d),l.delete(d),g.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return g}_inferConditionalTargets(e,t){let o=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(o))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,g;for(;(g=u.exec(o))!==null;)l.add(g[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){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(E){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${E?.message||E}`);throw S.cause=E,S.code=E?.code||"NORMALIZE_INPUT_FAILED",S}let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();to({path:K(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=K(r,".zibby.config.js");Ve(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let E=a?.agent;E?.provider?l=E.provider:E?.gemini?l="gemini":E?.claude?l="claude":E?.cursor?l="cursor":E?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},g=this._runtimeSchema();if(g){let E=g.safeParse(t);if(!E.success){let S=E.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${S.join(", ")}`)}O.step("State validated against schema")}let d=en(),c=t.sessionPath||d;c||tn();let{sessionPath:p,sessionTimestamp:f,sessionId:v}=rn({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${v}`);let k=await fe.loadContext(t.specPath||"",r,u);Object.keys(k).length>0&&O.step(`Context loaded: ${Object.keys(k).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new re({...t,config:a,agentType:l,outputPath:I,sessionPath:p,sessionTimestamp:f,context:k,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:b}=await Promise.resolve().then(()=>(de(),At)),m=a.skills&&typeof a.skills=="object"?a.skills:{},y=Object.values(m).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),w=E=>{for(let S of y)if(S.id===E)return S;return b(E)},T=new Set;for(let[,E]of this.nodes)for(let S of E.config?.skills||[])T.add(S);for(let E of T){let S=w(E);if(typeof S?.middleware=="function")try{let R=await S.middleware();typeof R=="function"&&_.set(E,R)}catch{}}let{backEdges:te,joinDegree:ln}=this._analyzeFlow(),$e=new Map,ne=[],Te=(E,S,R)=>{if(!E||E==="END")return;let D=ln.get(E)||0;if(R&&D>1&&!te.has(`${S}->${E}`)){let oe=($e.get(E)||0)+1;if(oe<D){$e.set(E,oe);return}$e.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let ge=[],ot=a?.recursionLimit??100,dn=0;try{for(;ne.length>0;){let S=ne.pop();if(!S||S==="END")continue;if(++dn>ot)throw new Error(`Workflow exceeded recursion limit (${ot}) \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 R=K(p,Re);if(Ve(R)){try{eo(R)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
43
|
-
${
|
|
41
|
+
${y}`)}}function sn(){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 an(){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 rn(String(e).trim())}catch{return String(e).trim()}}function cn(){sn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function ln({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function un(n={}){let e=Le.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${o}`:o}function dn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=rn(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=un(e),r="generated")}i=i??Date.now();let y=e.paths?.output||de;s=Q(n,y,je,a)}let l=!nt(s);return l&&on(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&ho({traceFrom:o,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),ln({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var re=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,o={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let y=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(y):r.input&&typeof r.input=="object"?d=r.input:d={},et(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(y):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:y?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.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:o}={}){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:o}),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,o=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&o(r)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,s,i){let r=o;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let g=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:g,data:{nodeType:g,label:d}});let p={};c._isCustomCode&&typeof c.execute=="function"&&(p.customCode=c.execute.toString());let I=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;I&&(p.description=I);let $=this.nodePrompts.get(d);if($)p.prompt=$;else if(typeof c.prompt=="function")try{let m=c.prompt({});typeof m=="string"&&m.trim()&&(p.prompt=m,p.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(p.executeCode=c.customExecute.toString());let T=c?.config?.dispatchesWorkflow;if(typeof T=="string"&&T.trim())p.dispatchesWorkflow=T.trim();else if(Array.isArray(T)){let m=[...new Set(T.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];m.length&&(p.dispatchesWorkflow=m)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(p.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let m=null;if(typeof Ae?.toJSONSchema=="function")try{m=Ae.toJSONSchema(c.outputSchema)}catch{}if(!m)try{m=nn(c.outputSchema,{target:"openApi3"})}catch{}p.outputSchema=m?{jsonSchema:m,variables:this._flattenJsonSchemaToVariables(m)}:{schema:c.outputSchema}}else p.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[d];h?.toolIds&&(p.tools=h.toolIds);let E=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;E&&E.length>0&&(p.skills=[...E]);let A=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;A&&A.length>0&&(p.plugins=A.map(m=>m&&typeof m=="object"?{...m}:m));let f=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;f&&f.length>0&&(p.stores=f.map(m=>m&&typeof m=="object"?{...m}:m));let S=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(S&&S.length>0){let m=new Set,w=[];for(let k of S){let W=typeof k=="string"?k.trim():"";!W||m.has(W)||(m.add(W),w.push(W))}w.length>0&&(p.uses=w)}Object.keys(p).length>0&&(t[d]=p)}let o=[];for(let[d,c]of this.edges)if(typeof c=="string")o.push({source:d,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:d,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(d)||c.routes.toString(),p=this._inferConditionalTargets(c.routes,c.labels),I=c.labels||{},$=this.nodes.get(d),T=$?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!$,h=d;if(!T){let E=`${d}__branch`;e.push({id:E,type:"decision",data:{nodeType:"decision",label:E}}),o.push({source:d,target:E}),h=E}for(let E of p){let A={source:h,target:E,data:{conditionalCode:g}};I[E]&&(A.label=I[E]),o.push(A)}}let s=d=>{if(!d)return null;if(typeof Ae?.toJSONSchema=="function")try{return Ae.toJSONSchema(d)}catch{}try{return nn(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of o)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:d,target:c})}let r=this._topoOrderNodes(e,o),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),y=s(this.contextSchema);return{nodes:r,edges:o,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:y}}_topoOrderNodes(e,t){let o=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(o.keys()),u=[...l].filter(d=>i.get(d)===0),y=[];for(;y.length<e.length;){let d;if(u.length>0){if(u.sort((c,g)=>o.get(c)-o.get(g)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(d),l.delete(d),y.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return y}_inferConditionalTargets(e,t){let o=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(o))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,y;for(;(y=u.exec(o))!==null;)l.add(y[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){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 _=new Error(`agent.normalizeInput() rejected the trigger input: ${b?.message||b}`);throw _.cause=b,_.code=b?.code||"NORMALIZE_INPUT_FAILED",_}let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();po({path:Q(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let b=Q(r,".zibby.config.js");nt(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let b=a?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},y=this._runtimeSchema();if(y){let b=y.safeParse(t);if(!b.success){let _=b.error.issues.map(M=>`${M.path.join(".")}: ${M.message}`);throw console.error("\u274C Initial state validation failed:"),_.forEach(M=>console.error(` - ${M}`)),new Error(`State validation failed: ${_.join(", ")}`)}P.step("State validated against schema")}let d=an(),c=t.sessionPath||d;c||cn();let{sessionPath:g,sessionTimestamp:p,sessionId:I}=dn({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${I}`);let $=await we.loadContext(t.specPath||"",r,u);Object.keys($).length>0&&P.step(`Context loaded: ${Object.keys($).join(", ")}`);let T=t.outputPath;!T&&t.specPath&&(e?.calculateOutputPath?T=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new ae({...t,config:a,agentType:l,outputPath:T,sessionPath:g,sessionTimestamp:p,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),E=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:A}=await Promise.resolve().then(()=>(fe(),Ct)),f=a.skills&&typeof a.skills=="object"?a.skills:{},S=Object.values(f).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),m=b=>{for(let _ of S)if(_.id===b)return _;return A(b)},w=new Set;for(let[,b]of this.nodes)for(let _ of b.config?.skills||[])w.add(_);for(let b of w){let _=m(b);if(typeof _?.middleware=="function")try{let M=await _.middleware();typeof M=="function"&&E.set(b,M)}catch{}}let{backEdges:k,joinDegree:W}=this._analyzeFlow(),J=new Map,se=[],Ne=(b,_,M)=>{if(!b||b==="END")return;let L=W.get(b)||0;if(M&&L>1&&!k.has(`${_}->${b}`)){let ie=(J.get(b)||0)+1;if(ie<L){J.set(b,ie);return}J.set(b,0)}se.includes(b)||se.push(b)};this.entryPoint&&se.push(this.entryPoint);let _e=[],lt=a?.recursionLimit??100,gn=0;try{for(;se.length>0;){let _=se.pop();if(!_||_==="END")continue;if(++gn>lt)throw new Error(`Workflow exceeded recursion limit (${lt}) \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 M=Q(g,Ue);if(nt(M)){try{uo(M)}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:h.getAll(),executionLog:_e,stoppedExternally:!0};let L=this.nodes.get(_);if(!L)throw new Error(`Node '${_}' not found in graph`);let ie=JSON.stringify({sessionPath:g,sessionTimestamp:p,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),mn=Q(g,Y);tn(mn,ie,"utf-8");let ut=h.get("config")?.paths?.output||de,yn=Q(r,ut,Y);on(Q(r,ut),{recursive:!0});try{tn(yn,ie,"utf-8")}catch{}let dt=t.onPipelineProgress;if(typeof dt=="function")try{dt({cwd:r,sessionPath:g,sessionId:I,outputBase:h.get("config")?.paths?.output||de,currentNode:_})}catch{}let wn=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",wn);let Sn=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Sn[_]||{}),P.nodeStart(_);let pt=Date.now(),Ee=this.nodePrompts.get(_);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(ne(),he));this._invokeAgent=x.invokeAgent}let _n=this._invokeAgent,Pe={},En=L.config?.skills||[];for(let x of En){let C=m(x);if(typeof C?.invokeAgentOptions=="function")try{let O=C.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});O&&typeof O=="object"&&(Pe={...Pe,...O})}catch(O){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${O.message}`)}}let ft=async(x,C,O={})=>{let B=_n(x,C,{...Pe,...O,signal:s.signal});return B.catch(()=>{}),s.signal.aborted?B:Promise.race([B,new Promise((ee,G)=>{let D=()=>{setTimeout(()=>{let mt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);mt.name="AbortError",G(mt)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},bn=async(x={},C={})=>{let O=C.prompt||"";if(Ee){let B=this._compiledPrompts.get(_);B||(B=fo.compile(Ee,{noEscape:!0}),this._compiledPrompts.set(_,B));try{O=B(x)}catch(ee){throw console.error(`\u274C Template rendering failed for node '${_}':`,ee.message),new Error(`Template rendering failed: ${ee.message}`,{cause:ee})}}else if(!O)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return ft(O,{state:h.getAll(),images:C.images||[]},{model:C.model||h.get("model"),workspace:h.get("workspace"),schema:C.schema,...C,signal:s.signal,nodeName:_})},ht=h.getAll(),In=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of In)Object.prototype.hasOwnProperty.call(ht,x)&&console.warn(`[workflow] node "${_}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let gt={...ht,state:h,invokeAgent:bn,_coreInvokeAgent:ft,agent:e,nodeId:_,promptTemplate:Ee,getPromptTemplate:()=>Ee};try{let x=(L.config?.skills||[]).map(D=>E.get(D)).filter(Boolean),C=[...this.middleware,...x],O;O=await Gt(e,s.signal,async()=>C.length>0?this._composeMiddleware(C,_,async()=>L.execute(gt,h),h.getAll(),h):L.execute(gt,h));let B=Date.now()-pt;if(_e.push({node:_,success:O.success,duration:B,timestamp:new Date().toISOString()}),!O.success){if(s.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:_e,stoppedExternally:!0};h.append("errors",{node:_,error:O.error});let D=(L.config?.retries||0)+1;throw P.nodeFailed(_,O.error,{duration:B}),new Error(`Node '${_}' failed after ${D} attempt(s): ${O.error}`)}h.update({[_]:O.output});let ee=this._summarizeNodeOutput(_,O.output);P.nodeComplete(_,{duration:B,details:ee});let G=this.edges.get(_);if(G)if(G.conditional){let D=G.routes(h.getAll());P.route(_,D),Ne(D,_,!1)}else if(Array.isArray(G))for(let D=G.length-1;D>=0;D--)Ne(G[D],_,!0);else Ne(G,_,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(_,x.message,{duration:Date.now()-pt}),h.set("failed",!0),h.set("failedAt",_),x}}P.graphComplete();let b={success:!0,state:h.getAll(),executionLog:_e};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}`)}}}};var ot=Symbol.for("@zibby/agent-workflow.nodes");globalThis[ot]||(globalThis[ot]=new Map);var Se=globalThis[ot];function pn(n,e){Se.set(n,e)}function rt(n){return Se.get(n)}function ke(n){return Se.has(n)}function go(){return Array.from(Se.keys())}function st(n){let e=Se.get(n);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}pn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let o=t?._coreInvokeAgent;o||(o=(await Promise.resolve().then(()=>(ne(),he))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=mo(s,t),r=await o(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:n},raw:typeof r=="string"?r:r.raw}}})});function mo(n,e){let t=/@([\w.]+)/g,o=new Set,s;for(;(s=t.exec(n))!==null;)o.add(s[1]);if(o.size===0)return n;let i=[],r=new Set;for(let a of o){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,g)=>c?.[g],e);if(u===void 0)continue;let y=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${d}
|
|
43
|
+
${y}`),a.includes(".")||r.add(l)}return i.length===0?n:`${n}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
48
|
${i.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}
|
|
51
|
-
`)}function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`).map((
|
|
50
|
+
`)}`}fe();H();var Oe={};function at(n,e){if(Array.isArray(e))return it(e);let t=Oe[n];return!t||t.length===0?null:it(t)}function it(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let s of n){let i=te(s);if(!i){v.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}o.push(s);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:s})}else{let r={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:s}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}H();function yo(n,e={}){let{nodes:t,edges:o,nodeConfigs:s={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(o))throw new j("Graph edges must be an array");let i=new re(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let g=xe(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&r.add(c.id)}for(let[c,g]of a){if(r.has(c))continue;let p=g.resolvedType,I=s[c]||{},$=at(p,I.tools);$&&(l[c]=$);let T={};I.prompt&&(T.prompt=I.prompt);let h=ke(p);if(v.debug(`[workflow] compiler: node "${c}" type="${p}" registered=${h}`),I.customCode&&!h)i.addNode(c,fn(c,I.customCode,I),T),i.setNodeType(c,p);else if(h){let E=rt(p);E.factory?i.addNode(c,E.create(c,{...I,resolvedTools:$}),T):i.addNode(c,E,T),i.setNodeType(c,p)}else if(I.executeCode)i.addNode(c,fn(c,I.executeCode,I),T),i.setNodeType(c,p);else throw new j(`Unknown node type "${p}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of o)r.has(c.target)||u.add(c.target);let y=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!y)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(y.id);let d=_o(o,"source");for(let c of o)if(!r.has(c.source))if(r.has(c.target)){let g=c.target,p=d.get(g)||[];if(p.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let I=Eo(g,p,r);i.addConditionalEdges(c.source,I)}else i.addEdge(c.source,c.target);return i}function wo(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let l=xe(a);if(l==="decision"||ke(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let o=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)o.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),o.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(n.nodes.filter(a=>xe(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)s.has(a.target)||i.add(a.target);let r=n.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of s){let l=n.edges.filter(y=>y.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(y=>y.data?.conditionalCode||y.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function So(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>xe(e)!=="decision").map(e=>e.id)}function xe(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function _o(n,e){let t=new Map;for(let o of n){let s=o[e];t.has(s)||t.set(s,[]),t.get(s).push(o)}return t}function Eo(n,e,t){let o=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!o)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let s=o.data?.conditionalCode||o.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${s})`)();r=u=>{let y=l(u);return i.has(y)||v.warn(`[workflow] conditional route from "${n}" returned "${y}" which is not in valid targets: ${[...i].join(", ")}`),y}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return r}function fn(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new j(`Failed to compile customCode for node "${n}": ${r.message}`)}let s=o(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ne(),he));return a(...r)},typeof Re<"u"?Re:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await s(r);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};fe();var ct=/^[a-z][a-z0-9_]{0,40}$/;function bo(n){if(n==null)return[];if(!Array.isArray(n))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return n.forEach((o,s)=>{if(o==null||typeof o!="object"||Array.isArray(o)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=o;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}ct.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${ct} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}Fe();ne();function Io(n,e={}){let{nodes:t,edges:o,nodeConfigs:s={}}=n,i=new Set,r=[],a=new Map;for(let $ of t){let T=$.data?.nodeType||$.type;a.set($.id,T),T==="decision"?i.add($.id):r.push({id:$.id,nodeType:T,label:$.data?.label||$.id})}let l=r.some($=>{let T=s[$.id]||{};return!T.customCode&&!T.executeCode}),{toolsPerNode:u,toolIdsByVar:y}=No(r,s),{simpleEdges:d,conditionalEdges:c}=Po(o,i),g=Ro(r,o,i),p=[],I=e.workflowType||"workflow";return p.push(vo(e)),p.push($o(I,{usesRegisteredNodes:l})),p.push(Ao(y)),p.push(ko(I)),p.push(Oo(r,s)),p.push(xo(r,g,d,c,u,I)),p.filter(Boolean).join(`
|
|
51
|
+
`)}function To(n){let e={};for(let[t,o]of Object.entries(n)){let{tools:s,...i}=o;Object.keys(i).length>0&&(e[t]=i)}return e}function vo(n){let e=n.workflowType||"workflow";return["// Generated workflow",`// ${n.projectId?`Project: ${n.projectId} | `:""}Type: ${e} | Version: ${n.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
|
+
`)}function $o(n,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
53
|
+
`)}function Ao(n){if(n.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,o]of n)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(o)}); // ${o.join(", ")}`);return e.push(""),e.join(`
|
|
54
|
+
`)}function ko(n){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${n}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
55
|
+
`)}function Oo(n,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let o of n){let s=hn(o.id),i=e[o.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${o.nodeType}" template`),t.push(`const ${s}_execute = ${i};`);else{let r=st(o.nodeType);r?(t.push(`// Default "${o.nodeType}" implementation`),t.push(`const ${s}_execute = ${r};`)):(t.push(`// No template for "${o.nodeType}" \u2014 passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
56
|
+
`)}function xo(n,e,t,o,s,i){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let l of n){let u=hn(l.id);r.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),r.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||o.length>0)&&r.push(" // Edges");for(let l of t)r.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of o){let u=l.code.split(`
|
|
57
|
+
`).map((y,d)=>d===0?y:` ${y}`).join(`
|
|
58
58
|
`);r.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of n){let u=s.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
|
|
59
|
-
`)}function
|
|
59
|
+
`)}function No(n,e){let t=new Map,o=new Map;for(let s of n){let i=e[s.id]?.tools,r;if(Array.isArray(i)&&i.length>0)r=[...i].sort();else{let a=Oe[s.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),o.has(a)||o.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:o}}function Po(n,e){let t=[],o=[],s=new Map,i=new Set;for(let r of n)s.has(r.source)||s.set(r.source,[]),s.get(r.source).push(r);for(let r of n)if(!e.has(r.source))if(e.has(r.target)){if(i.has(r.target))continue;i.add(r.target);let l=(s.get(r.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&o.push({source:r.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:o}}function Ro(n,e,t){let o=new Set;for(let i of e)t.has(i.target)||o.add(i.target);let s=n.find(i=>!o.has(i.id));return s?s.id:n[0]?.id}function hn(n){return n.replace(/[^a-zA-Z0-9]/g,"_")}H();var Co=`## Composing deployed agents (wrapper over marketplace bricks)
|
|
60
60
|
|
|
61
61
|
**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
|
|
62
62
|
modify a brick template's source and never rebuild its logic from scratch.
|
|
@@ -125,4 +125,4 @@ template workflow.json) and paste the exact array. The platform then
|
|
|
125
125
|
automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
|
|
126
126
|
listed in a deployed wrapper's composedOf stops receiving standalone webhook
|
|
127
127
|
events), so the same event never double-fires a brick inside AND outside the
|
|
128
|
-
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{
|
|
128
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Ge as AgentStrategy,Le as CI_ENV_VARS,Co as COMPOSE_KNOWLEDGE,j as CompilationError,we as ContextLoader,de as DEFAULT_OUTPUT_BASE,Nn as EVENTS_FILE,re as Graph,Oe as NODE_DEFAULT_TOOLS,Pn as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,F as Node,ce as OutputParser,xn as RAW_OUTPUT_FILE,On as RESULT_FILE,je as SESSIONS_DIR,Y as SESSION_INFO_FILE,Ue as STOP_REQUEST_FILE,ct as STORE_NAME_REGEX,$n as SchemaTypes,Ie as Timeline,At as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,re as WorkflowGraph,ae as WorkflowState,cn as clearInheritedSessionEnvForFreshRun,Rt as clearSkills,yo as compileGraph,et as dispatchSubgraph,So as extractSteps,To as generateNodeConfigsJson,Io as generateWorkflowCode,un as generateWorkflowSessionId,Ze as getAgentStrategy,Nt as getAllSkills,rt as getNodeImpl,st as getNodeTemplate,it as getResolvedToolDefinitions,te as getSkill,xt as getSkillSource,ke as hasNode,Ot as hasSkill,Dt as invokeAgent,go as listNodeTypes,Pt as listSkillIds,Bt as listStrategies,an as readPinnedSessionPathFromEnv,pn as registerNode,kt as registerSkill,Mt as registerStrategy,Ye as resolveInvocationExtras,Je as resolveInvocationModel,at as resolveNodeTools,dn as resolveWorkflowSession,An as setLogger,sn as shouldTrustInheritedSessionEnv,ln as syncProcessEnvToSession,P as timeline,wo as validateGraphConfig,bo as validateStoreDefs};
|
|
@@ -33,6 +33,8 @@
|
|
|
33
33
|
* error. In-process is never attempted without PROJECT_API_TOKEN — we
|
|
34
34
|
* keep the "no cloud creds = no sub-graphs" invariant from v1.
|
|
35
35
|
*/
|
|
36
|
+
import { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS } from './fetch-deadline.js';
|
|
37
|
+
export { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS };
|
|
36
38
|
/**
|
|
37
39
|
* Dispatch `workflowName` as a child of the currently-running execution.
|
|
38
40
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var L=()=>{},W={debug:L,info:L,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},M=Symbol.for("@zibby/agent-workflow.logger");globalThis[M]||(globalThis[M]={impl:W});var B=globalThis[M];var h={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{mkdirSync as te,existsSync as A,statSync as Y,readdirSync as K,rmSync as ne}from"node:fs";import{spawn as q}from"node:child_process";import{join as T}from"node:path";import{pathToFileURL as re}from"node:url";import{AsyncLocalStorage as oe}from"node:async_hooks";import{AsyncLocalStorage as Q}from"node:async_hooks";var k=new Q;function x(){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 G(e,t){let r=k.getStore()||x(),n=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:r.agent??null,signal:e.signal!==void 0?e.signal:r.signal??null});return k.run(n,t)}var D=new Map,j=new Map,H=new Map;function z(e,t,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");D.set(e,t),j.set(e,"ready"),H.set(e,{...r,cachedAt:Date.now()})}function F(e,t){j.set(e,"failed"),H.set(e,{error:t?.message||String(t),failedAt:Date.now()}),D.delete(e)}function J(e){return j.get(e)==="ready"?D.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function se(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var f=class extends Error{constructor(t,r){super(`in-process sub-graph fallback: ${t}${r?` (${r})`:""}`),this.fallback=!0,this.reason=t,this.detail=r||null,this.name="SubgraphFallback"}};function O(e,t,r,n="timeout",o=null){let s=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(r/1e3)}s (last status: ${n})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return s.code="SUBGRAPH_TIMEOUT",s.subgraphJobId=t,s.subgraphStatus=n,o&&(s.subgraphTransportError=o),s}function ae(e,t=process.env,r=process.uptime()){let n=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(r)&&r>0?r*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(n===null&&a===null)return null;let c=n===null?a:a===null?n:Math.min(n,a);return Math.max(1,c)}function ie(e,t){let r=new AbortController,n=!1,o=null,s=()=>{r.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),t!=null&&!r.signal.aborted&&(o=setTimeout(()=>{n=!0,r.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:r.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var N=new oe,X=Promise.resolve();async function ce(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,c])=>typeof a=="string"&&a&&typeof c=="string"):[];if(r.length===0)return t();let n=N.getStore()===!0,o=null;if(!n){let a=X;X=new Promise(c=>{o=c}),await a}let s=new Map;try{for(let[a,c]of r)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=c;return h.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await N.run(!0,t)}finally{for(let[a,c]of s)c===void 0?delete process.env[a]:process.env[a]=c;o&&o()}}function ue(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!r||!n||!o)throw new f("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:o}}async function le({apiBase:e,authToken:t,body:r}){let n;try{n=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}catch(s){throw new f("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.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(n.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 f("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function _({apiBase:e,authToken:t,payload:r}){try{let n=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});n.ok||h.warn(`[in-process subgraph] finalize returned ${n.status} for ${r.childExecutionId}`)}catch(n){h.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function de(e,t){let r=T(t,".ready"),n=T(t,"graph.mjs");if(A(r)&&A(n))return;te(t,{recursive:!0});let o=T(t,".lock"),s=!1;try{let{openSync:a,closeSync:c}=await import("node:fs"),g=a(o,"wx");c(g),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(A(r)&&A(n))return;await new Promise(c=>setTimeout(c,100))}throw new f("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((g,y)=>{let E=q("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),b=q("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});E.stdout.pipe(b.stdin);let w,p,m=()=>{if(w!==void 0&&p!==void 0){if(w!==0)return y(new Error(`curl exited ${w}`));if(p!==0)return y(new Error(`tar exited ${p}`));g()}};E.on("close",$=>{w=$,m()}),b.on("close",$=>{p=$,m()}),E.on("error",y),b.on("error",y)});let{writeFileSync:a,unlinkSync:c}=await import("node:fs");a(r,"");try{c(o)}catch{}}catch(a){try{let{unlinkSync:c}=await import("node:fs");c(o)}catch{}throw new f("bundle-extract-failed",a.message)}}async function pe(e){let t=T(e,"graph.mjs");if(!A(t))throw new f("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(re(t).href)}catch(o){throw new f("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=r.default||Object.values(r).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new f("entry-class-missing","no buildGraph() class export found");return n}async function V(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=x(),n;try{n=ue()}catch(i){throw i}h.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let o=await le({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:c,sourcesPresignedUrl:g,workflowVersion:y,workflowUuid:E,bundleReady:b,nodeConfigs:w}=o,p=se();if(a&&a!==p)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("runtime-mismatch",`${p} vs ${a}`);if(!b||!c)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new f("no-bundle","workflow bundle not built yet");let m=J(e);if(!m){let i=T(P,`${E}@${y||"0"}`);try{await de(c,i);try{ge()}catch{}}catch(u){throw u.fallback&&await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{m=await pe(i),z(e,m,{workflowUuid:E,version:y,runtimeTag:a,cacheDir:i})}catch(u){throw F(e,u),await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new f("import-failed",u.message)}}let $=Date.now(),C=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,v=w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0,R={...t.input||{},...v?{nodeConfigs:w}:{}},S=ae(t.timeoutMs),l=ie(t.signal,S),d,I;try{d=await ce(C,async()=>{let u=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return G({executionId:s,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(t.parentAgent,R,{signal:l.signal}))}),I=d&&typeof d=="object"&&"state"in d?d.state:d}catch(i){let u=l.timedOut();throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:u?"timeout":"failed",error:u?{message:`aborted at the declared ${Math.round(S/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:i.message,code:i.code||"CHILD_THREW",stack:i.stack},durationMs:Date.now()-$}}),u?O(e,s,S):i}finally{l.dispose()}if(d&&typeof d=="object"&&d.stoppedExternally){let i=l.timedOut();if(await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:i?"timeout":"canceled",finalState:I,durationMs:Date.now()-$}}),i)throw O(e,s,S);let u=new Error(`Sub-graph '${e}' canceled by parent abort`);throw u.code="SUBGRAPH_CANCELED",u.subgraphJobId=s,u}return await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:I,durationMs:Date.now()-$}}),{finalState:I,executionId:s}}function he(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),o;try{o=Y(n)}catch{continue}if(o.isDirectory()){let s;try{s=K(n)}catch{continue}for(let a of s)r.push(T(n,a))}else t+=o.size}return t}function ge({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!A(P))return{evicted:0,freedBytes:0};let t=K(P),r=[],n=0;for(let c of t){let g=T(P,c),y;try{y=Y(g)}catch{continue}let E=y.isDirectory()?he(g):y.size;n+=E,r.push({name:c,full:g,size:E,mtimeMs:y.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((c,g)=>c.mtimeMs-g.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let c of r){if(n-s<=o)break;if(!A(T(c.full,".lock")))try{ne(c.full,{recursive:!0,force:!0}),s+=c.size,a+=1}catch(g){h.debug(`[sub-graph cache] evict skip ${c.name}: ${g.message}`)}}return a>0&&h.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:n-s}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var fe=2e3,ye=600*1e3,be=new Set(["completed","failed","canceled","timeout"]);function we(){let e=process.env.PROGRESS_API_URL;if(!e)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return e.replace(/\/executions\/?$/,"")}function Ie(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function me(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function Ee(){return process.env.EXECUTION_ID||null}function Z(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((r,n)=>r==null?r:r[n],e):e}async function ke(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let r=x();t.parentAgent==null&&r.agent&&(t.parentAgent=r.agent),t.signal==null&&r.signal&&(t.signal=r.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((r.depth||0)>=n)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${r.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:ye;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:l}=await V(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),d=Z(l,t.output);return h.info(`[sub-graph] '${e}' completed in-process`),d}catch(l){if(l instanceof f||l?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${l.reason||"unknown"} \u2014 using HTTP`);else throw l}let s=we(),a=Ie(),c=me(),g=Ee(),y=`${s}/projects/${encodeURIComponent(a)}/workflows/${encodeURIComponent(e)}/trigger`,E={input:t.input||{},...g?{parentExecutionId:g}:{},...t.conversationId?{conversationId:t.conversationId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${g||"<none>"}`);let b=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`},body:JSON.stringify(E)});if(!b.ok){let l=null,d="";try{l=await b.json(),d=l?.error||l?.message||JSON.stringify(l)}catch{d=await b.text().catch(()=>"")}if(b.status===429){let i=l?.quotaInfo||{},u=new Error(`Sub-graph '${e}' blocked by execution quota (${i.used??"?"}/${i.limit??"?"} on plan ${i.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw u.code="SUBGRAPH_QUOTA_EXCEEDED",u.status=429,u.subgraph=e,u.quotaInfo=i,u}if(b.status===400){let i=new Error(`Sub-graph '${e}' rejected input: ${d}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.subgraph=e,i.validationErrors=l?.validationErrors||null,i.missing=l?.missing||null,i}let I=new Error(`Sub-graph '${e}' trigger rejected (${b.status}): ${d}`);throw I.code="SUBGRAPH_TRIGGER_FAILED",I.status=b.status,I.subgraph=e,I}let w=await b.json(),p=w?.data?.jobId||w?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(w).slice(0,200)}`);if(t.async)return h.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:fe,$=`${s}/executions/${encodeURIComponent(p)}`,C=Date.now()+o,v="accepted",R=0,S=null;for(;Date.now()<C;){await new Promise(i=>setTimeout(i,m)),R+=1;let l;try{l=await fetch($,{headers:{Authorization:`Bearer ${c}`}})}catch(i){S=i?.message||String(i),h.warn(`[sub-graph] status poll for ${p} could not reach the API (${S}), will retry`);continue}if(!l.ok){if(l.status>=500){h.warn(`[sub-graph] status poll for ${p} returned ${l.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${l.status}`)}let d;try{d=await l.json()}catch(i){S=i?.message||String(i),h.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${S}), will retry`);continue}let I=d?.data||d?.execution||d;if(v=I?.status||v,be.has(v)){if(v!=="completed"){let U=new Error(`Sub-graph '${e}' (${p}) ended in status '${v}'`);throw U.subgraphJobId=p,U.subgraphStatus=v,U}let i=I?.finalState||I?.state||{},u=Z(i,t.output);return h.info(`[sub-graph] '${e}' (${p}) completed after ${R} polls`),u}}throw O(e,p,o,v,S)}export{ke as dispatchSubgraph};
|
|
1
|
+
var J=()=>{},ae={debug:J,info:J,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k=Symbol.for("@zibby/agent-workflow.logger");globalThis[k]||(globalThis[k]={impl:ae});var G=globalThis[k];var g={debug:(...e)=>G.impl.debug?.(...e),info:(...e)=>G.impl.info?.(...e),warn:(...e)=>G.impl.warn?.(...e),error:(...e)=>G.impl.error?.(...e)};import{mkdirSync as de,existsSync as U,statSync as te,readdirSync as ne,rmSync as pe}from"node:fs";import{spawn as W}from"node:child_process";import{join as O}from"node:path";import{pathToFileURL as he}from"node:url";import{AsyncLocalStorage as ge}from"node:async_hooks";import{AsyncLocalStorage as ie}from"node:async_hooks";var j=new ie;function x(){let e=j.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 q(e,t){let n=j.getStore()||x(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return j.run(r,t)}var F=new Map,z=new Map,X=new Map;function Y(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");F.set(e,t),z.set(e,"ready"),X.set(e,{...n,cachedAt:Date.now()})}function K(e,t){z.set(e,"failed"),X.set(e,{error:t?.message||String(t),failedAt:Date.now()}),F.delete(e)}function V(e){return z.get(e)==="ready"?F.get(e):null}var P=3e4,Z=15e3;function B(e,t,n=process.env){let r=Number(n[e]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):t}function N(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function C(e,t){return N(B(e,t),e)}function _(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}var D=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function fe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var b=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}};function L(e,t,n,r="timeout",o=null){let a=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(n/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return a.code="SUBGRAPH_TIMEOUT",a.subgraphJobId=t,a.subgraphStatus=r,o&&(a.subgraphTransportError=o),a}function ye(e,t=process.env,n=process.uptime()){let r=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),a=Number.isFinite(n)&&n>0?n*1e3:0,s=Number.isFinite(o)&&o>0?o-a:null;if(r===null&&s===null)return null;let i=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,i)}function be(e,t){let n=new AbortController,r=!1,o=null,a=()=>{n.abort(e?.reason)};return e&&(e.aborted?a():e.addEventListener("abort",a,{once:!0})),t!=null&&!n.signal.aborted&&(o=setTimeout(()=>{r=!0,n.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",a)}}}var Q=new ge,ee=Promise.resolve();async function Ie(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(n.length===0)return t();let r=Q.getStore()===!0,o=null;if(!r){let s=ee;ee=new Promise(i=>{o=i}),await s}let a=new Map;try{for(let[s,i]of n)a.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return g.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await Q.run(!0,t)}finally{for(let[s,i]of a)i===void 0?delete process.env[s]:process.env[s]=i;o&&o()}}function Ee(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!r||!o)throw new b("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:o}}async function me({apiBase:e,authToken:t,body:n}){let r=C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal})}catch(s){throw new b(_(s)?"begin-timeout":"network",_(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let a=null;try{a=await o.json()}catch(s){if(_(s))throw new b("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.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(o.status===429){let s=a?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=s,i}if(o.status===400&&a?.validationErrors){let s=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=a.validationErrors,s.missing=a.missing,s}throw new b("begin-status",`begin returned ${o.status}`)}return a?.data||a}async function M({apiBase:e,authToken:t,payload:n}){let r=C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal});o.ok||g.warn(`[in-process subgraph] finalize returned ${o.status} for ${n.childExecutionId}`)}catch(o){g.warn(`[in-process subgraph] finalize ${_(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Te(e,t){let n=O(t,".ready"),r=O(t,"graph.mjs");if(U(n)&&U(r))return;de(t,{recursive:!0});let o=O(t,".lock"),a=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),y=s(o,"wx");i(y),a=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!a){let s=Date.now()+3e4;for(;Date.now()<s;){if(U(n)&&U(r))return;await new Promise(i=>setTimeout(i,100))}throw new b("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,I)=>{let S=Math.ceil(1e4/1e3),R=Math.ceil(B("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),h=W("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(R),e],{stdio:["ignore","pipe","inherit"]}),E=W("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(E.stdin);let d,m,v=()=>{if(d!==void 0&&m!==void 0){if(d!==0)return I(new Error(`curl exited ${d}`));if(m!==0)return I(new Error(`tar exited ${m}`));y()}};h.on("close",$=>{d=$,v()}),E.on("close",$=>{m=$,v()}),h.on("error",I),E.on("error",I)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(n,"");try{i(o)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new b("bundle-extract-failed",s.message)}}async function _e(e){let t=O(e,"graph.mjs");if(!U(t))throw new b("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(he(t).href)}catch(o){throw new b("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new b("entry-class-missing","no buildGraph() class export found");return r}async function re(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=x(),r;try{r=Ee()}catch(p){throw p}g.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await me({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:a,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:y,workflowVersion:I,workflowUuid:S,bundleReady:R,nodeConfigs:h}=o,E=fe();if(s&&s!==E)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("runtime-mismatch",`${E} vs ${s}`);if(!R||!i)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("no-bundle","workflow bundle not built yet");let d=V(e);if(!d){let p=O(D,`${S}@${I||"0"}`);try{await Te(i,p);try{we()}catch{}}catch(c){throw c.fallback&&await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{d=await _e(p),Y(e,d,{workflowUuid:S,version:I,runtimeTag:s,cacheDir:p})}catch(c){throw K(e,c),await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new b("import-failed",c.message)}}let m=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=h&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,w={...t.input||{},...$?{nodeConfigs:h}:{}},A=ye(t.timeoutMs),T=be(t.signal,A),u,l;try{u=await Ie(v,async()=>{let c=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return q({executionId:a,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,w,{signal:T.signal}))}),l=u&&typeof u=="object"&&"state"in u?u.state:u}catch(p){let c=T.timedOut();throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(A/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),c?L(e,a,A):p}finally{T.dispose()}if(u&&typeof u=="object"&&u.stoppedExternally){let p=T.timedOut();if(await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:p?"timeout":"canceled",finalState:l,durationMs:Date.now()-m}}),p)throw L(e,a,A);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=a,c}return await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"completed",finalState:l,durationMs:Date.now()-m}}),{finalState:l,executionId:a}}function Se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),o;try{o=te(r)}catch{continue}if(o.isDirectory()){let a;try{a=ne(r)}catch{continue}for(let s of a)n.push(O(r,s))}else t+=o.size}return t}function we({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!U(D))return{evicted:0,freedBytes:0};let t=ne(D),n=[],r=0;for(let i of t){let y=O(D,i),I;try{I=te(y)}catch{continue}let S=I.isDirectory()?Se(y):I.size;r+=S,n.push({name:i,full:y,size:S,mtimeMs:I.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,y)=>i.mtimeMs-y.mtimeMs);let o=Math.floor(e*.7),a=0,s=0;for(let i of n){if(r-a<=o)break;if(!U(O(i.full,".lock")))try{pe(i.full,{recursive:!0,force:!0}),a+=i.size,s+=1}catch(y){g.debug(`[sub-graph cache] evict skip ${i.name}: ${y.message}`)}}return s>0&&g.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(a/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:a,totalBytes:r-a}}catch(t){return g.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var $e=2e3,Oe=600*1e3,Re=new Set(["completed","failed","canceled","timeout"]);var Ae=()=>C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Me(e){let t=B("SUBGRAPH_POLL_TIMEOUT_MS",15e3),n=Math.max(1,Math.min(t,e-Date.now()));return N(n,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ue(){let e=process.env.PROGRESS_API_URL;if(!e)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return e.replace(/\/executions\/?$/,"")}function ve(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function xe(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function Pe(){return process.env.EXECUTION_ID||null}function oe(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}async function Ze(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=x();t.parentAgent==null&&n.agent&&(t.parentAgent=n.agent),t.signal==null&&n.signal&&(t.signal=n.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:Oe;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{g.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await re(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),l=oe(u,t.output);return g.info(`[sub-graph] '${e}' completed in-process`),l}catch(u){if(u instanceof b||u?.fallback)g.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let a=Ue(),s=ve(),i=xe(),y=Pe(),I=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(e)}/trigger`,S={input:t.input||{},...y?{parentExecutionId:y}:{},...t.conversationId?{conversationId:t.conversationId}:{}};g.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${y||"<none>"}`);let R=Ae(),h;try{h=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(S),signal:R.signal})}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger TIMED OUT ${R.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}if(!h.ok){let u=null,l="";try{u=await h.json(),l=u?.error||u?.message||JSON.stringify(u)}catch{l=await h.text().catch(()=>"")}if(h.status===429){let c=u?.quotaInfo||{},f=new Error(`Sub-graph '${e}' blocked by execution quota (${c.used??"?"}/${c.limit??"?"} on plan ${c.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw f.code="SUBGRAPH_QUOTA_EXCEEDED",f.status=429,f.subgraph=e,f.quotaInfo=c,f}if(h.status===400){let c=new Error(`Sub-graph '${e}' rejected input: ${l}`);throw c.code="SUBGRAPH_INVALID_INPUT",c.status=400,c.subgraph=e,c.validationErrors=u?.validationErrors||null,c.missing=u?.missing||null,c}let p=new Error(`Sub-graph '${e}' trigger rejected (${h.status}): ${l}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=h.status,p.subgraph=e,p}let E;try{E=await h.json()}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger body read TIMED OUT ${R.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}let d=E?.data?.jobId||E?.jobId;if(!d)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(E).slice(0,200)}`);if(t.async)return g.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:e};let m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:$e,v=`${a}/executions/${encodeURIComponent(d)}`,$=Date.now()+o,w="accepted",A=0,T=null;for(;Date.now()<$;){await new Promise(f=>setTimeout(f,m)),A+=1;let u=Me($),l;try{l=await fetch(v,{headers:{Authorization:`Bearer ${i}`},signal:u.signal})}catch(f){T=_(f)?`poll TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} could not reach the API (${T}), will retry`);continue}if(!l.ok){if(l.status>=500){g.warn(`[sub-graph] status poll for ${d} returned ${l.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${l.status}`)}let p;try{p=await l.json()}catch(f){T=_(f)?`poll body read TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} returned an unreadable body (${T}), will retry`);continue}let c=p?.data||p?.execution||p;if(w=c?.status||w,Re.has(w)){if(w!=="completed"){let H=new Error(`Sub-graph '${e}' (${d}) ended in status '${w}'`);throw H.subgraphJobId=d,H.subgraphStatus=w,H}let f=c?.finalState||c?.state||{},se=oe(f,t.output);return g.info(`[sub-graph] '${e}' (${d}) completed after ${A} polls`),se}}throw L(e,d,o,w,T)}export{Z as SUBGRAPH_POLL_TIMEOUT_MS,P as SUBGRAPH_TRIGGER_TIMEOUT_MS,Ze as dispatchSubgraph};
|