@zibby/agent-workflow 0.4.20 → 0.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/code-generator.js +20 -15
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +1 -1
- package/dist/graph-compiler.js +20 -15
- package/dist/graph.js +19 -14
- package/dist/index.js +18 -13
- package/dist/node-registry.js +13 -8
- package/dist/node.js +20 -15
- package/dist/strategy-registry.js +10 -5
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
|
-
var ve=Object.defineProperty;var ot=(r,t)=>()=>(r&&(t=r(r=0)),t);var Dt=(r,t)=>{for(var e in t)ve(r,e,{get:t[e],enumerable:!0})};var Lt,ke,it,_,
|
|
1
|
+
var ve=Object.defineProperty;var ot=(r,t)=>()=>(r&&(t=r(r=0)),t);var Dt=(r,t)=>{for(var e in t)ve(r,e,{get:t[e],enumerable:!0})};var Lt,ke,it,_,V=ot(()=>{Lt=()=>{},ke={debug:Lt,info:Lt,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},it={impl:ke},_={debug:(...r)=>it.impl.debug?.(...r),info:(...r)=>it.impl.info?.(...r),warn:(...r)=>it.impl.warn?.(...r),error:(...r)=>it.impl.error?.(...r)}});var Kt=ot(()=>{});var Vt={};Dt(Vt,{clearSkills:()=>De,getAllSkills:()=>Ce,getSkill:()=>St,hasSkill:()=>Be,listSkillIds:()=>Me,registerSkill:()=>Re});function Re(r){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");z.set(r.id,Object.freeze({...r}))}function St(r){return z.get(r)||null}function Be(r){return z.has(r)}function Ce(){return new Map(z)}function Me(){return Array.from(z.keys())}function De(){z.clear()}var mt,z,yt=ot(()=>{mt=Symbol.for("@zibby/agent-workflow.skills");globalThis[mt]||(globalThis[mt]=new Map);z=globalThis[mt]});var wt={};Dt(wt,{getAgentStrategy:()=>qt,invokeAgent:()=>Ue,listStrategies:()=>je,registerStrategy:()=>Le});function Le(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=U.findIndex(e=>e.getName()===r.getName());t>=0?U[t]=r:U.push(r)}function je(){return U.map(r=>r.getName())}function qt(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let n=U.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}_.debug(`[workflow] agent selection: requested=${o}`);let s=U.find(n=>n.getName()===o);if(!s){let n=U.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${n}`)}if(!s.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${s.getName()}`),s}async function Ue(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},s={...t,state:o},n=qt(s),i=o.config||e.config||{},a=i.models||{},l=e.nodeName&&a[e.nodeName]||null,u=a.default||null,p=i.agent?.[n.name]?.model||null,c=l||u||p||e.model||null,S={...e,model:c,workspace:o.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:i},h=r,b=S.skills||[];if(b.length>0&&!e.skipPromptFragments){let I=b.map(d=>{let f=St(d)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);I.length>0&&(h+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${I.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let E=o._currentNodeConfig?.stores;if(Array.isArray(E)&&E.length>0&&typeof E[0]=="object"){let I=E.length<=8,d=E.map(f=>{let g=f?.id??f?.storeId??"",m=f?.type?` \xB7 ${f.type}`:"",P=(f?.description||"").toString().replace(/\s+/g," ").trim(),T=`- ${g}${m} \xB7 ${P||"(no description)"}`;if(I&&f?.schema&&typeof f.schema=="object"){let B=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);B.length&&(T+=`
|
|
6
|
+
fields: ${B.join(", ")}`)}return T});h+=`
|
|
7
|
+
|
|
8
|
+
AVAILABLE STORES (pick by description; pass the storeId to the store tool):
|
|
9
|
+
${d.join(`
|
|
10
|
+
`)}`}let A=o._currentNodeConfig?.extraPromptInstructions?.trim();return A&&(h+=`
|
|
6
11
|
|
|
7
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
|
|
8
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
9
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
|
|
10
15
|
|
|
11
|
-
${
|
|
12
|
-
`),_.debug(`[workflow] prompt length: ${
|
|
16
|
+
${A}
|
|
17
|
+
`),_.debug(`[workflow] prompt length: ${h.length} chars`),n.invoke(h,S)}var _t,U,It=ot(()=>{Kt();V();yt();_t=Symbol.for("@zibby/agent-workflow.strategies");globalThis[_t]||(globalThis[_t]=[]);U=globalThis[_t]});var Oe=new Set(["__proto__","constructor","prototype"]);function dt(r){if(Oe.has(r))throw new Error(`Invalid state key: "${r}"`)}var st=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){dt(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let o of e)dt(o);this._history.push({...this._state});for(let o of e)this._state[o]=t[o]}append(t,e){dt(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import W from"handlebars";var nt=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of o)try{return this.validate(JSON.parse(s))}catch(n){if(!(n instanceof SyntaxError))throw n}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&s.type){let n=typeof t[o];n!==s.type&&e.push(`Field '${o}' expected ${s.type}, got ${n}`)}if(s.validate&&o in t){let n=s.validate(t[o]);n&&e.push(`Field '${o}': ${n}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
13
18
|
${e.join(`
|
|
14
|
-
`)}`);return t}};
|
|
19
|
+
`)}`);return t}};V();import{writeFileSync as Et,readFileSync as Xt,existsSync as Qt,mkdirSync as We}from"node:fs";import{join as bt,dirname as Fe}from"node:path";import O from"chalk";var xe="__WORKFLOW_GRAPH_LOG__",q=O.gray("\u2502"),Pe=O.gray("\u250C"),jt=O.gray("\u2514"),ft=O.green("\u25C6"),Ut=O.hex("#c084fc")("\u25C6"),Wt=O.hex("#2dd4bf")("\u25C6"),ht=O.red("\u25C6"),Ft=`${q} `,Gt=2;function Ht(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Jt(r,t){return(e,o,s)=>{if(typeof e!="string")return r(e,o,s);let n=process.stdout.columns||120,i="";for(let a=0;a<e.length;a++){let l=e[a];t.lineStart&&(i+=Ft,t.col=Gt,t.lineStart=!1),l===`
|
|
15
20
|
`?(i+=l,t.lineStart=!0,t.col=0,t.inEsc=!1):l==="\x1B"?(t.inEsc=!0,i+=l):t.inEsc?(i+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(t.inEsc=!1)):(t.col++,i+=l,t.col>=n&&(i+=`
|
|
16
21
|
${Ft}`,t.col=Gt))}return r(i,o,s)}}var gt=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 t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Jt(this._origStdoutWrite,t),process.stderr.write=Jt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
17
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
@@ -20,18 +25,18 @@ ${Ft}`,t.col=Gt))}return r(i,o,s)}}var gt=class{constructor(){this._currentNode=
|
|
|
20
25
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
21
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
22
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
23
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(ft,t):process.stdout.write.bind(process.stdout)(`${
|
|
24
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Ut,t):process.stdout.write.bind(process.stdout)(`${
|
|
25
|
-
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Wt,e):process.stdout.write.bind(process.stdout)(`${
|
|
26
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,O.red(t)):process.stdout.write.bind(process.stdout)(`${
|
|
27
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?O.dim(` ${Ht(o)}`):"";this._rawWrite(`${jt} ${O.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?O.dim(` ${Ht(s)}`):"";this._rawWrite(`${ht} ${O.red(e)}`),this._rawWrite(`${jt} ${O.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},k=new gt;var at=".zibby/output",Yt="sessions",Z=".session-info.json",Zt=".zibby-stop";var Ne={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory"},Tr=Object.freeze([Ne.CODEBASE_MEMORY]),zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",r=>Number(r)+1);W.helpers.json||W.registerHelper("json",r=>JSON.stringify(r,null,2));W.helpers.eq||W.registerHelper("eq",(r,t)=>r===t);var L=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return _.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let n;typeof this.prompt=="function"?n=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(o())):n=this.prompt;let i=s("_skillHints");i&&(n=`${i}
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(ft,t):process.stdout.write.bind(process.stdout)(`${q} ${ft} ${t}
|
|
29
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Ut,t):process.stdout.write.bind(process.stdout)(`${q} ${Ut} ${t}
|
|
30
|
+
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Wt,e):process.stdout.write.bind(process.stdout)(`${q} ${Wt} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,O.red(t)):process.stdout.write.bind(process.stdout)(`${q} ${ht} ${O.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?O.dim(` ${Ht(o)}`):"";this._rawWrite(`${jt} ${O.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?O.dim(` ${Ht(s)}`):"";this._rawWrite(`${ht} ${O.red(e)}`),this._rawWrite(`${jt} ${O.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},k=new gt;var at=".zibby/output",Yt="sessions",Z=".session-info.json",Zt=".zibby-stop";var Ne={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store"},Tr=Object.freeze([Ne.CODEBASE_MEMORY]),zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",r=>Number(r)+1);W.helpers.json||W.registerHelper("json",r=>JSON.stringify(r,null,2));W.helpers.eq||W.registerHelper("eq",(r,t)=>r===t);var L=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return _.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let n;typeof this.prompt=="function"?n=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(o())):n=this.prompt;let i=s("_skillHints");i&&(n=`${i}
|
|
28
33
|
|
|
29
|
-
${n}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let c=bt(u,Z);if(Qt(c)){let f=JSON.parse(Xt(c,"utf-8"));f.currentNode=this.name,Et(c,JSON.stringify(f,null,2),"utf-8")}let g=bt(u,"..",Z);if(Qt(g))try{let f=JSON.parse(Xt(g,"utf-8"));f.currentNode=this.name,Et(g,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let g=o().config||{},f=g.agents||{},E=this.config.agent??f[this.name]??null,b={state:o()};E&&(b.preferredAgent=E);let T={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:g,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let d=await I(n,b,T),y,h;if(typeof d=="string"?(y=d,h=null):d.structured?(y=d.raw||JSON.stringify(d.structured,null,2),h=d.structured):(y=d.raw||JSON.stringify(d,null,2),h=d.extracted||null),u)try{let m=bt(u,this.name,"raw_stream_output.txt");We(Fe(m),{recursive:!0}),Et(m,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&h){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(h,null,2)}`);let m=h;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),h)}catch(B){_.warn(`[workflow] onComplete hook failed: ${B.message}`)}return{success:!0,output:m,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:y}),raw:y}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(y);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:y}}return{success:!0,output:y,raw:y}}catch(g){p=g,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},X=class extends L{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};q();q();import{mkdirSync as Je,existsSync as G,statSync as ie,readdirSync as ae,rmSync as Ye}from"node:fs";import{spawn as ne}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ze}from"node:url";import{AsyncLocalStorage as Ge}from"node:async_hooks";var $t=new Ge;function Q(){let r=$t.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function te(r,t){let e=$t.getStore()||Q(),o=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return $t.run(o,t)}var Tt=new Map,At=new Map,ee=new Map;function re(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),At.set(r,"ready"),ee.set(r,{...e,cachedAt:Date.now()})}function oe(r,t){At.set(r,"failed"),ee.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function se(r){return At.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var x=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}};function Ke(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!o||!s)throw new x("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function qe({apiBase:r,authToken:t,body:e}){let o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new x("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let n=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(o.status===429){let n=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=n,i}if(o.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new x("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function F({apiBase:r,authToken:t,payload:e}){try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function Ve(r,t){let e=j(t,".ready"),o=j(t,"graph.mjs");if(G(e)&&G(o))return;Je(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),l=i(s,"wx");a(l),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(G(e)&&G(o))return;await new Promise(a=>setTimeout(a,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let g,f,E=()=>{if(g!==void 0&&f!==void 0){if(g!==0)return u(new Error(`curl exited ${g}`));if(f!==0)return u(new Error(`tar exited ${f}`));l()}};p.on("close",b=>{g=b,E()}),c.on("close",b=>{f=b,E()}),p.on("error",u),c.on("error",u)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(e,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new x("bundle-extract-failed",i.message)}}async function Xe(r){let t=j(r,"graph.mjs");if(!G(t))throw new x("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ze(t).href)}catch(s){throw new x("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new x("entry-class-missing","no buildGraph() class export found");return o}async function ce(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),o;try{o=Ke()}catch(h){throw h}_.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await qe({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,g=ze();if(i&&i!==g)throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${g} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new x("runtime-mismatch",`${g} vs ${i}`);if(!c||!a)throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new x("no-bundle","workflow bundle not built yet");let f=se(r);if(!f){let h=j(ct,`${p}@${u||"0"}`);try{await Ve(a,h);try{tr()}catch{}}catch(m){throw m.fallback&&await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason}}}),m}try{f=await Xe(h),re(r,f,{workflowUuid:p,version:u,runtimeTag:i,cacheDir:h})}catch(m){throw oe(r,m),await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason||"IMPORT_FAILED"}}}),m.fallback?m:new x("import-failed",m.message)}}let E=Date.now(),T=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),I={...t.input||{}},d,y;try{d=await te({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>T.run(t.parentAgent,I,{signal:t.signal})),y=d&&typeof d=="object"&&"state"in d?d.state:d}catch(h){throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-E}}),h}if(d&&typeof d=="object"&&d.stoppedExternally){await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:y,durationMs:Date.now()-E}});let h=new Error(`Sub-graph '${r}' canceled by parent abort`);throw h.code="SUBGRAPH_CANCELED",h.subgraphJobId=n,h}return await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:y,durationMs:Date.now()-E}}),{finalState:y,executionId:n}}function Qe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ie(o)}catch{continue}if(s.isDirectory()){let n;try{n=ae(o)}catch{continue}for(let i of n)e.push(j(o,i))}else t+=s.size}return t}function tr({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!G(ct))return{evicted:0,freedBytes:0};let t=ae(ct),e=[],o=0;for(let a of t){let l=j(ct,a),u;try{u=ie(l)}catch{continue}let p=u.isDirectory()?Qe(l):u.size;o+=p,e.push({name:a,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let a of e){if(o-n<=s)break;if(!G(j(a.full,".lock")))try{Ye(a.full,{recursive:!0,force:!0}),n+=a.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:o-n}}catch(t){return _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var er=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","timeout"]);function sr(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function nr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function ir(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ar(){return process.env.EXECUTION_ID||null}function le(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],r):r}async function ue(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=o)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{_.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:h}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(h,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(h){if(h instanceof x||h?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${h.reason||"unknown"} \u2014 using HTTP`);else throw h}let s=sr(),n=nr(),i=ir(),a=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(u)});if(!p.ok){let h=null,m="";try{h=await p.json(),m=h?.error||h?.message||JSON.stringify(h)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let A=h?.quotaInfo||{},M=new Error(`Sub-graph '${r}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=A,M}if(p.status===400){let A=new Error(`Sub-graph '${r}' rejected input: ${m}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=r,A.validationErrors=h?.validationErrors||null,A.missing=h?.missing||null,A}let B=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${m}`);throw B.code="SUBGRAPH_TRIGGER_FAILED",B.status=p.status,B.subgraph=r,B}let c=await p.json(),g=c?.data?.jobId||c?.jobId;if(!g)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${g} (not waiting)`),{jobId:g,status:"accepted",workflow:r};let f=Number.isFinite(t.timeoutMs)?t.timeoutMs:rr,E=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:er,b=`${s}/executions/${encodeURIComponent(g)}`,T=Date.now()+f,I="accepted",d=0;for(;Date.now()<T;){await new Promise(A=>setTimeout(A,E)),d+=1;let h=await fetch(b,{headers:{Authorization:`Bearer ${i}`}});if(!h.ok){if(h.status>=500){_.warn(`[sub-graph] status poll for ${g} returned ${h.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${g}: ${h.status}`)}let m=await h.json(),B=m?.data||m?.execution||m;if(I=B?.status||I,or.has(I)){if(I!=="completed"){let S=new Error(`Sub-graph '${r}' (${g}) ended in status '${I}'`);throw S.subgraphJobId=g,S.subgraphStatus=I,S}let A=B?.finalState||B?.state||{},M=le(A,t.output);return _.info(`[sub-graph] '${r}' (${g}) completed after ${d} polls`),M}}let y=new Error(`Sub-graph '${r}' (${g}) timed out after ${Math.round(f/1e3)}s (last status: ${I})`);throw y.subgraphJobId=g,y.subgraphStatus=I,y}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as vt,dirname as de}from"node:path";var lt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=de(vt(e,t));for(let l of n){let u=await this.findAndMergeContextFiles(l,a,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let u=vt(e,l);pe(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(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=vt(n,t);if(pe(i))try{s.unshift(await this.loadFile(i))}catch(l){console.warn(`[workflow] could not load ${t} from ${i}: ${l.message}`)}let a=de(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
34
|
+
${n}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let c=bt(u,Z);if(Qt(c)){let h=JSON.parse(Xt(c,"utf-8"));h.currentNode=this.name,Et(c,JSON.stringify(h,null,2),"utf-8")}let S=bt(u,"..",Z);if(Qt(S))try{let h=JSON.parse(Xt(S,"utf-8"));h.currentNode=this.name,Et(S,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let S=o().config||{},h=S.agents||{},b=this.config.agent??h[this.name]??null,E={state:o()};b&&(E.preferredAgent=b);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let d=await I(n,E,A),f,g;if(typeof d=="string"?(f=d,g=null):d.structured?(f=d.raw||JSON.stringify(d.structured,null,2),g=d.structured):(f=d.raw||JSON.stringify(d,null,2),g=d.extracted||null),u)try{let m=bt(u,this.name,"raw_stream_output.txt");We(Fe(m),{recursive:!0}),Et(m,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let m=g;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),g)}catch(P){_.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:m,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(f);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:f}}return{success:!0,output:f,raw:f}}catch(S){p=S,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},X=class extends L{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};V();V();import{mkdirSync as Je,existsSync as G,statSync as ie,readdirSync as ae,rmSync as Ye}from"node:fs";import{spawn as ne}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ze}from"node:url";import{AsyncLocalStorage as Ge}from"node:async_hooks";var $t=new Ge;function Q(){let r=$t.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function te(r,t){let e=$t.getStore()||Q(),o=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return $t.run(o,t)}var Tt=new Map,At=new Map,ee=new Map;function re(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),At.set(r,"ready"),ee.set(r,{...e,cachedAt:Date.now()})}function oe(r,t){At.set(r,"failed"),ee.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function se(r){return At.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var x=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}};function Ke(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!o||!s)throw new x("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Ve({apiBase:r,authToken:t,body:e}){let o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new x("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let n=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(o.status===429){let n=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=n,i}if(o.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new x("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function F({apiBase:r,authToken:t,payload:e}){try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function qe(r,t){let e=j(t,".ready"),o=j(t,"graph.mjs");if(G(e)&&G(o))return;Je(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),l=i(s,"wx");a(l),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(G(e)&&G(o))return;await new Promise(a=>setTimeout(a,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let S,h,b=()=>{if(S!==void 0&&h!==void 0){if(S!==0)return u(new Error(`curl exited ${S}`));if(h!==0)return u(new Error(`tar exited ${h}`));l()}};p.on("close",E=>{S=E,b()}),c.on("close",E=>{h=E,b()}),p.on("error",u),c.on("error",u)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(e,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new x("bundle-extract-failed",i.message)}}async function Xe(r){let t=j(r,"graph.mjs");if(!G(t))throw new x("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ze(t).href)}catch(s){throw new x("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new x("entry-class-missing","no buildGraph() class export found");return o}async function ce(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),o;try{o=Ke()}catch(g){throw g}_.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await Ve({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,S=ze();if(i&&i!==S)throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new x("runtime-mismatch",`${S} vs ${i}`);if(!c||!a)throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new x("no-bundle","workflow bundle not built yet");let h=se(r);if(!h){let g=j(ct,`${p}@${u||"0"}`);try{await qe(a,g);try{tr()}catch{}}catch(m){throw m.fallback&&await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason}}}),m}try{h=await Xe(g),re(r,h,{workflowUuid:p,version:u,runtimeTag:i,cacheDir:g})}catch(m){throw oe(r,m),await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason||"IMPORT_FAILED"}}}),m.fallback?m:new x("import-failed",m.message)}}let b=Date.now(),A=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),I={...t.input||{}},d,f;try{d=await te({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>A.run(t.parentAgent,I,{signal:t.signal})),f=d&&typeof d=="object"&&"state"in d?d.state:d}catch(g){throw await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-b}}),g}if(d&&typeof d=="object"&&d.stoppedExternally){await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:f,durationMs:Date.now()-b}});let g=new Error(`Sub-graph '${r}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=n,g}return await F({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:f,durationMs:Date.now()-b}}),{finalState:f,executionId:n}}function Qe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ie(o)}catch{continue}if(s.isDirectory()){let n;try{n=ae(o)}catch{continue}for(let i of n)e.push(j(o,i))}else t+=s.size}return t}function tr({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!G(ct))return{evicted:0,freedBytes:0};let t=ae(ct),e=[],o=0;for(let a of t){let l=j(ct,a),u;try{u=ie(l)}catch{continue}let p=u.isDirectory()?Qe(l):u.size;o+=p,e.push({name:a,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let a of e){if(o-n<=s)break;if(!G(j(a.full,".lock")))try{Ye(a.full,{recursive:!0,force:!0}),n+=a.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:o-n}}catch(t){return _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var er=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","timeout"]);function sr(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function nr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function ir(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ar(){return process.env.EXECUTION_ID||null}function le(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],r):r}async function ue(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=o)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{_.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(g,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(g){if(g instanceof x||g?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=sr(),n=nr(),i=ir(),a=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(u)});if(!p.ok){let g=null,m="";try{g=await p.json(),m=g?.error||g?.message||JSON.stringify(g)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let T=g?.quotaInfo||{},B=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=r,B.quotaInfo=T,B}if(p.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${m}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=g?.validationErrors||null,T.missing=g?.missing||null,T}let P=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${m}`);throw P.code="SUBGRAPH_TRIGGER_FAILED",P.status=p.status,P.subgraph=r,P}let c=await p.json(),S=c?.data?.jobId||c?.jobId;if(!S)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${S} (not waiting)`),{jobId:S,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:rr,b=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:er,E=`${s}/executions/${encodeURIComponent(S)}`,A=Date.now()+h,I="accepted",d=0;for(;Date.now()<A;){await new Promise(T=>setTimeout(T,b)),d+=1;let g=await fetch(E,{headers:{Authorization:`Bearer ${i}`}});if(!g.ok){if(g.status>=500){_.warn(`[sub-graph] status poll for ${S} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${S}: ${g.status}`)}let m=await g.json(),P=m?.data||m?.execution||m;if(I=P?.status||I,or.has(I)){if(I!=="completed"){let y=new Error(`Sub-graph '${r}' (${S}) ended in status '${I}'`);throw y.subgraphJobId=S,y.subgraphStatus=I,y}let T=P?.finalState||P?.state||{},B=le(T,t.output);return _.info(`[sub-graph] '${r}' (${S}) completed after ${d} polls`),B}}let f=new Error(`Sub-graph '${r}' (${S}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw f.subgraphJobId=S,f.subgraphStatus=I,f}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as vt,dirname as de}from"node:path";var lt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=de(vt(e,t));for(let l of n){let u=await this.findAndMergeContextFiles(l,a,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let u=vt(e,l);pe(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(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=vt(n,t);if(pe(i))try{s.unshift(await this.loadFile(i))}catch(l){console.warn(`[workflow] could not load ${t} from ${i}: ${l.message}`)}let a=de(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
30
35
|
|
|
31
36
|
---
|
|
32
37
|
|
|
33
38
|
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=cr(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(t).href);return s.default||s}return e}};import{mkdirSync as me,existsSync as Ot,writeFileSync as fe,unlinkSync as lr}from"node:fs";import{join as H,resolve as Se}from"node:path";import{config as ur}from"dotenv";import{zodToJsonSchema as he}from"zod-to-json-schema";import{z as ut}from"zod";import pr from"handlebars";function dr({traceFrom:r,sessionId:t,sessionPath:e,idSource:o,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${i} sessionId=${t} source=${o} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let p=(new Error("session trace").stack||"").split(`
|
|
34
39
|
`).slice(2,14).join(`
|
|
35
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
36
|
-
${p}`)}}function fr(){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 hr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Se(String(t).trim())}catch{return String(t).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Sr(r={}){let t=zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function yr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Se(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,i="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Sr(t),i="generated")}n=n??Date.now();let p=t.paths?.output||at;s=H(r,p,Yt,a)}let l=!Ot(s);return l&&me(s,{recursive:!0}),(l||i!=="initialState.sessionPath")&&dr({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:l}),mr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var ge=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,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(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},ue(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},a=new L(i);return a.name=t,this.nodes.set(t,a),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof L?e:new L(e);return s.name=t,this.nodes.set(t,s),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new X({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,n){let i=o;for(let a=t.length-1;a>=0;a--){let l=t[a],u=i;i=()=>l(e,u,s,n)}return i()}serialize(){let t=[],e={};for(let[p,c]of this.nodes){let g=this.nodeTypeMap.get(p)||(c instanceof X?"decision":p);t.push({id:p,type:g,data:{nodeType:g,label:p}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let E=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;E&&(f.description=E);let b=this.nodePrompts.get(p);if(b)f.prompt=b;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(f.prompt=y,f.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof ut?.toJSONSchema=="function")try{y=ut.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=he(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let T=(this.resolvedToolsMap||{})[p];T?.toolIds&&(f.tools=T.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(f.skills=[...I]);let d=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;d&&d.length>0&&(f.stores=[...d]),Object.keys(f).length>0&&(e[p]=f)}let o=[];for(let[p,c]of this.edges)if(typeof c=="string")o.push({source:p,target:c});else if(c.conditional){let g=this.conditionalCodeMap.get(p)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{};for(let b of f){let T={source:p,target:b,data:{conditionalCode:g}};E[b]&&(T.label=E[b]),o.push(T)}}let s=p=>{if(!p)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(p)}catch{}try{return he(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let n=0;for(let p of o)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:p,target:c})}let i=this._runtimeSchema(),a=s(i||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:a,inputSchema:l,contextSchema:u}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(o))!==null;){let u=i[2]!==void 0?i[2]:i[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(e&&typeof e=="object")for(let u of Object.keys(e))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,p;for(;(p=u.exec(o))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},n=t.required||[];for(let[i,a]of Object.entries(s)){let l=e?`${e}.${i}`:i;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!n.includes(i)}),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(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,a=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();ur({path:H(i,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let w=H(i,".zibby.config.js");Ot(w)&&(a=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=e.agentType;if(!l){let w=a?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let w=p.safeParse(e);if(!w.success){let P=w.error.issues.map(N=>`${N.path.join(".")}: ${N.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(N=>console.error(` - ${N}`)),new Error(`State validation failed: ${P.join(", ")}`)}k.step("State validated against schema")}let c=hr(),g=e.sessionPath||c;g||gr();let{sessionPath:f,sessionTimestamp:E,sessionId:b}=yr({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:g,sessionTimestamp:e.sessionTimestamp}});k.step(`Session ${b}`);let T=await lt.loadContext(e.specPath||"",i,u);Object.keys(T).length>0&&k.step(`Context loaded: ${Object.keys(T).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let d=new st({...e,config:a,agentType:l,outputPath:I,sessionPath:f,sessionTimestamp:E,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),y=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:h}=await Promise.resolve().then(()=>(yt(),qt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},B=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),A=w=>{for(let P of B)if(P.id===w)return P;return h(w)},M=new Set;for(let[,w]of this.nodes)for(let P of w.config?.skills||[])M.add(P);for(let w of M){let P=A(w);if(typeof P?.middleware=="function")try{let N=await P.middleware();typeof N=="function"&&y.set(w,N)}catch{}}let S=this.entryPoint,tt=[],kt=a?.recursionLimit??100,ye=0;try{for(;S&&S!=="END";){if(++ye>kt)throw new Error(`Workflow exceeded recursion limit (${kt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=H(f,Zt);if(Ot(P)){try{lr(P)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
37
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};let
|
|
41
|
+
${p}`)}}function fr(){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 hr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Se(String(t).trim())}catch{return String(t).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Sr(r={}){let t=zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function yr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Se(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,i="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Sr(t),i="generated")}n=n??Date.now();let p=t.paths?.output||at;s=H(r,p,Yt,a)}let l=!Ot(s);return l&&me(s,{recursive:!0}),(l||i!=="initialState.sessionPath")&&dr({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:l}),mr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var ge=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,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(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},ue(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},a=new L(i);return a.name=t,this.nodes.set(t,a),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof L?e:new L(e);return s.name=t,this.nodes.set(t,s),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new X({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,n){let i=o;for(let a=t.length-1;a>=0;a--){let l=t[a],u=i;i=()=>l(e,u,s,n)}return i()}serialize(){let t=[],e={};for(let[p,c]of this.nodes){let S=this.nodeTypeMap.get(p)||(c instanceof X?"decision":p);t.push({id:p,type:S,data:{nodeType:S,label:p}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(h.description=b);let E=this.nodePrompts.get(p);if(E)h.prompt=E;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(h.prompt=f,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof ut?.toJSONSchema=="function")try{f=ut.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=he(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let A=(this.resolvedToolsMap||{})[p];A?.toolIds&&(h.tools=A.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(h.skills=[...I]);let d=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;d&&d.length>0&&(h.stores=[...d]),Object.keys(h).length>0&&(e[p]=h)}let o=[];for(let[p,c]of this.edges)if(typeof c=="string")o.push({source:p,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(p)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{};for(let E of h){let A={source:p,target:E,data:{conditionalCode:S}};b[E]&&(A.label=b[E]),o.push(A)}}let s=p=>{if(!p)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(p)}catch{}try{return he(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let n=0;for(let p of o)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:p,target:c})}let i=this._runtimeSchema(),a=s(i||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:a,inputSchema:l,contextSchema:u}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(o))!==null;){let u=i[2]!==void 0?i[2]:i[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(e&&typeof e=="object")for(let u of Object.keys(e))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,p;for(;(p=u.exec(o))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},n=t.required||[];for(let[i,a]of Object.entries(s)){let l=e?`${e}.${i}`:i;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!n.includes(i)}),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(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,a=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();ur({path:H(i,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let w=H(i,".zibby.config.js");Ot(w)&&(a=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=e.agentType;if(!l){let w=a?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let w=p.safeParse(e);if(!w.success){let N=w.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}k.step("State validated against schema")}let c=hr(),S=e.sessionPath||c;S||gr();let{sessionPath:h,sessionTimestamp:b,sessionId:E}=yr({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:S,sessionTimestamp:e.sessionTimestamp}});k.step(`Session ${E}`);let A=await lt.loadContext(e.specPath||"",i,u);Object.keys(A).length>0&&k.step(`Context loaded: ${Object.keys(A).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let d=new st({...e,config:a,agentType:l,outputPath:I,sessionPath:h,sessionTimestamp:b,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:g}=await Promise.resolve().then(()=>(yt(),Vt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},P=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),T=w=>{for(let N of P)if(N.id===w)return N;return g(w)},B=new Set;for(let[,w]of this.nodes)for(let N of w.config?.skills||[])B.add(N);for(let w of B){let N=T(w);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(w,R)}catch{}}let y=this.entryPoint,tt=[],kt=a?.recursionLimit??100,ye=0;try{for(;y&&y!=="END";){if(++ye>kt)throw new Error(`Workflow exceeded recursion limit (${kt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(h,Zt);if(Ot(N)){try{lr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};let R=this.nodes.get(y);if(!R)throw new Error(`Node '${y}' not found in graph`);let xt=JSON.stringify({sessionPath:h,sessionTimestamp:b,currentNode:y,createdAt:new Date().toISOString(),config:d.get("config")}),_e=H(h,Z);fe(_e,xt,"utf-8");let Pt=d.get("config")?.paths?.output||at,we=H(i,Pt,Z);me(H(i,Pt),{recursive:!0});try{fe(we,xt,"utf-8")}catch{}let Nt=e.onPipelineProgress;if(typeof Nt=="function")try{Nt({cwd:i,sessionPath:h,sessionId:E,outputBase:d.get("config")?.paths?.output||at,currentNode:y})}catch{}let Ie=(this.resolvedToolsMap||{})[y]||null;d.set("_currentNodeTools",Ie);let Ee=d.get("nodeConfigs")||{};d.set("_currentNodeConfig",Ee[y]||{}),k.nodeStart(y);let Rt=Date.now(),et=this.nodePrompts.get(y);if(!this._invokeAgent){let v=await Promise.resolve().then(()=>(It(),wt));this._invokeAgent=v.invokeAgent}let be=this._invokeAgent,pt={},$e=R.config?.skills||[];for(let v of $e){let C=T(v);if(typeof C?.invokeAgentOptions=="function")try{let $=C.invokeAgentOptions(d.getAll(),{agentType:d.get("agentType"),nodeName:y});$&&typeof $=="object"&&(pt={...pt,...$})}catch($){console.warn(`[graph] skill '${v}' invokeAgentOptions threw: ${$.message}`)}}let Bt=async(v,C,$={})=>{let M=be(v,C,{...pt,...$,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((J,Y)=>{let D=()=>{setTimeout(()=>{let K=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${n}ms`);K.name="AbortError",Y(K)},n)};s.signal.addEventListener("abort",D,{once:!0})})])},Te=async(v={},C={})=>{let $=C.prompt||"";if(et){let M=this._compiledPrompts.get(y);M||(M=pr.compile(et,{noEscape:!0}),this._compiledPrompts.set(y,M));try{$=M(v)}catch(J){throw console.error(`\u274C Template rendering failed for node '${y}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!$)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return Bt($,{state:d.getAll(),images:C.images||[]},{model:C.model||d.get("model"),workspace:d.get("workspace"),schema:C.schema,...C,signal:s.signal})},Ct=d.getAll(),Ae=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let v of Ae)Object.prototype.hasOwnProperty.call(Ct,v)&&console.warn(`[workflow] node "${y}": state key "${v}" is shadowed by the engine context prop; read it via context.state.get('${v}')`);let Mt={...Ct,state:d,invokeAgent:Te,_coreInvokeAgent:Bt,agent:t,nodeId:y,promptTemplate:et,getPromptTemplate:()=>et};try{let v=(R.config?.skills||[]).map(D=>f.get(D)).filter(Boolean),C=[...this.middleware,...v],$;C.length>0?$=await this._composeMiddleware(C,y,async()=>R.execute(Mt,d),d.getAll(),d):$=await R.execute(Mt,d);let M=Date.now()-Rt;if(tt.push({node:y,success:$.success,duration:M,timestamp:new Date().toISOString()}),!$.success){if(s.signal.aborted)return k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};d.append("errors",{node:y,error:$.error});let D=R.config?.retries||0,K=`${y}_retries`,rt=d.getAll()[K]||0;if(rt<D){k.stepInfo(`Retrying (attempt ${rt+1}/${D})`),d.update({[K]:rt+1,[`${y}_raw`]:$.raw});continue}throw k.nodeFailed(y,$.error,{duration:M}),new Error(`Node '${y}' failed after ${rt} attempts: ${$.error}`)}d.update({[y]:$.output});let J=this._summarizeNodeOutput(y,$.output);k.nodeComplete(y,{duration:M,details:J});let Y=this.edges.get(y);if(!Y)y="END";else if(Y.conditional){let D=Y.routes(d.getAll());k.route(y,D),y=D}else y=Y}catch(v){throw k.isInsideNode&&k.nodeFailed(y,v.message,{duration:Date.now()-Rt}),d.set("failed",!0),d.set("failedAt",y),v}}k.graphComplete();let w={success:!0,state:d.getAll(),executionLog:tt};return t&&typeof t.onComplete=="function"&&await t.onComplete(w),w}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(w){console.warn(`[workflow] agent.cleanup() failed: ${w.message}`)}}}};export{ge as WorkflowGraph,gr as clearInheritedSessionEnvForFreshRun,Sr as generateWorkflowSessionId,hr as readPinnedSessionPathFromEnv,yr as resolveWorkflowSession,fr as shouldTrustInheritedSessionEnv,mr as syncProcessEnvToSession};
|