@zibby/agent-workflow 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.js +21 -21
- package/dist/in-process-subgraph.d.ts +75 -0
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +31 -31
- package/dist/sub-graph-executor.d.ts +7 -1
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph-compiler.js
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
var
|
|
1
|
+
var qt=Object.defineProperty;var ve=(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 ue=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(o){throw t=[o],o}};var qe=(n,e)=>{for(var t in e)qt(n,t,{get:e[t],enumerable:!0})};var Ke,Vt,fe,_,F=ue(()=>{Ke=()=>{},Vt={debug:Ke,info:Ke,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},fe={impl:Vt},_={debug:(...n)=>fe.impl.debug?.(...n),info:(...n)=>fe.impl.info?.(...n),warn:(...n)=>fe.impl.warn?.(...n),error:(...n)=>fe.impl.error?.(...n)}});var at=ue(()=>{});var ct={};qe(ct,{clearSkills:()=>sn,getAllSkills:()=>on,getSkill:()=>oe,getSkillSource:()=>nn,hasSkill:()=>tn,listSkillIds:()=>rn,registerSkill:()=>en});function en(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,r=n.id;if(G.has(r)&&!o){let s=ne.get(r);if(!(s===t)){let a=s||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${r}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}G.set(r,Object.freeze({...n})),t===void 0?ne.delete(r):ne.set(r,t)}function oe(n){return G.get(n)||null}function tn(n){return G.has(n)}function nn(n){return ne.get(n)||null}function on(){return new Map(G)}function rn(){return Array.from(G.keys())}function sn(){G.clear(),ne.clear()}var Oe,Pe,G,ne,ge=ue(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills"),Pe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Oe]||(globalThis[Oe]=new Map);globalThis[Pe]||(globalThis[Pe]=new Map);G=globalThis[Oe],ne=globalThis[Pe]});var re={};qe(re,{getAgentStrategy:()=>dt,invokeAgent:()=>ln,listStrategies:()=>cn,registerStrategy:()=>an,resolveInvocationExtras:()=>ut,resolveInvocationModel:()=>lt});function an(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===n.getName());e>=0?H[e]=n:H.push(n)}function cn(){return H.map(n=>n.getName())}function lt({config:n={},options:e={},strategyName:t,envModel:o,nodeConfigModel:r}={}){let s=n.models||{},i=typeof r=="string"&&r.trim()&&r.trim()!=="auto"?r.trim():null,a=e.nodeName&&s[e.nodeName]||null,u=s.default||null,d=n.agent?.[t]?.model||null,y=(typeof o=="string"?o.trim():"")||null;return i||a||u||d||e.model||y||null}function ut({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 dt(n={}){let{state:e={},preferredAgent:t=null}=n,o=t||e.agentType||process.env.AGENT_TYPE;if(!o){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}_.debug(`[workflow] agent selection: requested=${o}`);let r=H.find(s=>s.getName()===o);if(!r){let s=H.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${s}`)}if(!r.canHandle(n))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${r.getName()}`),r}async function ln(n,e={},t={}){let o=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},r={...e,state:o},s=dt(r),i=o.config||t.config||{},a=o._currentNodeConfig||{},u=typeof a.agent=="string"?a.agent.trim():"",d=!u||u===s.name?a.model:null,y=lt({config:i,options:t,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:d}),l={...t,model:y,...ut({options:t,stateView:o,context:e}),config:i},c=n,g=l.skills||[];if(g.length>0&&!t.skipPromptFragments){let A=t.connectedIntegrations;if(!A){let p=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof p=="string"&&p.trim()!==""){A={};for(let E of p.split(",").map($=>$.trim()).filter(Boolean))A[E]=!0}}let T=p=>{let E=p&&p.requiresIntegration;return!E||!A?!0:(Array.isArray(E)?E:[E]).some(v=>A[v]===!0)},f=s.name==="assistant",h=p=>p?.inProcessOnly!==!0||f,I=g.map(p=>{let E=oe(p);if(!T(E)||!h(E))return null;let $=E?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);I.length>0&&(c+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${I.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let m=o._currentNodeConfig?.stores;if(Array.isArray(m)&&m.length>0&&typeof m[0]=="object"){let A=m.length<=8,T=m.map(f=>{let h=f?.id??f?.storeId??"",I=(f?.name??"").toString().trim()||h,p=f?.type?` \xB7 ${f.type}`:"",E=(f?.description||"").toString().replace(/\s+/g," ").trim(),$=`- ${I} \xB7 ${E||"(no description)"}${p} (id: ${h})`;if(A&&f?.schema&&typeof f.schema=="object"){let v=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);v.length&&($+=`
|
|
6
|
+
fields: ${v.join(", ")}`)}return $});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 b=o._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(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
|
+
${b}
|
|
17
|
+
`),_.debug(`[workflow] prompt length: ${c.length} chars`),s.invoke(c,l)}var Ne,H,se=ue(()=>{at();F();ge();Ne=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ne]||(globalThis[Ne]=[]);H=globalThis[Ne]});var Kt=new Set(["__proto__","constructor","prototype"]);function Te(n){if(Kt.has(n))throw new Error(`Invalid state key: "${n}"`)}var de=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){Te(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let o of t)Te(o);this._history.push({...this._state});for(let o of t)this._state[o]=e[o]}append(e,t){Te(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 J from"handlebars";var pe=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(r=>r[0]);for(let r of o)try{return this.validate(JSON.parse(r))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[o,r]of Object.entries(this.schema)){if(r.required&&!(o in e)&&t.push(`Missing required field: ${o}`),o in e&&r.type){let s=typeof e[o];s!==r.type&&t.push(`Field '${o}' expected ${r.type}, got ${s}`)}if(r.validate&&o in e){let s=r.validate(e[o]);s&&t.push(`Field '${o}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};F();import{writeFileSync as Ce,readFileSync as pt,existsSync as ft,mkdirSync as
|
|
20
|
-
`?(
|
|
21
|
-
${et}`,e.col=tt))}return n(
|
|
19
|
+
`)}`);return e}};F();import{writeFileSync as Ce,readFileSync as pt,existsSync as ft,mkdirSync as un}from"node:fs";import{join as Re,dirname as dn}from"node:path";import O from"chalk";var Xt="__WORKFLOW_GRAPH_LOG__",te=O.gray("\u2502"),Qt=O.gray("\u250C"),Ve=O.gray("\u2514"),Ae=O.green("\u25C6"),Xe=O.hex("#c084fc")("\u25C6"),Qe=O.hex("#2dd4bf")("\u25C6"),ke=O.red("\u25C6"),et=`${te} `,tt=2;function nt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function ot(n,e){return(t,o,r)=>{if(typeof t!="string")return n(t,o,r);let s=process.stdout.columns||120,i="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(i+=et,e.col=tt,e.lineStart=!1),u===`
|
|
20
|
+
`?(i+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,i+=u):e.inEsc?(i+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,i+=u,e.col>=s&&(i+=`
|
|
21
|
+
${et}`,e.col=tt))}return n(i,o,r)}}var xe=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=ot(this._origStdoutWrite,e),process.stderr.write=ot(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=`${Xt}${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(Xe,e):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(Ae,e):process.stdout.write.bind(process.stdout)(`${te} ${Ae} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Xe,e):process.stdout.write.bind(process.stdout)(`${te} ${Xe} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=O.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Qe,t):process.stdout.write.bind(process.stdout)(`${te} ${Qe} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(ke,O.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${ke} ${O.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Qt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:o,details:r}=t;if(r)for(let i of r)this._rawWrite(`${Ae} ${i}`);let s=o?O.dim(` ${nt(o)}`):"";this._rawWrite(`${Ve} ${O.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,o={}){this._stopIntercepting();let{duration:r}=o,s=r?O.dim(` ${nt(r)}`):"";this._rawWrite(`${ke} ${O.red(t)}`),this._rawWrite(`${Ve} ${O.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(O.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},P=new xe;var he=".zibby/output",rt="sessions",K=".session-info.json",st=".zibby-stop";var oo=Object.freeze(["codebase-memory","code-scan","artifact"]),it=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",n=>Number(n)+1);J.helpers.json||J.registerHelper("json",n=>JSON.stringify(n,null,2));J.helpers.eq||J.registerHelper("eq",(n,e)=>n===e);var U=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 pe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return _.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>t&&typeof t.getAll=="function"?t.getAll():e,r=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return _.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let i=r("_skillHints");i&&(s=`${i}
|
|
33
33
|
|
|
34
|
-
${i}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(ft(l)){let S=JSON.parse(pt(l,"utf-8"));S.currentNode=this.name,Ce(l,JSON.stringify(S,null,2),"utf-8")}let c=Re(d,"..",K);if(ft(c))try{let S=JSON.parse(pt(c,"utf-8"));S.currentNode=this.name,Ce(c,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},S=c.agents||{},g=this.config.agent??S[this.name]??null,E={state:o()};g&&(E.preferredAgent=g);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(ie(),se))).invokeAgent);let f=await $(i,E,A),m,w;if(typeof f=="string"?(m=f,w=null):f.structured?(m=f.raw||JSON.stringify(f.structured,null,2),w=f.structured):(m=f.raw||JSON.stringify(f,null,2),w=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");ln(un(p),{recursive:!0}),Ce(p,typeof m=="string"?m:JSON.stringify(m),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),w)}catch(b){I.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:p,raw:m}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:m}),raw:m}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(m);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:m}}return{success:!0,output:m,raw:m}}catch(c){h=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};F();F();import{mkdirSync as fn,existsSync as Y,statSync as Et,readdirSync as $t,rmSync as hn}from"node:fs";import{spawn as _t}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as gn}from"node:url";import{AsyncLocalStorage as mn}from"node:async_hooks";import{AsyncLocalStorage as dn}from"node:async_hooks";var ae=new dn;function V(){let n=ae.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 ht(n,e){let t=ae.getStore()||V(),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 ae.run(o,e)}function gt(n,e,t){let o=ae.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ae.run(r,t)}var Be=new Map,Me=new Map,mt=new Map;function yt(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");Be.set(n,e),Me.set(n,"ready"),mt.set(n,{...t,cachedAt:Date.now()})}function St(n,e){Me.set(n,"failed"),mt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Be.delete(n)}function wt(n){return Me.get(n)==="ready"?Be.get(n):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function yn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},bt=new mn,It=Promise.resolve();async function Sn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(t.length===0)return e();let o=bt.getStore()===!0,r=null;if(!o){let s=It;It=new Promise(a=>{r=a}),await s}let i=new Map;try{for(let[s,a]of t)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await bt.run(!0,e)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;r&&r()}}function wn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function _n({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 N("network",`begin fetch failed: ${i.message}`)}let r=null;try{r=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=r?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(o.status===400&&r?.validationErrors){let i=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=r.validationErrors,i.missing=r.missing,i}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({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||I.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){I.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function bn(n,e){let t=U(e,".ready"),o=U(e,"graph.mjs");if(Y(t)&&Y(o))return;fn(e,{recursive:!0});let r=U(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(r,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=_t("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=_t("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,S,g=()=>{if(c!==void 0&&S!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(S!==0)return d(new Error(`tar exited ${S}`));u()}};h.on("close",E=>{c=E,g()}),l.on("close",E=>{S=E,g()}),h.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(t,"");try{a(r)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",s.message)}}async function In(n){let e=U(n,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(gn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function vt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=wn()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await _n({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=r,S=yn();if(s&&s!==S)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("runtime-mismatch",`${S} vs ${s}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let g=wt(n);if(!g){let p=U(ye,`${h}@${d||"0"}`);try{await bn(a,p);try{$n()}catch{}}catch(b){throw b.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{g=await In(p),yt(n,g,{workflowUuid:h,version:d,runtimeTag:s,cacheDir:p})}catch(b){throw St(n,b),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let E=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,$=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...$?{nodeConfigs:c}:{}},m,w;try{m=await Sn(A,async()=>{let b=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return ht({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>b.run(e.parentAgent,f,{signal:e.signal}))}),w=m&&typeof m=="object"&&"state"in m?m.state:m}catch(p){throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-E}}),p}if(m&&typeof m=="object"&&m.stoppedExternally){await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:w,durationMs:Date.now()-E}});let p=new Error(`Sub-graph '${n}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-E}}),{finalState:w,executionId:i}}function En(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=Et(o)}catch{continue}if(r.isDirectory()){let i;try{i=$t(o)}catch{continue}for(let s of i)t.push(U(o,s))}else e+=r.size}return e}function $n({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=$t(ye),t=[],o=0;for(let a of e){let u=U(ye,a),d;try{d=Et(u)}catch{continue}let h=d.isDirectory()?En(u):d.size;o+=h,t.push({name:a,full:u,size:h,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),i=0,s=0;for(let a of t){if(o-i<=r)break;if(!Y(U(a.full,".lock")))try{hn(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:o-i}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var vn=2e3,An=600*1e3,Tn=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 xn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function On(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Pn(){return process.env.EXECUTION_ID||null}function At(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 Tt(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();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.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:w}=await vt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=At(w,e.output);return I.info(`[sub-graph] '${n}' completed in-process`),p}catch(w){if(w instanceof N||w?.fallback)I.info(`[sub-graph] in-process fallback for '${n}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let r=kn(),i=xn(),s=On(),a=Pn(),u=`${r}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!h.ok){let w=null,p="";try{w=await h.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let v=w?.quotaInfo||{},P=new Error(`Sub-graph '${n}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw P.code="SUBGRAPH_QUOTA_EXCEEDED",P.status=429,P.subgraph=n,P.quotaInfo=v,P}if(h.status===400){let v=new Error(`Sub-graph '${n}' rejected input: ${p}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=n,v.validationErrors=w?.validationErrors||null,v.missing=w?.missing||null,v}let b=new Error(`Sub-graph '${n}' trigger rejected (${h.status}): ${p}`);throw b.code="SUBGRAPH_TRIGGER_FAILED",b.status=h.status,b.subgraph=n,b}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:n};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:An,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:vn,E=`${r}/executions/${encodeURIComponent(c)}`,A=Date.now()+S,$="accepted",f=0;for(;Date.now()<A;){await new Promise(v=>setTimeout(v,g)),f+=1;let w=await fetch(E,{headers:{Authorization:`Bearer ${s}`}});if(!w.ok){if(w.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),b=p?.data||p?.execution||p;if($=b?.status||$,Tn.has($)){if($!=="completed"){let X=new Error(`Sub-graph '${n}' (${c}) ended in status '${$}'`);throw X.subgraphJobId=c,X.subgraphStatus=$,X}let v=b?.finalState||b?.state||{},P=At(v,e.output);return I.info(`[sub-graph] '${n}' (${c}) completed after ${f} polls`),P}}let m=new Error(`Sub-graph '${n}' (${c}) timed out after ${Math.round(S/1e3)}s (last status: ${$})`);throw m.subgraphJobId=c,m.subgraphStatus=$,m}import{existsSync as kt,readFileSync as Nn}from"node:fs";import{join as je,dirname as xt}from"node:path";var Se=class{static async loadContext(e,t,o={}){let r={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(je(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();r[h]=d}}}let s=o.discovery||{};for(let[a,u]of Object.entries(s))try{let d=je(t,u);kt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],i=t;for(;i.startsWith(o);){let s=je(i,e);if(kt(s))try{r.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let a=xt(i);if(a===i)break;i=a}return r.length===0?null:r.every(s=>typeof s=="string")?r.join(`
|
|
34
|
+
${s}`);let a=o(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Re(d,K);if(ft(l)){let g=JSON.parse(pt(l,"utf-8"));g.currentNode=this.name,Ce(l,JSON.stringify(g,null,2),"utf-8")}let c=Re(d,"..",K);if(ft(c))try{let g=JSON.parse(pt(c,"utf-8"));g.currentNode=this.name,Ce(c,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(l){_.debug(`[workflow] could not update session info: ${l.message}`)}let y=null;for(let l=0;l<=this.retries;l++)try{_.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=o().config||{},g=c.agents||{},m=this.config.agent??g[this.name]??null,b={state:o()};m&&(b.preferredAgent=m);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},T=e?._coreInvokeAgent;T||(T=(await Promise.resolve().then(()=>(se(),re))).invokeAgent);let f=await T(s,b,A),h,I;if(typeof f=="string"?(h=f,I=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),I=f.structured):(h=f.raw||JSON.stringify(f,null,2),I=f.extracted||null),d)try{let p=Re(d,this.name,"raw_stream_output.txt");un(dn(p),{recursive:!0}),Ce(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){_.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&I){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(I,null,2)}`);let p=I;if(typeof this.onComplete=="function")try{p=await this.onComplete(o(),I)}catch(E){_.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),P.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(c){y=c,l<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:y.message,raw:null}}};F();F();import{mkdirSync as hn,existsSync as Y,statSync as Et,readdirSync as $t,rmSync as gn}from"node:fs";import{spawn as _t}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as mn}from"node:url";import{AsyncLocalStorage as yn}from"node:async_hooks";import{AsyncLocalStorage as pn}from"node:async_hooks";var ie=new pn;function V(){let n=ie.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 ht(n,e){let t=ie.getStore()||V(),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 ie.run(o,e)}function gt(n,e,t){let o=ie.getStore()||V(),r=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return ie.run(r,t)}var Me=new Map,Be=new Map,mt=new Map;function yt(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");Me.set(n,e),Be.set(n,"ready"),mt.set(n,{...t,cachedAt:Date.now()})}function wt(n,e){Be.set(n,"failed"),mt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Me.delete(n)}function St(n){return Be.get(n)==="ready"?Me.get(n):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function wn(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function ye(n,e,t,o="timeout"){let r=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`);return r.code="SUBGRAPH_TIMEOUT",r.subgraphJobId=e,r.subgraphStatus=o,r}function Sn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,r=Number(e&&e.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(t)&&t>0?t*1e3:0,i=Number.isFinite(r)&&r>0?r-s:null;if(o===null&&i===null)return null;let a=o===null?i:i===null?o:Math.min(o,i);return Math.max(1,a)}function _n(n,e){let t=new AbortController,o=!1,r=null,s=()=>{t.abort(n?.reason)};return n&&(n.aborted?s():n.addEventListener("abort",s,{once:!0})),e!=null&&!t.signal.aborted&&(r=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof r.unref=="function"&&r.unref()),{signal:t.signal,timedOut:()=>o,dispose(){r&&(clearTimeout(r),r=null),n&&n.removeEventListener("abort",s)}}}var bt=new yn,It=Promise.resolve();async function bn(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([i,a])=>typeof i=="string"&&i&&typeof a=="string"):[];if(t.length===0)return e();let o=bt.getStore()===!0,r=null;if(!o){let i=It;It=new Promise(a=>{r=a}),await i}let s=new Map;try{for(let[i,a]of t)s.set(i,Object.prototype.hasOwnProperty.call(process.env,i)?process.env[i]:void 0),process.env[i]=a;return _.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await bt.run(!0,e)}finally{for(let[i,a]of s)a===void 0?delete process.env[i]:process.env[i]=a;r&&r()}}function In(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,r=process.env.PROJECT_API_TOKEN;if(!t||!o||!r)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:r}}async function En({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(s){throw new N("network",`begin fetch failed: ${s.message}`)}let r=null;try{r=await o.json()}catch{}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=r?.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&&r?.validationErrors){let s=new Error(`Sub-graph rejected input: ${r?.error||r?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=r.validationErrors,s.missing=r.missing,s}throw new N("begin-status",`begin returned ${o.status}`)}return r?.data||r}async function z({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 $n(n,e){let t=W(e,".ready"),o=W(e,"graph.mjs");if(Y(t)&&Y(o))return;hn(e,{recursive:!0});let r=W(e,".lock"),s=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),u=i(r,"wx");a(u),s=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!s){let i=Date.now()+3e4;for(;Date.now()<i;){if(Y(t)&&Y(o))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let y=_t("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),l=_t("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});y.stdout.pipe(l.stdin);let c,g,m=()=>{if(c!==void 0&&g!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(g!==0)return d(new Error(`tar exited ${g}`));u()}};y.on("close",b=>{c=b,m()}),l.on("close",b=>{g=b,m()}),y.on("error",d),l.on("error",d)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(t,"");try{a(r)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(r)}catch{}throw new N("bundle-extract-failed",i.message)}}async function vn(n){let e=W(n,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(mn(e).href)}catch(r){throw new N("import-failed",`${r?.code||r?.name||"unknown"}: ${r.message}`)}let o=t.default||Object.values(t).find(r=>typeof r=="function"&&r.prototype?.buildGraph);if(!o)throw new N("entry-class-missing","no buildGraph() class export found");return o}async function vt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=V(),o;try{o=In()}catch($){throw $}_.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let r=await En({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:y,bundleReady:l,nodeConfigs:c}=r,g=wn();if(i&&i!==g)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("runtime-mismatch",`${g} vs ${i}`);if(!l||!a)throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,discard:!0}}),new N("no-bundle","workflow bundle not built yet");let m=St(n);if(!m){let $=W(me,`${y}@${d||"0"}`);try{await $n(a,$);try{An()}catch{}}catch(v){throw v.fallback&&await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{m=await vn($),yt(n,m,{workflowUuid:y,version:d,runtimeTag:i,cacheDir:$})}catch(v){throw wt(n,v),await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new N("import-failed",v.message)}}let b=Date.now(),A=r.env&&typeof r.env=="object"&&!Array.isArray(r.env)?r.env:null,T=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...T?{nodeConfigs:c}:{}},h=Sn(e.timeoutMs),I=_n(e.signal,h),p,E;try{p=await bn(A,async()=>{let v=await(typeof m=="function"&&m.prototype?.buildGraph?new m:m).buildGraph();return ht({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:I.signal}))}),E=p&&typeof p=="object"&&"state"in p?p.state:p}catch($){let v=I.timedOut();throw await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:v?"timeout":"failed",error:v?{message:`aborted at the declared ${Math.round(h/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:$.message,code:$.code||"CHILD_THREW",stack:$.stack},durationMs:Date.now()-b}}),v?ye(n,s,h):$}finally{I.dispose()}if(p&&typeof p=="object"&&p.stoppedExternally){let $=I.timedOut();if(await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:$?"timeout":"canceled",finalState:E,durationMs:Date.now()-b}}),$)throw ye(n,s,h);let v=new Error(`Sub-graph '${n}' canceled by parent abort`);throw v.code="SUBGRAPH_CANCELED",v.subgraphJobId=s,v}return await z({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:s,status:"completed",finalState:E,durationMs:Date.now()-b}}),{finalState:E,executionId:s}}function Tn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),r;try{r=Et(o)}catch{continue}if(r.isDirectory()){let s;try{s=$t(o)}catch{continue}for(let i of s)t.push(W(o,i))}else e+=r.size}return e}function An({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=$t(me),t=[],o=0;for(let a of e){let u=W(me,a),d;try{d=Et(u)}catch{continue}let y=d.isDirectory()?Tn(u):d.size;o+=y,t.push({name:a,full:u,size:y,mtimeMs:d.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let r=Math.floor(n*.7),s=0,i=0;for(let a of t){if(o-s<=r)break;if(!Y(W(a.full,".lock")))try{gn(a.full,{recursive:!0,force:!0}),s+=a.size,i+=1}catch(u){_.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:s,totalBytes:o-s}}catch(e){return _.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var kn=2e3,xn=600*1e3,On=new Set(["completed","failed","canceled","timeout"]);function Pn(){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 Nn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Cn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Rn(){return process.env.EXECUTION_ID||null}function Tt(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 At(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=V();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 r=Number.isFinite(e.timeoutMs)?e.timeoutMs:xn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{_.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:h}=await vt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:r}),I=Tt(h,e.output);return _.info(`[sub-graph] '${n}' completed in-process`),I}catch(h){if(h instanceof N||h?.fallback)_.info(`[sub-graph] in-process fallback for '${n}': ${h.reason||"unknown"} \u2014 using HTTP`);else throw h}let s=Pn(),i=Nn(),a=Cn(),u=Rn(),d=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(n)}/trigger`,y={input:e.input||{},...u?{parentExecutionId:u}:{},...e.conversationId?{conversationId:e.conversationId}:{}};_.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${u||"<none>"}`);let l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(y)});if(!l.ok){let h=null,I="";try{h=await l.json(),I=h?.error||h?.message||JSON.stringify(h)}catch{I=await l.text().catch(()=>"")}if(l.status===429){let E=h?.quotaInfo||{},$=new Error(`Sub-graph '${n}' blocked by execution quota (${E.used??"?"}/${E.limit??"?"} on plan ${E.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw $.code="SUBGRAPH_QUOTA_EXCEEDED",$.status=429,$.subgraph=n,$.quotaInfo=E,$}if(l.status===400){let E=new Error(`Sub-graph '${n}' rejected input: ${I}`);throw E.code="SUBGRAPH_INVALID_INPUT",E.status=400,E.subgraph=n,E.validationErrors=h?.validationErrors||null,E.missing=h?.missing||null,E}let p=new Error(`Sub-graph '${n}' trigger rejected (${l.status}): ${I}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=l.status,p.subgraph=n,p}let c=await l.json(),g=c?.data?.jobId||c?.jobId;if(!g)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=${g} (not waiting)`),{jobId:g,status:"accepted",workflow:n};let m=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:kn,b=`${s}/executions/${encodeURIComponent(g)}`,A=Date.now()+r,T="accepted",f=0;for(;Date.now()<A;){await new Promise(E=>setTimeout(E,m)),f+=1;let h=await fetch(b,{headers:{Authorization:`Bearer ${a}`}});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 I=await h.json(),p=I?.data||I?.execution||I;if(T=p?.status||T,On.has(T)){if(T!=="completed"){let v=new Error(`Sub-graph '${n}' (${g}) ended in status '${T}'`);throw v.subgraphJobId=g,v.subgraphStatus=T,v}let E=p?.finalState||p?.state||{},$=Tt(E,e.output);return _.info(`[sub-graph] '${n}' (${g}) completed after ${f} polls`),$}}throw ye(n,g,r,T)}import{existsSync as kt,readFileSync as Mn}from"node:fs";import{join as je,dirname as xt}from"node:path";var we=class{static async loadContext(e,t,o={}){let r={},s=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=xt(je(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let y=u.replace(/\.[^.]+$/,"").toLowerCase();r[y]=d}}}let i=o.discovery||{};for(let[a,u]of Object.entries(i))try{let d=je(t,u);kt(d)&&(r[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return r}static async findAndMergeContextFiles(e,t,o){let r=[],s=t;for(;s.startsWith(o);){let i=je(s,e);if(kt(i))try{r.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${e} from ${i}: ${u.message}`)}let a=xt(s);if(a===s)break;s=a}return r.length===0?null:r.every(i=>typeof i=="string")?r.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):r.every(
|
|
38
|
+
`):r.every(i=>typeof i=="object")?Object.assign({},...r):r[r.length-1]}static async loadFile(e){let t=Mn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),r=await import(o(e).href);return r.default||r}return t}};import{mkdirSync as Nt,existsSync as De,writeFileSync as Ot,unlinkSync as Bn}from"node:fs";import{join as Z,resolve as Ct}from"node:path";import{config as jn}from"dotenv";import{zodToJsonSchema as Pt}from"zod-to-json-schema";import{z as Se}from"zod";import Dn from"handlebars";function Ln({traceFrom:n,sessionId:e,sessionPath:t,idSource:o,mkdirFresh:r}){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=${n} pid=${process.pid} ppid=${i} sessionId=${e} source=${o} mkdir=${r?"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
|
-
${h}`)}}function jn(){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 Dn(){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 Ct(String(e).trim())}catch{return String(e).trim()}}function Ln(){jn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Wn({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=it.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Fn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,i=t.sessionTimestamp,s="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Ct(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,s="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Un(e),s="generated")}i=i??Date.now();let h=e.paths?.output||ge;r=Z(n,h,rt,a)}let u=!De(r);return u&&Nt(r,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Mn({traceFrom:o,sessionId:a,sessionPath:r,idSource:s,mkdirFresh:u}),Wn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:i}}var _e=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 W)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(h):s.input&&typeof s.input=="object"?l=s.input:l={},Tt(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new W(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof W)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof W?t:new W(r?{...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 r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). 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 s of this._simpleTargets(i)){if(!s||s==="END")continue;let a=t.get(s)||0;a===1?e.add(`${i}->${s}`):a===0&&o(s)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[i]of this.edges)for(let s of this._simpleTargets(i))!s||s==="END"||e.has(`${i}->${s}`)||r.set(s,(r.get(s)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,i){let s=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=s;s=()=>u(t,d,r,i)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let S=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:S,data:{nodeType:S,label:l}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.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&&(g.description=E);let A=this.nodePrompts.get(l);if(A)g.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(g.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Pt(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[l];$?.toolIds&&(g.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(g.skills=[...f]);let m=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;m&&m.length>0&&(g.plugins=m.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[l]=g)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let S of c)o.push({source:l,target:S});else if(c.conditional){let S=this.conditionalCodeMap.get(l)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),E=c.labels||{},A=this.nodes.get(l),$=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!$){let m=`${l}__branch`;e.push({id:m,type:"decision",data:{nodeType:"decision",label:m}}),o.push({source:l,target:m}),f=m}for(let m of g){let w={source:f,target:m,data:{conditionalCode:S}};E[m]&&(w.label=E[m]),o.push(w)}}let r=l=>{if(!l)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(l)}catch{}try{return Pt(l,{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 l of o)if(l.target==="END"){i+=1;let c=`END__${i}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let s=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),h=r(this.contextSchema);return{nodes:s,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),i=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&i.has(l.target)&&(s.get(l.source).push(l.target),i.set(l.target,i.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>i.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,S)=>o.get(c)-o.get(S)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,S)=>o.get(c)-o.get(S))[0];a.add(l),u.delete(l),h.push(r.get(l));for(let c of s.get(l)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(o))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(o))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(r)){let u=t?`${t}.${s}`:s;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}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[r,i]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${r}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(d=>d?.passed===!0).length,u=i.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${r}: ${s} 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(_){let y=new Error(`agent.normalizeInput() rejected the trigger input: ${_?.message||_}`);throw y.cause=_,y.code=_?.code||"NORMALIZE_INPUT_FAILED",y}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();Rn({path:Z(s,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=Z(s,".zibby.config.js");De(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let _=a?.agent;_?.provider?u=_.provider:_?.gemini?u="gemini":_?.claude?u="claude":_?.cursor?u="cursor":_?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let _=h.safeParse(t);if(!_.success){let y=_.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),y.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${y.join(", ")}`)}O.step("State validated against schema")}let l=Dn(),c=t.sessionPath||l;c||Ln();let{sessionPath:S,sessionTimestamp:g,sessionId:E}=Fn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${E}`);let A=await Se.loadContext(t.specPath||"",s,d);Object.keys(A).length>0&&O.step(`Context loaded: ${Object.keys(A).join(", ")}`);let $=t.outputPath;!$&&t.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new pe({...t,config:a,agentType:u,outputPath:$,sessionPath:S,sessionTimestamp:g,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),m=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(me(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},b=Object.values(p).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),v=_=>{for(let y of b)if(y.id===_)return y;return w(_)},P=new Set;for(let[,_]of this.nodes)for(let y of _.config?.skills||[])P.add(y);for(let _ of P){let y=v(_);if(typeof y?.middleware=="function")try{let B=await y.middleware();typeof B=="function"&&m.set(_,B)}catch{}}let{backEdges:X,joinDegree:Dt}=this._analyzeFlow(),Ie=new Map,Q=[],Ee=(_,y,B)=>{if(!_||_==="END")return;let D=Dt.get(_)||0;if(B&&D>1&&!X.has(`${y}->${_}`)){let ee=(Ie.get(_)||0)+1;if(ee<D){Ie.set(_,ee);return}Ie.set(_,0)}Q.includes(_)||Q.push(_)};this.entryPoint&&Q.push(this.entryPoint);let ce=[],Fe=a?.recursionLimit??100,Lt=0;try{for(;Q.length>0;){let y=Q.pop();if(!y||y==="END")continue;if(++Lt>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=Z(S,st);if(De(B)){try{Cn(B)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
43
|
-
${
|
|
41
|
+
${y}`)}}function Un(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function Wn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ct(String(e).trim())}catch{return String(e).trim()}}function Fn(){Un()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Gn({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 Hn(n={}){let e=it.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,r=n.paths?.sessionPrefix;return r?`${r}_${o}`:o}function Jn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let r=t.sessionPath,s=t.sessionTimestamp,i="initialState.sessionPath";if(!r&&process.env.ZIBBY_SESSION_PATH)try{let d=Ct(String(process.env.ZIBBY_SESSION_PATH));d&&(r=d,i="ZIBBY_SESSION_PATH")}catch{}let a;if(r)a=String(r).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,i="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,i="config.sessionId"):(a=Hn(e),i="generated")}s=s??Date.now();let y=e.paths?.output||he;r=Z(n,y,rt,a)}let u=!De(r);return u&&Nt(r,{recursive:!0}),(u||i!=="initialState.sessionPath")&&Ln({traceFrom:o,sessionId:a,sessionPath:r,idSource:i,mkdirFresh:u}),Gn({sessionPath:r,sessionId:a}),{sessionPath:r,sessionId:a,sessionTimestamp:s}}var _e=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 U)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let i=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:i.workflow,retries:i.retries,onComplete:i.onComplete,execute:async d=>{let y=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof i.input=="function"?l=i.input(y):i.input&&typeof i.input=="object"?l=i.input:l={},At(i.workflow,{input:l,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(y):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:y?._signal,parentAgent:d?.agent})}},u=new U(a);return u.name=e,this.nodes.set(e,u),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let r=!(t instanceof U)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof U?t:new U(r?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),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 r=this.edges.get(e);return r!==void 0&&!r.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(r)?r.join(", "):r}). 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=s=>{t.set(s,1);for(let i of this._simpleTargets(s)){if(!i||i==="END")continue;let a=t.get(i)||0;a===1?e.add(`${s}->${i}`):a===0&&o(i)}t.set(s,2)};this.entryPoint&&o(this.entryPoint);let r=new Map;for(let[s]of this.edges)for(let i of this._simpleTargets(s))!i||i==="END"||e.has(`${s}->${i}`)||r.set(i,(r.get(i)||0)+1);return{backEdges:e,joinDegree:r}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,r,s){let i=o;for(let a=e.length-1;a>=0;a--){let u=e[a],d=i;i=()=>u(t,d,r,s)}return i()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let g=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:g,data:{nodeType:g,label:l}});let m={};c._isCustomCode&&typeof c.execute=="function"&&(m.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&&(m.description=b);let A=this.nodePrompts.get(l);if(A)m.prompt=A;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(m.prompt=p,m.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(m.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(m.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(m.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof Se?.toJSONSchema=="function")try{p=Se.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Pt(c.outputSchema,{target:"openApi3"})}catch{}m.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else m.outputSchema={schema:c.outputSchema};let T=(this.resolvedToolsMap||{})[l];T?.toolIds&&(m.tools=T.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(m.skills=[...f]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(m.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let I=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;I&&I.length>0&&(m.stores=I.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(m).length>0&&(t[l]=m)}let o=[];for(let[l,c]of this.edges)if(typeof c=="string")o.push({source:l,target:c});else if(Array.isArray(c))for(let g of c)o.push({source:l,target:g});else if(c.conditional){let g=this.conditionalCodeMap.get(l)||c.routes.toString(),m=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{},A=this.nodes.get(l),T=A?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!A,f=l;if(!T){let h=`${l}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),o.push({source:l,target:h}),f=h}for(let h of m){let I={source:f,target:h,data:{conditionalCode:g}};b[h]&&(I.label=b[h]),o.push(I)}}let r=l=>{if(!l)return null;if(typeof Se?.toJSONSchema=="function")try{return Se.toJSONSchema(l)}catch{}try{return Pt(l,{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 s=0;for(let l of o)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:l,target:c})}let i=this._topoOrderNodes(e,o),a=this._runtimeSchema(),u=r(a||this.stateSchema),d=r(this.inputSchema),y=r(this.contextSchema);return{nodes:i,edges:o,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:y}}_topoOrderNodes(e,t){let o=new Map(e.map((l,c)=>[l.id,c])),r=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),i=new Map(e.map(l=>[l.id,[]]));for(let l of t)i.has(l.source)&&s.has(l.target)&&(i.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let a=new Set,u=new Set(o.keys()),d=[...u].filter(l=>s.get(l)===0),y=[];for(;y.length<e.length;){let l;if(d.length>0){if(d.sort((c,g)=>o.get(c)-o.get(g)),l=d.shift(),a.has(l))continue}else l=[...u].sort((c,g)=>o.get(c)-o.get(g))[0];a.add(l),u.delete(l),y.push(r.get(l));for(let c of i.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return y}_inferConditionalTargets(e,t){let o=e.toString(),r=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=s.exec(o))!==null;){let d=i[2]!==void 0?i[2]:i[3];d!==void 0&&d!==""&&r.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let u=new Set;for(let d of r)a.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,y;for(;(y=d.exec(o))!==null;)u.add(y[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let r=e.$ref.replace("#/definitions/","");o=e.definitions[r]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],r=e.properties||{},s=e.required||[];for(let[i,a]of Object.entries(r)){let u=t?`${t}.${i}`:i;o.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!s.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${u}[]`))}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[r,s]of Object.entries(t))if(!(r==="success"||r==="raw"||r==="nextNode")){if(typeof s=="string"&&s.length<=80)o.push(`${r}: ${s}`);else if(Array.isArray(s)){let i=s.length,a=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);o.push(u?`${r}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${r}: ${i} 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(S){let w=new Error(`agent.normalizeInput() rejected the trigger input: ${S?.message||S}`);throw w.cause=S,w.code=S?.code||"NORMALIZE_INPUT_FAILED",w}let r=new AbortController;o.signal&&(o.signal.aborted?r.abort():o.signal.addEventListener("abort",()=>r.abort(),{once:!0}));let s=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,i=t.cwd||process.cwd();jn({path:Z(i,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let S=Z(i,".zibby.config.js");De(S)&&(a=(await import(S)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let S=a?.agent;S?.provider?u=S.provider:S?.gemini?u="gemini":S?.claude?u="claude":S?.cursor?u="cursor":S?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},y=this._runtimeSchema();if(y){let S=y.safeParse(t);if(!S.success){let w=S.error.issues.map(M=>`${M.path.join(".")}: ${M.message}`);throw console.error("\u274C Initial state validation failed:"),w.forEach(M=>console.error(` - ${M}`)),new Error(`State validation failed: ${w.join(", ")}`)}P.step("State validated against schema")}let l=Wn(),c=t.sessionPath||l;c||Fn();let{sessionPath:g,sessionTimestamp:m,sessionId:b}=Jn({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});P.step(`Session ${b}`);let A=await we.loadContext(t.specPath||"",i,d);Object.keys(A).length>0&&P.step(`Context loaded: ${Object.keys(A).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 f=new de({...t,config:a,agentType:u,outputPath:T,sessionPath:g,sessionTimestamp:m,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:r.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:I}=await Promise.resolve().then(()=>(ge(),ct)),p=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(p).filter(S=>S&&typeof S=="object"&&typeof S.id=="string"),$=S=>{for(let w of E)if(w.id===S)return w;return I(S)},v=new Set;for(let[,S]of this.nodes)for(let w of S.config?.skills||[])v.add(w);for(let S of v){let w=$(S);if(typeof w?.middleware=="function")try{let M=await w.middleware();typeof M=="function"&&h.set(S,M)}catch{}}let{backEdges:Dt,joinDegree:Lt}=this._analyzeFlow(),Ie=new Map,X=[],Ee=(S,w,M)=>{if(!S||S==="END")return;let D=Lt.get(S)||0;if(M&&D>1&&!Dt.has(`${w}->${S}`)){let Q=(Ie.get(S)||0)+1;if(Q<D){Ie.set(S,Q);return}Ie.set(S,0)}X.includes(S)||X.push(S)};this.entryPoint&&X.push(this.entryPoint);let ae=[],Fe=a?.recursionLimit??100,Ut=0;try{for(;X.length>0;){let w=X.pop();if(!w||w==="END")continue;if(++Ut>Fe)throw new Error(`Workflow exceeded recursion limit (${Fe}) \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=Z(g,st);if(De(M)){try{Bn(M)}catch{}r.abort()}if(r.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};let D=this.nodes.get(w);if(!D)throw new Error(`Node '${w}' not found in graph`);let Q=JSON.stringify({sessionPath:g,sessionTimestamp:m,currentNode:w,createdAt:new Date().toISOString(),config:f.get("config")}),Wt=Z(g,K);Ot(Wt,Q,"utf-8");let Ge=f.get("config")?.paths?.output||he,Ft=Z(i,Ge,K);Nt(Z(i,Ge),{recursive:!0});try{Ot(Ft,Q,"utf-8")}catch{}let He=t.onPipelineProgress;if(typeof He=="function")try{He({cwd:i,sessionPath:g,sessionId:b,outputBase:f.get("config")?.paths?.output||he,currentNode:w})}catch{}let Gt=(this.resolvedToolsMap||{})[w]||null;f.set("_currentNodeTools",Gt);let Ht=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ht[w]||{}),P.nodeStart(w);let Je=Date.now(),ce=this.nodePrompts.get(w);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(se(),re));this._invokeAgent=x.invokeAgent}let Jt=this._invokeAgent,$e={},zt=D.config?.skills||[];for(let x of zt){let C=$(x);if(typeof C?.invokeAgentOptions=="function")try{let k=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:w});k&&typeof k=="object"&&($e={...$e,...k})}catch(k){console.warn(`[graph] skill '${x}' invokeAgentOptions threw: ${k.message}`)}}let ze=async(x,C,k={})=>{let B=Jt(x,C,{...$e,...k,signal:r.signal});return B.catch(()=>{}),r.signal.aborted?B:Promise.race([B,new Promise((q,L)=>{let R=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);ee.name="AbortError",L(ee)},s)};r.signal.addEventListener("abort",R,{once:!0})})])},Yt=async(x={},C={})=>{let k=C.prompt||"";if(ce){let B=this._compiledPrompts.get(w);B||(B=Dn.compile(ce,{noEscape:!0}),this._compiledPrompts.set(w,B));try{k=B(x)}catch(q){throw console.error(`\u274C Template rendering failed for node '${w}':`,q.message),new Error(`Template rendering failed: ${q.message}`,{cause:q})}}else if(!k)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return ze(k,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:r.signal})},Ye=f.getAll(),Zt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let x of Zt)Object.prototype.hasOwnProperty.call(Ye,x)&&console.warn(`[workflow] node "${w}": state key "${x}" is shadowed by the engine context prop; read it via context.state.get('${x}')`);let Ze={...Ye,state:f,invokeAgent:Yt,_coreInvokeAgent:ze,agent:e,nodeId:w,promptTemplate:ce,getPromptTemplate:()=>ce};try{let x=(D.config?.skills||[]).map(R=>h.get(R)).filter(Boolean),C=[...this.middleware,...x],k;k=await gt(e,r.signal,async()=>C.length>0?this._composeMiddleware(C,w,async()=>D.execute(Ze,f),f.getAll(),f):D.execute(Ze,f));let B=Date.now()-Je;if(ae.push({node:w,success:k.success,duration:B,timestamp:new Date().toISOString()}),!k.success){if(r.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:ae,stoppedExternally:!0};f.append("errors",{node:w,error:k.error});let R=D.config?.retries||0,ee=`${w}_retries`,le=f.getAll()[ee]||0;if(le<R){P.stepInfo(`Retrying (attempt ${le+1}/${R})`),f.update({[ee]:le+1,[`${w}_raw`]:k.raw});continue}throw P.nodeFailed(w,k.error,{duration:B}),new Error(`Node '${w}' failed after ${le} attempts: ${k.error}`)}f.update({[w]:k.output});let q=this._summarizeNodeOutput(w,k.output);P.nodeComplete(w,{duration:B,details:q});let L=this.edges.get(w);if(L)if(L.conditional){let R=L.routes(f.getAll());P.route(w,R),Ee(R,w,!1)}else if(Array.isArray(L))for(let R=L.length-1;R>=0;R--)Ee(L[R],w,!0);else Ee(L,w,!0)}catch(x){throw P.isInsideNode&&P.nodeFailed(w,x.message,{duration:Date.now()-Je}),f.set("failed",!0),f.set("failedAt",w),x}}P.graphComplete();let S={success:!0,state:f.getAll(),executionLog:ae};return e&&typeof e.onComplete=="function"&&await e.onComplete(S),S}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(S){console.warn(`[workflow] agent.cleanup() failed: ${S.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var Ue=globalThis[Le];function zn(n,e){Ue.set(n,e)}function Rt(n){return Ue.get(n)}function We(n){return Ue.has(n)}zn("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(()=>(se(),re))).invokeAgent);let r=e.extraPromptInstructions||"Execute the task based on the current state.",s=Yn(r,t),i=await o(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:n},raw:typeof i=="string"?i:i.raw}}})});function Yn(n,e){let t=/@([\w.]+)/g,o=new Set,r;for(;(r=t.exec(n))!==null;)o.add(r[1]);if(o.size===0)return n;let s=[],i=new Set;for(let a of o){let u=a.split(".")[0];if(i.has(u))continue;let d=a.split(".").reduce((c,g)=>c?.[g],e);if(d===void 0)continue;let y=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
|
|
43
|
+
${y}`),a.includes(".")||i.add(u)}return s.length===0?n:`${n}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
|
-
${
|
|
48
|
+
${s.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}
|
|
50
|
+
`)}`}ge();F();var Zn={};function Bt(n,e){if(Array.isArray(e))return Mt(e);let t=Zn[n];return!t||t.length===0?null:Mt(t)}function Mt(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},o=[];for(let r of n){let s=oe(r);if(!s){_.warn(`[workflow] unknown skill "${r}" \u2014 skipping`);continue}o.push(r);for(let i of s.tools||[])e.push({name:i.name,description:i.description,input_schema:i.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let i=s.resolve();i&&(t[s.serverName]={...i,toolPrefix:r})}else{let i={};for(let a of s.envKeys||[]){let u=process.env[a];u&&(i[a]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:i,toolPrefix:r}}}return o.length===0?null:{toolIds:o,claudeTools:e,mcpServers:t}}F();function rr(n,e={}){let{nodes:t,edges:o,nodeConfigs:r={}}=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 s=new _e(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let i=new Set,a=new Map,u={};for(let c of t){let g=be(c);a.set(c.id,{...c,resolvedType:g}),g==="decision"&&i.add(c.id)}for(let[c,g]of a){if(i.has(c))continue;let m=g.resolvedType,b=r[c]||{},A=Bt(m,b.tools);A&&(u[c]=A);let T={};b.prompt&&(T.prompt=b.prompt);let f=We(m);if(_.debug(`[workflow] compiler: node "${c}" type="${m}" registered=${f}`),b.customCode&&!f)s.addNode(c,jt(c,b.customCode,b),T),s.setNodeType(c,m);else if(f){let h=Rt(m);h.factory?s.addNode(c,h.create(c,{...b,resolvedTools:A}),T):s.addNode(c,h,T),s.setNodeType(c,m)}else if(b.executeCode)s.addNode(c,jt(c,b.executeCode,b),T),s.setNodeType(c,m);else throw new j(`Unknown node type "${m}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of o)i.has(c.target)||d.add(c.target);let y=t.find(c=>!i.has(c.id)&&!d.has(c.id));if(!y)throw new j("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(y.id);let l=qn(o,"source");for(let c of o)if(!i.has(c.source))if(i.has(c.target)){let g=c.target,m=l.get(g)||[];if(m.length===0)throw new j(`Decision node "${g}" has no outgoing edges`);let b=Kn(g,m,i);s.addConditionalEdges(c.source,b)}else s.addEdge(c.source,c.target);return s}function sr(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 u=be(a);if(u==="decision"||We(u))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" 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 r=new Set(n.nodes.filter(a=>be(a)==="decision").map(a=>a.id)),s=new Set;for(let a of n.edges)r.has(a.target)||s.add(a.target);let i=n.nodes.filter(a=>!r.has(a.id)&&!s.has(a.id));i.length===0?e.push("No entry point found (every node has incoming edges)"):i.length>1&&e.push(`Multiple entry points found: ${i.map(a=>a.id).join(", ")}`);for(let a of r){let u=n.edges.filter(y=>y.source===a);u.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),u.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 ir(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>be(e)!=="decision").map(e=>e.id)}function be(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function qn(n,e){let t=new Map;for(let o of n){let r=o[e];t.has(r)||t.set(r,[]),t.get(r).push(o)}return t}function Kn(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 r=o.data?.conditionalCode||o.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),i;try{let u=new Function(`return (${r})`)();i=d=>{let y=u(d);return s.has(y)||_.warn(`[workflow] conditional route from "${n}" returned "${y}" which is not in valid targets: ${[...s].join(", ")}`),y}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return i}function jt(n,e,t={}){let o;try{o=new Function("invokeAgent","require","console",`return (${e})`)}catch(i){throw new j(`Failed to compile customCode for node "${n}": ${i.message}`)}let r=o(async(...i)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(se(),re));return a(...i)},typeof ve<"u"?ve:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:s,execute:async i=>{try{let a=await r(i);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"}};export{j as CompilationError,rr as compileGraph,ir as extractSteps,sr as validateGraphConfig};
|