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