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