@zibby/agent-workflow 0.4.39 → 0.6.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/README.md +1 -1
- package/dist/agents/base.d.ts +10 -19
- package/dist/agents/base.js +1 -1
- package/dist/code-generator.d.ts +2 -2
- package/dist/code-generator.js +12 -12
- package/dist/compose-knowledge.d.ts +1 -1
- package/dist/constants.d.ts +9 -9
- package/dist/context-loader.d.ts +2 -2
- package/dist/context-loader.js +2 -2
- package/dist/exec-context.d.ts +28 -14
- package/dist/graph-compiler.d.ts +6 -6
- package/dist/graph-compiler.js +16 -16
- package/dist/graph.d.ts +46 -63
- package/dist/graph.js +16 -16
- package/dist/in-process-subgraph.d.ts +58 -25
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +45 -18
- package/dist/index.js +27 -27
- package/dist/logger.d.ts +13 -12
- package/dist/logger.js +1 -1
- package/dist/node-registry.d.ts +5 -5
- package/dist/node-registry.js +8 -8
- package/dist/node.d.ts +14 -12
- package/dist/node.js +11 -11
- package/dist/output-parser.d.ts +3 -27
- package/dist/output-parser.js +2 -2
- package/dist/skill-registry.d.ts +7 -21
- package/dist/state.d.ts +8 -4
- package/dist/state.js +1 -1
- package/dist/stores.d.ts +8 -11
- package/dist/strategy-registry.d.ts +18 -12
- package/dist/strategy-registry.js +8 -8
- package/dist/sub-graph-executor.d.ts +36 -8
- package/dist/sub-graph-executor.js +1 -1
- package/dist/subgraph-registry.d.ts +37 -16
- package/dist/timeline.d.ts +35 -20
- package/dist/timeline.js +8 -8
- package/dist/tool-resolver.d.ts +8 -15
- package/dist/tool-resolver.js +1 -1
- package/package.json +5 -3
package/dist/graph.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Oe=Object.defineProperty;var rt=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(n){throw e=[n],n}};var Dt=(r,t)=>{for(var e in t)Oe(r,e,{get:t[e],enumerable:!0})};var Lt,Re,it,I,V=rt(()=>{Lt=()=>{},Re={debug:Lt,info:Lt,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},it={impl:Re},I={debug:(...r)=>it.impl.debug?.(...r),info:(...r)=>it.impl.info?.(...r),warn:(...r)=>it.impl.warn?.(...r),error:(...r)=>it.impl.error?.(...r)}});var Vt=rt(()=>{});var Kt={};Dt(Kt,{clearSkills:()=>Ue,getAllSkills:()=>Le,getSkill:()=>St,getSkillSource:()=>De,hasSkill:()=>je,listSkillIds:()=>We,registerSkill:()=>Me});function Me(r,t={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:e,override:n=!1}=t,o=r.id;if(W.has(o)&&!n){let i=X.get(o);if(!(i===e)){let a=i||"first-party",u=e||"first-party";throw new Error(`Skill id collision: "${o}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}W.set(o,Object.freeze({...r})),e===void 0?X.delete(o):X.set(o,e)}function St(r){return W.get(r)||null}function je(r){return W.has(r)}function De(r){return X.get(r)||null}function Le(){return new Map(W)}function We(){return Array.from(W.keys())}function Ue(){W.clear(),X.clear()}var mt,yt,W,X,wt=rt(()=>{mt=Symbol.for("@zibby/agent-workflow.skills"),yt=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[mt]||(globalThis[mt]=new Map);globalThis[yt]||(globalThis[yt]=new Map);W=globalThis[mt],X=globalThis[yt]});var It={};Dt(It,{getAgentStrategy:()=>Qt,invokeAgent:()=>He,listStrategies:()=>Ge,registerStrategy:()=>Fe,resolveInvocationModel:()=>Xt});function Fe(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=U.findIndex(e=>e.getName()===r.getName());t>=0?U[t]=r:U.push(r)}function Ge(){return U.map(r=>r.getName())}function Xt({config:r={},options:t={},strategyName:e,envModel:n}={}){let o=r.models||{},i=t.nodeName&&o[t.nodeName]||null,s=o.default||null,a=r.agent?.[e]?.model||null,u=(typeof n=="string"?n.trim():"")||null;return i||s||a||t.model||u||null}function Qt(r={}){let{state:t={},preferredAgent:e=null}=r,n=e||t.agentType||process.env.AGENT_TYPE;if(!n){let i=U.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${n}`);let o=U.find(i=>i.getName()===n);if(!o){let i=U.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!o.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${o.getName()}`),o}async function He(r,t={},e={}){let n=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},o={...t,state:n},i=Qt(o),s=n.config||e.config||{},a=Xt({config:s,options:e,strategyName:i.name,envModel:process.env.MODEL}),u={...e,model:a,workspace:n.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],extraMcpServers:e.extraMcpServers||n.extraMcpServers||t.extraMcpServers||[],plugins:e.plugins||t.plugins||[],config:s},p=r,h=u.skills||[];if(h.length>0&&!e.skipPromptFragments){let S=h.map(y=>{let w=St(y)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);S.length>0&&(p+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${S.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let c=
|
|
5
|
+
`)}`)}let c=n._currentNodeConfig?.stores;if(Array.isArray(c)&&c.length>0&&typeof c[0]=="object"){let S=c.length<=8,y=c.map(w=>{let T=w?.id??w?.storeId??"",$=(w?.name??"").toString().trim()||T,f=w?.type?` \xB7 ${w.type}`:"",g=(w?.description||"").toString().replace(/\s+/g," ").trim(),m=`- ${$} \xB7 ${g||"(no description)"}${f} (id: ${T})`;if(S&&w?.schema&&typeof w.schema=="object"){let d=w.schema.properties&&typeof w.schema.properties=="object"?Object.keys(w.schema.properties):Object.keys(w.schema);d.length&&(m+=`
|
|
6
6
|
fields: ${d.join(", ")}`)}return m});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let l=
|
|
9
|
+
${y.join(`
|
|
10
|
+
`)}`}let l=n._currentNodeConfig?.extraPromptInstructions?.trim();return l&&(p+=`
|
|
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
|
${l}
|
|
17
|
-
`),I.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,u)}var _t,
|
|
17
|
+
`),I.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,u)}var _t,U,bt=rt(()=>{Vt();V();wt();_t=Symbol.for("@zibby/agent-workflow.strategies");globalThis[_t]||(globalThis[_t]=[]);U=globalThis[_t]});var Ne=new Set(["__proto__","constructor","prototype"]);function dt(r){if(Ne.has(r))throw new Error(`Invalid state key: "${r}"`)}var ot=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){dt(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let n of e)dt(n);this._history.push({...this._state});for(let n of e)this._state[n]=t[n]}append(t,e){dt(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import F from"handlebars";var st=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 n=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(o=>o[0]);for(let o of n)try{return this.validate(JSON.parse(o))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[n,o]of Object.entries(this.schema)){if(o.required&&!(n in t)&&e.push(`Missing required field: ${n}`),n in t&&o.type){let i=typeof t[n];i!==o.type&&e.push(`Field '${n}' expected ${o.type}, got ${i}`)}if(o.validate&&n in t){let i=o.validate(t[n]);i&&e.push(`Field '${n}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};V();import{writeFileSync as Et,readFileSync as te,existsSync as ee,mkdirSync as Je}from"node:fs";import{join as $t,dirname as Ye}from"node:path";import x from"chalk";var Be="__WORKFLOW_GRAPH_LOG__",K=x.gray("\u2502"),Ce=x.gray("\u250C"),
|
|
20
|
-
`?(
|
|
21
|
-
${Gt}`,t.col=Ht))}return s
|
|
19
|
+
`)}`);return t}};V();import{writeFileSync as Et,readFileSync as te,existsSync as ee,mkdirSync as Je}from"node:fs";import{join as $t,dirname as Ye}from"node:path";import x from"chalk";var Be="__WORKFLOW_GRAPH_LOG__",K=x.gray("\u2502"),Ce=x.gray("\u250C"),Wt=x.gray("\u2514"),ft=x.green("\u25C6"),Ut=x.hex("#c084fc")("\u25C6"),Ft=x.hex("#2dd4bf")("\u25C6"),ht=x.red("\u25C6"),Gt=`${K} `,Ht=2;function Jt(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Yt(r,t){return(e,n,o)=>{if(typeof e!="string")return r(e,n,o);let i=process.stdout.columns||120,s="";for(let a=0;a<e.length;a++){let u=e[a];t.lineStart&&(s+=Gt,t.col=Ht,t.lineStart=!1),u===`
|
|
20
|
+
`?(s+=u,t.lineStart=!0,t.col=0,t.inEsc=!1):u==="\x1B"?(t.inEsc=!0,s+=u):t.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(t.inEsc=!1)):(t.col++,s+=u,t.col>=i&&(s+=`
|
|
21
|
+
${Gt}`,t.col=Ht))}return r(s,n,o)}}var gt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Yt(this._origStdoutWrite,t),process.stderr.write=Yt(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
24
|
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Be}${JSON.stringify(t)}
|
|
@@ -26,17 +26,17 @@ ${Gt}`,t.col=Ht))}return s(n,r,o)}}var gt=class{constructor(){this._currentNode=
|
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
28
|
`)}step(t){this._origStdoutWrite?this._writeDot(ft,t):process.stdout.write.bind(process.stdout)(`${K} ${ft} ${t}
|
|
29
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(
|
|
29
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Ut,t):process.stdout.write.bind(process.stdout)(`${K} ${Ut} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=x.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ft,e):process.stdout.write.bind(process.stdout)(`${K} ${Ft} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,x.red(t)):process.stdout.write.bind(process.stdout)(`${K} ${ht} ${x.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:n,details:o}=e;if(o)for(let s of o)this._rawWrite(`${ft} ${s}`);let i=n?x.dim(` ${Jt(n)}`):"";this._rawWrite(`${Wt} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,n={}){this._stopIntercepting();let{duration:o}=n,i=o?x.dim(` ${Jt(o)}`):"";this._rawWrite(`${ht} ${x.red(e)}`),this._rawWrite(`${Wt} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(x.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},P=new gt;var at=".zibby/output",Zt="sessions",z=".session-info.json",zt=".zibby-stop";var Nn=Object.freeze(["codebase-memory","code-scan","artifact"]),qt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",r=>Number(r)+1);F.helpers.json||F.registerHelper("json",r=>JSON.stringify(r,null,2));F.helpers.eq||F.registerHelper("eq",(r,t)=>r===t);var D=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 st(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 I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return I.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let s=o("_skillHints");s&&(i=`${s}
|
|
33
33
|
|
|
34
|
-
${i}`);let a=r(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=$t(p,z);if(ee(c)){let y=JSON.parse(te(c,"utf-8"));y.currentNode=this.name,Et(c,JSON.stringify(y,null,2),"utf-8")}let l=$t(p,"..",z);if(ee(l))try{let y=JSON.parse(te(l,"utf-8"));y.currentNode=this.name,Et(l,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(c){I.debug(`[workflow] could not update session info: ${c.message}`)}let h=null;for(let c=0;c<=this.retries;c++)try{I.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=r().config||{},y=l.agents||{},S=this.config.agent??y[this.name]??null,w={state:r()};S&&(w.preferredAgent=S);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(bt(),It))).invokeAgent);let f=await $(i,w,T),g,m;if(typeof f=="string"?(g=f,m=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),m=f.structured):(g=f.raw||JSON.stringify(f,null,2),m=f.extracted||null),p)try{let d=$t(p,this.name,"raw_stream_output.txt");Je(Ye(d),{recursive:!0}),Et(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let d=m;if(typeof this.onComplete=="function")try{d=await this.onComplete(r(),m)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){h=l,c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};V();V();import{mkdirSync as qe,existsSync as H,statSync as ue,readdirSync as pe,rmSync as Ve}from"node:fs";import{spawn as ae}from"node:child_process";import{join as L}from"node:path";import{pathToFileURL as Ke}from"node:url";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{AsyncLocalStorage as Ze}from"node:async_hooks";var vt=new Ze;function Q(){let s=vt.getStore();return s||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function re(s,t){let e=vt.getStore()||Q(),r=Object.freeze({executionId:s.executionId,parentExecutionId:s.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(s.executionId!==e.executionId?1:0),conversationId:s.conversationId!==void 0?s.conversationId:e.conversationId??null,dispatchMode:s.dispatchMode??null});return vt.run(r,t)}var Tt=new Map,At=new Map,se=new Map;function oe(s,t,e={}){if(!s||typeof s!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(s,t),At.set(s,"ready"),se.set(s,{...e,cachedAt:Date.now()})}function ne(s,t){At.set(s,"failed"),se.set(s,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(s)}function ie(s){return At.get(s)==="ready"?Tt.get(s):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Qe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}},ce=new Xe,le=Promise.resolve();async function tr(s,t){let e=s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(e.length===0)return t();let r=ce.getStore()===!0,o=null;if(!r){let n=le;le=new Promise(a=>{o=a}),await n}let i=new Map;try{for(let[n,a]of e)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return I.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${r?" (nested)":""}`),await ce.run(!0,t)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;o&&o()}}function er(){let s=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=s||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!e||!r||!o)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:r,authToken:o}}async function rr({apiBase:s,authToken:t,body:e}){let r;try{r=await fetch(`${s}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let o=null;try{o=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=o?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(r.status===400&&o?.validationErrors){let i=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=o.validationErrors,i.missing=o.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return o?.data||o}async function G({apiBase:s,authToken:t,payload:e}){try{let r=await fetch(`${s}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${e.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function sr(s,t){let e=L(t,".ready"),r=L(t,"graph.mjs");if(H(e)&&H(r))return;qe(t,{recursive:!0});let o=L(t,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(o,"wx");a(u),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(H(e)&&H(r))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((u,p)=>{let h=ae("curl",["-fsSL",s],{stdio:["ignore","pipe","inherit"]}),c=ae("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(c.stdin);let l,y,S=()=>{if(l!==void 0&&y!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(y!==0)return p(new Error(`tar exited ${y}`));u()}};h.on("close",w=>{l=w,S()}),c.on("close",w=>{y=w,S()}),h.on("error",p),c.on("error",p)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(e,"");try{a(o)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new P("bundle-extract-failed",n.message)}}async function or(s){let t=L(s,"graph.mjs");if(!H(t))throw new P("entry-missing",`graph.mjs missing under ${s}`);let e;try{e=await import(Ke(t).href)}catch(o){throw new P("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=e.default||Object.values(e).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function de(s,t={}){if(!s||typeof s!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),r;try{r=er()}catch(d){throw d}I.debug(`[in-process subgraph] begin '${s}' parent=${e.executionId||"<root>"}`);let o=await rr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:s,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:h,bundleReady:c,nodeConfigs:l}=o,y=Qe();if(n&&n!==y)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${y} vs ${n}`);if(!c||!a)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let S=ie(s);if(!S){let d=L(ct,`${h}@${p||"0"}`);try{await sr(a,d);try{ir()}catch{}}catch(E){throw E.fallback&&await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{S=await or(d),oe(s,S,{workflowUuid:h,version:p,runtimeTag:n,cacheDir:d})}catch(E){throw ne(s,E),await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new P("import-failed",E.message)}}let w=Date.now(),T=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...t.input||{},...$?{nodeConfigs:l}:{}},g,m;try{g=await tr(T,async()=>{let E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return re({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,f,{signal:t.signal}))}),m=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-w}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-w}});let d=new Error(`Sub-graph '${s}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function nr(s){let t=0,e=[s];for(;e.length;){let r=e.pop(),o;try{o=ue(r)}catch{continue}if(o.isDirectory()){let i;try{i=pe(r)}catch{continue}for(let n of i)e.push(L(r,n))}else t+=o.size}return t}function ir({cap:s=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!H(ct))return{evicted:0,freedBytes:0};let t=pe(ct),e=[],r=0;for(let a of t){let u=L(ct,a),p;try{p=ue(u)}catch{continue}let h=p.isDirectory()?nr(u):p.size;r+=h,e.push({name:a,full:u,size:h,mtimeMs:p.mtimeMs})}if(r<=s)return{evicted:0,freedBytes:0,totalBytes:r};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let o=Math.floor(s*.7),i=0,n=0;for(let a of e){if(r-i<=o)break;if(!H(L(a.full,".lock")))try{Ve(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ar=2e3,cr=600*1e3,lr=new Set(["completed","failed","canceled","timeout"]);function ur(){let s=process.env.PROGRESS_API_URL;if(!s)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 s.replace(/\/executions\/?$/,"")}function pr(){let s=process.env.PROJECT_ID;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return s}function dr(){let s=process.env.PROJECT_API_TOKEN;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return s}function fr(){return process.env.EXECUTION_ID||null}function fe(s,t){return t==null?s:typeof t=="function"?t(s):typeof t=="string"?t.split(".").reduce((e,r)=>e==null?e:e[r],s):s}async function he(s,t={}){if(!s||typeof s!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=r)throw new Error(`dispatchSubgraph('${s}'): sub-graph depth ${e.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{I.debug(`[sub-graph] trying in-process for '${s}'`);let{finalState:m}=await de(s,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=fe(m,t.output);return I.info(`[sub-graph] '${s}' completed in-process`),d}catch(m){if(m instanceof P||m?.fallback)I.info(`[sub-graph] in-process fallback for '${s}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let o=ur(),i=pr(),n=dr(),a=fr(),u=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(s)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${s}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(p)});if(!h.ok){let m=null,d="";try{m=await h.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await h.text().catch(()=>"")}if(h.status===429){let A=m?.quotaInfo||{},M=new Error(`Sub-graph '${s}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=s,M.quotaInfo=A,M}if(h.status===400){let A=new Error(`Sub-graph '${s}' rejected input: ${d}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=s,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let E=new Error(`Sub-graph '${s}' trigger rejected (${h.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=s,E}let c=await h.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${s}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${s}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:s};let y=Number.isFinite(t.timeoutMs)?t.timeoutMs:cr,S=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ar,w=`${o}/executions/${encodeURIComponent(l)}`,T=Date.now()+y,$="accepted",f=0;for(;Date.now()<T;){await new Promise(A=>setTimeout(A,S)),f+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${n}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${l} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${m.status}`)}let d=await m.json(),E=d?.data||d?.execution||d;if($=E?.status||$,lr.has($)){if($!=="completed"){let _=new Error(`Sub-graph '${s}' (${l}) ended in status '${$}'`);throw _.subgraphJobId=l,_.subgraphStatus=$,_}let A=E?.finalState||E?.state||{},M=fe(A,t.output);return I.info(`[sub-graph] '${s}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${s}' (${l}) timed out after ${Math.round(y/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as ge,readFileSync as hr}from"node:fs";import{join as kt,dirname as me}from"node:path";var lt=class{static async loadContext(t,e,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=me(kt(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let h=u.replace(/\.[^.]+$/,"").toLowerCase();o[h]=p}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let p=kt(e,u);ge(p)&&(o[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return o}static async findAndMergeContextFiles(t,e,r){let o=[],i=e;for(;i.startsWith(r);){let n=kt(i,t);if(ge(n))try{o.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${t} from ${n}: ${u.message}`)}let a=me(i);if(a===i)break;i=a}return o.length===0?null:o.every(n=>typeof n=="string")?o.join(`
|
|
34
|
+
${i}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=$t(p,z);if(ee(c)){let S=JSON.parse(te(c,"utf-8"));S.currentNode=this.name,Et(c,JSON.stringify(S,null,2),"utf-8")}let l=$t(p,"..",z);if(ee(l))try{let S=JSON.parse(te(l,"utf-8"));S.currentNode=this.name,Et(l,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(c){I.debug(`[workflow] could not update session info: ${c.message}`)}let h=null;for(let c=0;c<=this.retries;c++)try{I.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},S=l.agents||{},y=this.config.agent??S[this.name]??null,w={state:n()};y&&(w.preferredAgent=y);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(bt(),It))).invokeAgent);let f=await $(i,w,T),g,m;if(typeof f=="string"?(g=f,m=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),m=f.structured):(g=f.raw||JSON.stringify(f,null,2),m=f.extracted||null),p)try{let d=$t(p,this.name,"raw_stream_output.txt");Je(Ye(d),{recursive:!0}),Et(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let d=m;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),m)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),P.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){h=l,c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};V();V();import{mkdirSync as qe,existsSync as H,statSync as ue,readdirSync as pe,rmSync as Ve}from"node:fs";import{spawn as ae}from"node:child_process";import{join as L}from"node:path";import{pathToFileURL as Ke}from"node:url";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{AsyncLocalStorage as Ze}from"node:async_hooks";var vt=new Ze;function Q(){let r=vt.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function ne(r,t){let e=vt.getStore()||Q(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return vt.run(n,t)}var Tt=new Map,kt=new Map,re=new Map;function oe(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),kt.set(r,"ready"),re.set(r,{...e,cachedAt:Date.now()})}function se(r,t){kt.set(r,"failed"),re.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function ie(r){return kt.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Qe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}},ce=new Xe,le=Promise.resolve();async function tn(r,t){let e=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(e.length===0)return t();let n=ce.getStore()===!0,o=null;if(!n){let s=le;le=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of e)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${n?" (nested)":""}`),await ce.run(!0,t)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function en(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!e||!n||!o)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:n,authToken:o}}async function nn({apiBase:r,authToken:t,body:e}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(i){throw new O("network",`begin fetch failed: ${i.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=o?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(n.status===400&&o?.validationErrors){let i=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=o.validationErrors,i.missing=o.missing,i}throw new O("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function G({apiBase:r,authToken:t,payload:e}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${e.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function rn(r,t){let e=L(t,".ready"),n=L(t,"graph.mjs");if(H(e)&&H(n))return;qe(t,{recursive:!0});let o=L(t,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(o,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(H(e)&&H(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let h=ae("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ae("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(c.stdin);let l,S,y=()=>{if(l!==void 0&&S!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(S!==0)return p(new Error(`tar exited ${S}`));u()}};h.on("close",w=>{l=w,y()}),c.on("close",w=>{S=w,y()}),h.on("error",p),c.on("error",p)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(e,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new O("bundle-extract-failed",s.message)}}async function on(r){let t=L(r,"graph.mjs");if(!H(t))throw new O("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ke(t).href)}catch(o){throw new O("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=e.default||Object.values(e).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function de(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),n;try{n=en()}catch(d){throw d}I.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let o=await nn({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:h,bundleReady:c,nodeConfigs:l}=o,S=Qe();if(s&&s!==S)throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${S} vs ${s}`);if(!c||!a)throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let y=ie(r);if(!y){let d=L(ct,`${h}@${p||"0"}`);try{await rn(a,d);try{an()}catch{}}catch(E){throw E.fallback&&await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{y=await on(d),oe(r,y,{workflowUuid:h,version:p,runtimeTag:s,cacheDir:d})}catch(E){throw se(r,E),await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new O("import-failed",E.message)}}let w=Date.now(),T=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...t.input||{},...$?{nodeConfigs:l}:{}},g,m;try{g=await tn(T,async()=>{let E=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return ne({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,f,{signal:t.signal}))}),m=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-w}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-w}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function sn(r){let t=0,e=[r];for(;e.length;){let n=e.pop(),o;try{o=ue(n)}catch{continue}if(o.isDirectory()){let i;try{i=pe(n)}catch{continue}for(let s of i)e.push(L(n,s))}else t+=o.size}return t}function an({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!H(ct))return{evicted:0,freedBytes:0};let t=pe(ct),e=[],n=0;for(let a of t){let u=L(ct,a),p;try{p=ue(u)}catch{continue}let h=p.isDirectory()?sn(u):p.size;n+=h,e.push({name:a,full:u,size:h,mtimeMs:p.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let o=Math.floor(r*.7),i=0,s=0;for(let a of e){if(n-i<=o)break;if(!H(L(a.full,".lock")))try{Ve(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:n-i}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var cn=2e3,ln=600*1e3,un=new Set(["completed","failed","canceled","timeout"]);function pn(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function dn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function fn(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function hn(){return process.env.EXECUTION_ID||null}function fe(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,n)=>e==null?e:e[n],r):r}async function he(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{I.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:m}=await de(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=fe(m,t.output);return I.info(`[sub-graph] '${r}' completed in-process`),d}catch(m){if(m instanceof O||m?.fallback)I.info(`[sub-graph] in-process fallback for '${r}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let o=pn(),i=dn(),s=fn(),a=hn(),u=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(p)});if(!h.ok){let m=null,d="";try{m=await h.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await h.text().catch(()=>"")}if(h.status===429){let k=m?.quotaInfo||{},M=new Error(`Sub-graph '${r}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=k,M}if(h.status===400){let k=new Error(`Sub-graph '${r}' rejected input: ${d}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=r,k.validationErrors=m?.validationErrors||null,k.missing=m?.missing||null,k}let E=new Error(`Sub-graph '${r}' trigger rejected (${h.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=r,E}let c=await h.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let S=Number.isFinite(t.timeoutMs)?t.timeoutMs:ln,y=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:cn,w=`${o}/executions/${encodeURIComponent(l)}`,T=Date.now()+S,$="accepted",f=0;for(;Date.now()<T;){await new Promise(k=>setTimeout(k,y)),f+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${l} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${m.status}`)}let d=await m.json(),E=d?.data||d?.execution||d;if($=E?.status||$,un.has($)){if($!=="completed"){let _=new Error(`Sub-graph '${r}' (${l}) ended in status '${$}'`);throw _.subgraphJobId=l,_.subgraphStatus=$,_}let k=E?.finalState||E?.state||{},M=fe(k,t.output);return I.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(S/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as ge,readFileSync as gn}from"node:fs";import{join as At,dirname as me}from"node:path";var lt=class{static async loadContext(t,e,n={}){let o={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=me(At(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let h=u.replace(/\.[^.]+$/,"").toLowerCase();o[h]=p}}}let s=n.discovery||{};for(let[a,u]of Object.entries(s))try{let p=At(e,u);ge(p)&&(o[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return o}static async findAndMergeContextFiles(t,e,n){let o=[],i=e;for(;i.startsWith(n);){let s=At(i,t);if(ge(s))try{o.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${t} from ${s}: ${u.message}`)}let a=me(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):o.every(
|
|
38
|
+
`):o.every(s=>typeof s=="object")?Object.assign({},...o):o[o.length-1]}static async loadFile(t){let e=gn(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),o=await import(n(t).href);return o.default||o}return e}};import{mkdirSync as _e,existsSync as xt,writeFileSync as ye,unlinkSync as mn}from"node:fs";import{join as J,resolve as Ie}from"node:path";import{config as yn}from"dotenv";import{zodToJsonSchema as Se}from"zod-to-json-schema";import{z as ut}from"zod";import Sn from"handlebars";function wn({traceFrom:r,sessionId:t,sessionPath:e,idSource:n,mkdirFresh:o}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${s} sessionId=${t} source=${n} mkdir=${o?"yes":"no"} path=${e}`;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
|
-
`);console.log(`[zibby:session] stack (${
|
|
41
|
-
${h}`)}}function wr(){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 _r(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Ie(String(t).trim())}catch{return String(t).trim()}}function Ir(){wr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function br({sessionPath:s,sessionId:t}){s&&typeof s=="string"&&(process.env.ZIBBY_SESSION_PATH=s),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Er(s={}){let t=qt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),r=t||`${Date.now()}_${e}`,o=s.paths?.sessionPrefix;return o?`${o}_${r}`:r}function $r({cwd:s=process.cwd(),config:t={},initialState:e={},traceFrom:r="resolveWorkflowSession"}={}){let o=e.sessionPath,i=e.sessionTimestamp,n="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let p=Ie(String(process.env.ZIBBY_SESSION_PATH));p&&(o=p,n="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,n="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,n="config.sessionId"):(a=Er(t),n="generated")}i=i??Date.now();let h=t.paths?.output||at;o=J(s,h,Zt,a)}let u=!xt(o);return u&&_e(o,{recursive:!0}),(u||n!=="initialState.sessionPath")&&yr({traceFrom:r,sessionId:a,sessionPath:o,idSource:n,mkdirFresh:u}),br({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var we=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(t,e,r={}){if(!(e instanceof D)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,a={name:t,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async p=>{let h=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof n.input=="function"?c=n.input(h):n.input&&typeof n.input=="object"?c=n.input:c={},he(n.workflow,{input:c,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:p?.agent})}},u=new D(a);return u.name=t,this.nodes.set(t,u),r.prompt&&this.nodePrompts.set(t,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),this}let o=!(e instanceof D)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof D?e:new D(o?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),r.prompt?this.nodePrompts.set(t,r.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:r}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:r}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,r,o,i){let n=r;for(let a=t.length-1;a>=0;a--){let u=t[a],p=n;n=()=>u(e,p,o,i)}return n()}serialize(){let t=[],e={};for(let[c,l]of this.nodes){let y=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);t.push({id:c,type:y,data:{nodeType:y,label:c}});let S={};l._isCustomCode&&typeof l.execute=="function"&&(S.customCode=l.execute.toString());let w=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;w&&(S.description=w);let T=this.nodePrompts.get(c);if(T)S.prompt=T;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(S.prompt=d,S.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(S.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof ut?.toJSONSchema=="function")try{d=ut.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=ye(l.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else S.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[c];$?.toolIds&&(S.tools=$.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(S.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(S.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let m=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;m&&m.length>0&&(S.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(S).length>0&&(e[c]=S)}let r=[];for(let[c,l]of this.edges)if(typeof l=="string")r.push({source:c,target:l});else if(l.conditional){let y=this.conditionalCodeMap.get(c)||l.routes.toString(),S=this._inferConditionalTargets(l.routes,l.labels),w=l.labels||{},T=this.nodes.get(c),$=T?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!T,f=c;if(!$){let g=`${c}__branch`;t.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),r.push({source:c,target:g}),f=g}for(let g of S){let m={source:f,target:g,data:{conditionalCode:y}};w[g]&&(m.label=w[g]),r.push(m)}}let o=c=>{if(!c)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(c)}catch{}try{return ye(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of r)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:c,target:l})}let n=this._topoOrderNodes(t,r),a=this._runtimeSchema(),u=o(a||this.stateSchema),p=o(this.inputSchema),h=o(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:h}}_topoOrderNodes(t,e){let r=new Map(t.map((c,l)=>[c.id,l])),o=new Map(t.map(c=>[c.id,c])),i=new Map(t.map(c=>[c.id,0])),n=new Map(t.map(c=>[c.id,[]]));for(let c of e)n.has(c.source)&&i.has(c.target)&&(n.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(r.keys()),p=[...u].filter(c=>i.get(c)===0),h=[];for(;h.length<t.length;){let c;if(p.length>0){if(p.sort((l,y)=>r.get(l)-r.get(y)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,y)=>r.get(l)-r.get(y))[0];a.add(c),u.delete(c),h.push(o.get(c));for(let l of n.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return h}_inferConditionalTargets(t,e){let r=t.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=i.exec(r))!==null;){let p=n[2]!==void 0?n[2]:n[3];p!==void 0&&p!==""&&o.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))a.add(p);let u=new Set;for(let p of o)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=p.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let r=t;if(t.$ref&&t.definitions){let o=t.$ref.replace("#/definitions/","");r=t.definitions[o]||t}return this._flattenSchema(r,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let r=[],o=t.properties||{},i=t.required||[];for(let[n,a]of Object.entries(o)){let u=e?`${e}.${n}`:n;r.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!i.includes(n)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${u}[]`))}return r}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let r=[];e.success!==void 0&&r.push(`Result: ${e.success?"passed":"failed"}`);for(let[o,i]of Object.entries(e))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${o}: ${i}`);else if(Array.isArray(i)){let n=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);r.push(u?`${o}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${o}: ${n} items`)}if(r.length>=4)break}return r}async run(t,e={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=new AbortController;r.signal&&(r.signal.aborted?o.abort():r.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();mr({path:J(n,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let b=J(n,".zibby.config.js");xt(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let b=a?.agent;b?.provider?u=b.provider:b?.gemini?u="gemini":b?.claude?u="claude":b?.cursor?u="cursor":b?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let b=h.safeParse(e);if(!b.success){let N=b.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}O.step("State validated against schema")}let c=_r(),l=e.sessionPath||c;l||Ir();let{sessionPath:y,sessionTimestamp:S,sessionId:w}=$r({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});O.step(`Session ${w}`);let T=await lt.loadContext(e.specPath||"",n,p);Object.keys(T).length>0&&O.step(`Context loaded: ${Object.keys(T).join(", ")}`);let $=e.outputPath;!$&&e.specPath&&(t?.calculateOutputPath?$=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new ot({...e,config:a,agentType:u,outputPath:$,sessionPath:y,sessionTimestamp:S,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(wt(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(d).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),A=b=>{for(let N of E)if(N.id===b)return N;return m(b)},M=new Set;for(let[,b]of this.nodes)for(let N of b.config?.skills||[])M.add(N);for(let b of M){let N=A(b);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&g.set(b,R)}catch{}}let _=this.entryPoint,tt=[],Ot=a?.recursionLimit??100,be=0;try{for(;_&&_!=="END";){if(++be>Ot)throw new Error(`Workflow exceeded recursion limit (${Ot}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=J(y,zt);if(xt(N)){try{gr(N)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
40
|
+
`);console.log(`[zibby:session] stack (${r}):
|
|
41
|
+
${h}`)}}function _n(){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 In(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Ie(String(t).trim())}catch{return String(t).trim()}}function bn(){_n()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function En({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function $n(r={}){let t=qt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),n=t||`${Date.now()}_${e}`,o=r.paths?.sessionPrefix;return o?`${o}_${n}`:n}function vn({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:n="resolveWorkflowSession"}={}){let o=e.sessionPath,i=e.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let p=Ie(String(process.env.ZIBBY_SESSION_PATH));p&&(o=p,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,s="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,s="config.sessionId"):(a=$n(t),s="generated")}i=i??Date.now();let h=t.paths?.output||at;o=J(r,h,Zt,a)}let u=!xt(o);return u&&_e(o,{recursive:!0}),(u||s!=="initialState.sessionPath")&&wn({traceFrom:n,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:u}),En({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var we=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(t,e,n={}){if(!(e instanceof D)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let s=e,a={name:t,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async p=>{let h=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof s.input=="function"?c=s.input(h):s.input&&typeof s.input=="object"?c=s.input:c={},he(s.workflow,{input:c,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:p?.agent})}},u=new D(a);return u.name=t,this.nodes.set(t,u),n.prompt&&this.nodePrompts.set(t,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(t,n),this}let o=!(e instanceof D)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof D?e:new D(o?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),n.prompt?this.nodePrompts.set(t,n.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(n).length>0&&this.nodeOptions.set(t,n),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:n}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:n}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,n,o,i){let s=n;for(let a=t.length-1;a>=0;a--){let u=t[a],p=s;s=()=>u(e,p,o,i)}return s()}serialize(){let t=[],e={};for(let[c,l]of this.nodes){let S=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);t.push({id:c,type:S,data:{nodeType:S,label:c}});let y={};l._isCustomCode&&typeof l.execute=="function"&&(y.customCode=l.execute.toString());let w=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;w&&(y.description=w);let T=this.nodePrompts.get(c);if(T)y.prompt=T;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(y.prompt=d,y.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(y.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(y.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof ut?.toJSONSchema=="function")try{d=ut.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=Se(l.outputSchema,{target:"openApi3"})}catch{}y.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else y.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[c];$?.toolIds&&(y.tools=$.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(y.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(y.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let m=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;m&&m.length>0&&(y.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(y).length>0&&(e[c]=y)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(l.conditional){let S=this.conditionalCodeMap.get(c)||l.routes.toString(),y=this._inferConditionalTargets(l.routes,l.labels),w=l.labels||{},T=this.nodes.get(c),$=T?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!T,f=c;if(!$){let g=`${c}__branch`;t.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of y){let m={source:f,target:g,data:{conditionalCode:S}};w[g]&&(m.label=w[g]),n.push(m)}}let o=c=>{if(!c)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(c)}catch{}try{return Se(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let s=this._topoOrderNodes(t,n),a=this._runtimeSchema(),u=o(a||this.stateSchema),p=o(this.inputSchema),h=o(this.contextSchema);return{nodes:s,edges:n,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:h}}_topoOrderNodes(t,e){let n=new Map(t.map((c,l)=>[c.id,l])),o=new Map(t.map(c=>[c.id,c])),i=new Map(t.map(c=>[c.id,0])),s=new Map(t.map(c=>[c.id,[]]));for(let c of e)s.has(c.source)&&i.has(c.target)&&(s.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>i.get(c)===0),h=[];for(;h.length<t.length;){let c;if(p.length>0){if(p.sort((l,S)=>n.get(l)-n.get(S)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,S)=>n.get(l)-n.get(S))[0];a.add(c),u.delete(c),h.push(o.get(c));for(let l of s.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return h}_inferConditionalTargets(t,e){let n=t.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(n))!==null;){let p=s[2]!==void 0?s[2]:s[3];p!==void 0&&p!==""&&o.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))a.add(p);let u=new Set;for(let p of o)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=p.exec(n))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let n=t;if(t.$ref&&t.definitions){let o=t.$ref.replace("#/definitions/","");n=t.definitions[o]||t}return this._flattenSchema(n,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let n=[],o=t.properties||{},i=t.required||[];for(let[s,a]of Object.entries(o)){let u=e?`${e}.${s}`:s;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}return n}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let n=[];e.success!==void 0&&n.push(`Result: ${e.success?"passed":"failed"}`);for(let[o,i]of Object.entries(e))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);n.push(u?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(n.length>=4)break}return n}async run(t,e={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=new AbortController;n.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,s=e.cwd||process.cwd();yn({path:J(s,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let b=J(s,".zibby.config.js");xt(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let b=a?.agent;b?.provider?u=b.provider:b?.gemini?u="gemini":b?.claude?u="claude":b?.cursor?u="cursor":b?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let b=h.safeParse(e);if(!b.success){let N=b.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}P.step("State validated against schema")}let c=In(),l=e.sessionPath||c;l||bn();let{sessionPath:S,sessionTimestamp:y,sessionId:w}=vn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});P.step(`Session ${w}`);let T=await lt.loadContext(e.specPath||"",s,p);Object.keys(T).length>0&&P.step(`Context loaded: ${Object.keys(T).join(", ")}`);let $=e.outputPath;!$&&e.specPath&&(t?.calculateOutputPath?$=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new ot({...e,config:a,agentType:u,outputPath:$,sessionPath:S,sessionTimestamp:y,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(wt(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(d).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),k=b=>{for(let N of E)if(N.id===b)return N;return m(b)},M=new Set;for(let[,b]of this.nodes)for(let N of b.config?.skills||[])M.add(N);for(let b of M){let N=k(b);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&g.set(b,R)}catch{}}let _=this.entryPoint,tt=[],Pt=a?.recursionLimit??100,be=0;try{for(;_&&_!=="END";){if(++be>Pt)throw new Error(`Workflow exceeded recursion limit (${Pt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=J(S,zt);if(xt(N)){try{mn(N)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:tt,stoppedExternally:!0};let R=this.nodes.get(_);if(!R)throw new Error(`Node '${_}' not found in graph`);let Ot=JSON.stringify({sessionPath:S,sessionTimestamp:y,currentNode:_,createdAt:new Date().toISOString(),config:f.get("config")}),Ee=J(S,z);ye(Ee,Ot,"utf-8");let Nt=f.get("config")?.paths?.output||at,$e=J(s,Nt,z);_e(J(s,Nt),{recursive:!0});try{ye($e,Ot,"utf-8")}catch{}let Rt=e.onPipelineProgress;if(typeof Rt=="function")try{Rt({cwd:s,sessionPath:S,sessionId:w,outputBase:f.get("config")?.paths?.output||at,currentNode:_})}catch{}let ve=(this.resolvedToolsMap||{})[_]||null;f.set("_currentNodeTools",ve);let Te=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Te[_]||{}),P.nodeStart(_);let Bt=Date.now(),et=this.nodePrompts.get(_);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(bt(),It));this._invokeAgent=A.invokeAgent}let ke=this._invokeAgent,pt={},Ae=R.config?.skills||[];for(let A of Ae){let B=k(A);if(typeof B?.invokeAgentOptions=="function")try{let v=B.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:_});v&&typeof v=="object"&&(pt={...pt,...v})}catch(v){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${v.message}`)}}let Ct=async(A,B,v={})=>{let C=ke(A,B,{...pt,...v,signal:o.signal});return C.catch(()=>{}),o.signal.aborted?C:Promise.race([C,new Promise((Y,Z)=>{let j=()=>{setTimeout(()=>{let q=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);q.name="AbortError",Z(q)},i)};o.signal.addEventListener("abort",j,{once:!0})})])},xe=async(A={},B={})=>{let v=B.prompt||"";if(et){let C=this._compiledPrompts.get(_);C||(C=Sn.compile(et,{noEscape:!0}),this._compiledPrompts.set(_,C));try{v=C(A)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${_}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!v)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Ct(v,{state:f.getAll(),images:B.images||[]},{model:B.model||f.get("model"),workspace:f.get("workspace"),schema:B.schema,...B,signal:o.signal})},Mt=f.getAll(),Pe=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of Pe)Object.prototype.hasOwnProperty.call(Mt,A)&&console.warn(`[workflow] node "${_}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let jt={...Mt,state:f,invokeAgent:xe,_coreInvokeAgent:Ct,agent:t,nodeId:_,promptTemplate:et,getPromptTemplate:()=>et};try{let A=(R.config?.skills||[]).map(j=>g.get(j)).filter(Boolean),B=[...this.middleware,...A],v;B.length>0?v=await this._composeMiddleware(B,_,async()=>R.execute(jt,f),f.getAll(),f):v=await R.execute(jt,f);let C=Date.now()-Bt;if(tt.push({node:_,success:v.success,duration:C,timestamp:new Date().toISOString()}),!v.success){if(o.signal.aborted)return P.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:tt,stoppedExternally:!0};f.append("errors",{node:_,error:v.error});let j=R.config?.retries||0,q=`${_}_retries`,nt=f.getAll()[q]||0;if(nt<j){P.stepInfo(`Retrying (attempt ${nt+1}/${j})`),f.update({[q]:nt+1,[`${_}_raw`]:v.raw});continue}throw P.nodeFailed(_,v.error,{duration:C}),new Error(`Node '${_}' failed after ${nt} attempts: ${v.error}`)}f.update({[_]:v.output});let Y=this._summarizeNodeOutput(_,v.output);P.nodeComplete(_,{duration:C,details:Y});let Z=this.edges.get(_);if(!Z)_="END";else if(Z.conditional){let j=Z.routes(f.getAll());P.route(_,j),_=j}else _=Z}catch(A){throw P.isInsideNode&&P.nodeFailed(_,A.message,{duration:Date.now()-Bt}),f.set("failed",!0),f.set("failedAt",_),A}}P.graphComplete();let b={success:!0,state:f.getAll(),executionLog:tt};return t&&typeof t.onComplete=="function"&&await t.onComplete(b),b}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};export{we as WorkflowGraph,bn as clearInheritedSessionEnvForFreshRun,$n as generateWorkflowSessionId,In as readPinnedSessionPathFromEnv,vn as resolveWorkflowSession,_n as shouldTrustInheritedSessionEnv,En as syncProcessEnvToSession};
|
|
@@ -1,3 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process sub-graph executor.
|
|
3
|
+
*
|
|
4
|
+
* The fast path that `dispatchSubgraph` falls into when:
|
|
5
|
+
* - the caller is inside another running workflow on a Fargate task
|
|
6
|
+
* - the runtime feature flag (`ZIBBY_INPROCESS_SUBGRAPH=1`) is set
|
|
7
|
+
* - the child workflow's bundle is fetchable + runtime-compatible
|
|
8
|
+
*
|
|
9
|
+
* What happens here, end-to-end:
|
|
10
|
+
*
|
|
11
|
+
* 1. POST /internal/subgraph/begin
|
|
12
|
+
* → backend mints the child EXEC row, presigns the child's bundle,
|
|
13
|
+
* returns runtimeTag + tokens. Quota is enforced here.
|
|
14
|
+
*
|
|
15
|
+
* 2. Compare runtimeTag with the parent's. Mismatch → throw a typed
|
|
16
|
+
* error so the caller drops back to HTTP/trigger. (Native modules
|
|
17
|
+
* compiled against the wrong Node major would fail at `import()`
|
|
18
|
+
* anyway, and a missed mismatch could crash the whole Fargate
|
|
19
|
+
* container — we'd rather pay one cold start than risk that.)
|
|
20
|
+
*
|
|
21
|
+
* 3. Fetch + extract the bundle to /tmp/zibby/subgraphs/<uuid>@<ver>/.
|
|
22
|
+
* File-locked so a parent that spawns concurrent sibling children
|
|
23
|
+
* doesn't double-fetch the same bundle. Cached for the lifetime
|
|
24
|
+
* of the Fargate task — second call to the same child is a no-op.
|
|
25
|
+
*
|
|
26
|
+
* 4. `import()` the bundle's graph.mjs. Node ESM keys module identity
|
|
27
|
+
* by URL, so different versions of the same child workflow get
|
|
28
|
+
* separate module graphs and don't cross-contaminate.
|
|
29
|
+
*
|
|
30
|
+
* 5. Push an ALS scope with the child's execution id, then run the
|
|
31
|
+
* child's WorkflowGraph with the parent's AbortSignal. Any cancel
|
|
32
|
+
* that hits the parent propagates immediately to the child — no
|
|
33
|
+
* polling, no heartbeat — because the same controller drives both.
|
|
34
|
+
*
|
|
35
|
+
* 6. POST /internal/subgraph/finalize with the terminal status.
|
|
36
|
+
* Idempotent on the backend; retries are safe.
|
|
37
|
+
*
|
|
38
|
+
* Anything that fails along the way (network blip, bundle not ready,
|
|
39
|
+
* runtime mismatch, depth exceeded) throws a typed `SubgraphFallback`
|
|
40
|
+
* with `.reason` so `sub-graph-executor.js` can re-route to HTTP.
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* Typed marker that callers should drop back to the HTTP/trigger path.
|
|
44
|
+
* Carries `.reason` for observability + a Boolean tag so a `catch` block
|
|
45
|
+
* can `if (e.fallback)` without instanceof-juggling across module loads.
|
|
46
|
+
*/
|
|
47
|
+
export declare class SubgraphFallback extends Error {
|
|
48
|
+
detail?: any;
|
|
49
|
+
fallback?: any;
|
|
50
|
+
reason?: any;
|
|
51
|
+
constructor(reason: any, detail: any);
|
|
52
|
+
}
|
|
1
53
|
/**
|
|
2
54
|
* Run `workflowName` in-process inside the parent's Fargate task.
|
|
3
55
|
*
|
|
@@ -30,21 +82,15 @@
|
|
|
30
82
|
* these through, do NOT fall back, because
|
|
31
83
|
* HTTP would fail the same way.
|
|
32
84
|
*/
|
|
33
|
-
export function runInProcessSubgraph(workflowName:
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
signal?: AbortSignal;
|
|
37
|
-
parentAgent?: object;
|
|
38
|
-
output?: string | Function;
|
|
39
|
-
}): Promise<{
|
|
40
|
-
finalState: object;
|
|
41
|
-
executionId: string;
|
|
85
|
+
export declare function runInProcessSubgraph(workflowName: any, options?: any): Promise<{
|
|
86
|
+
finalState: any;
|
|
87
|
+
executionId: any;
|
|
42
88
|
}>;
|
|
43
89
|
/** Best-effort cache size probe. Returns total bytes under CACHE_ROOT
|
|
44
90
|
* or 0 if nothing yet. Used by metrics + by `evictCacheIfOver()` below. */
|
|
45
|
-
export function getCacheStats(): {
|
|
91
|
+
export declare function getCacheStats(): {
|
|
46
92
|
bytes: number;
|
|
47
|
-
entries:
|
|
93
|
+
entries: number;
|
|
48
94
|
};
|
|
49
95
|
/**
|
|
50
96
|
* LRU-ish cache eviction. Called opportunistically after each successful
|
|
@@ -58,9 +104,7 @@ export function getCacheStats(): {
|
|
|
58
104
|
* on each fresh extract, so cold versions naturally rank older. Good
|
|
59
105
|
* enough for warm-pool cleanup; not a replacement for a real LRU cache.
|
|
60
106
|
*/
|
|
61
|
-
export function evictCacheIfOver({ cap }?: {
|
|
62
|
-
cap?: number;
|
|
63
|
-
}): {
|
|
107
|
+
export declare function evictCacheIfOver({ cap }?: any): {
|
|
64
108
|
evicted: number;
|
|
65
109
|
freedBytes: number;
|
|
66
110
|
totalBytes?: undefined;
|
|
@@ -69,14 +113,3 @@ export function evictCacheIfOver({ cap }?: {
|
|
|
69
113
|
freedBytes: number;
|
|
70
114
|
totalBytes: number;
|
|
71
115
|
};
|
|
72
|
-
/**
|
|
73
|
-
* Typed marker that callers should drop back to the HTTP/trigger path.
|
|
74
|
-
* Carries `.reason` for observability + a Boolean tag so a `catch` block
|
|
75
|
-
* can `if (e.fallback)` without instanceof-juggling across module loads.
|
|
76
|
-
*/
|
|
77
|
-
export class SubgraphFallback extends Error {
|
|
78
|
-
constructor(reason: any, detail: any);
|
|
79
|
-
fallback: boolean;
|
|
80
|
-
reason: any;
|
|
81
|
-
detail: any;
|
|
82
|
-
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as Y,existsSync as I,statSync as N,readdirSync as C,rmSync as W}from"node:fs";import{spawn as j}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as Z}from"node:url";import{AsyncLocalStorage as K}from"node:async_hooks";var R=()=>{},q={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k={impl:q};var b={debug:(...e)=>k.impl.debug?.(...e),info:(...e)=>k.impl.info?.(...e),warn:(...e)=>k.impl.warn?.(...e),error:(...e)=>k.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var _=new V;function B(){let e=_.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function O(e,n){let r=_.getStore()||B(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null});return _.run(t,n)}var A=new Map,$=new Map,P=new Map;function M(e,n,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof n!="function")throw new Error("subgraph-registry.register: factory must be a function");A.set(e,n),$.set(e,"ready"),P.set(e,{...r,cachedAt:Date.now()})}function D(e,n){$.set(e,"failed"),P.set(e,{error:n?.message||String(n),failedAt:Date.now()}),A.delete(e)}function U(e){return $.get(e)==="ready"?A.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Q(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(n,r){super(`in-process sub-graph fallback: ${n}${r?` (${r})`:""}`),this.fallback=!0,this.reason=n,this.detail=r||null,this.name="SubgraphFallback"}},L=new K,H=Promise.resolve();async function ee(e,n){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(r.length===0)return n();let t=L.getStore()===!0,a=null;if(!t){let s=H;H=new Promise(i=>{a=i}),await s}let o=new Map;try{for(let[s,i]of r)o.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return b.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${t?" (nested)":""}`),await L.run(!0,n)}finally{for(let[s,i]of o)i===void 0?delete process.env[s]:process.env[s]=i;a&&a()}}function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),n=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||n,t=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!r||!t||!a)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:t,authToken:a}}async function ne({apiBase:e,authToken:n,body:r}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)})}catch(o){throw new l("network",`begin fetch failed: ${o.message}`)}let a=null;try{a=await t.json()}catch{}if(!t.ok){if(t.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(t.status===429){let o=a?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=o,s}if(t.status===400&&a?.validationErrors){let o=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=a.validationErrors,o.missing=a.missing,o}throw new l("begin-status",`begin returned ${t.status}`)}return a?.data||a}async function E({apiBase:e,authToken:n,payload:r}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});t.ok||b.warn(`[in-process subgraph] finalize returned ${t.status} for ${r.childExecutionId}`)}catch(t){b.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function re(e,n){let r=w(n,".ready"),t=w(n,"graph.mjs");if(I(r)&&I(t))return;Y(n,{recursive:!0});let a=w(n,".lock"),o=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),d=s(a,"wx");i(d),o=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!o){let s=Date.now()+3e4;for(;Date.now()<s;){if(I(r)&&I(t))return;await new Promise(i=>setTimeout(i,100))}throw new l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let g=j("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=j("tar",["-xzf","-","-C",n],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(S.stdin);let f,m,h=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(m!==0)return p(new Error(`tar exited ${m}`));d()}};g.on("close",v=>{f=v,h()}),S.on("close",v=>{m=v,h()}),g.on("error",p),S.on("error",p)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(r,"");try{i(a)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new l("bundle-extract-failed",s.message)}}async function oe(e){let n=w(e,"graph.mjs");if(!I(n))throw new l("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(Z(n).href)}catch(a){throw new l("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let t=r.default||Object.values(r).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ye(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=B(),t;try{t=te()}catch(c){throw c}b.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let a=await ne({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:n.input||{},...n.conversationId?{conversationId:n.conversationId}:{}}}),{childExecutionId:o,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:g,bundleReady:S,nodeConfigs:f}=a,m=Q();if(s&&s!==m)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new l("runtime-mismatch",`${m} vs ${s}`);if(!S||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new l("no-bundle","workflow bundle not built yet");let h=U(e);if(!h){let c=w(x,`${g}@${p||"0"}`);try{await re(i,c);try{se()}catch{}}catch(u){throw u.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{h=await oe(c),M(e,h,{workflowUuid:g,version:p,runtimeTag:s,cacheDir:c})}catch(u){throw D(e,u),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new l("import-failed",u.message)}}let v=Date.now(),G=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,F=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,J={...n.input||{},...F?{nodeConfigs:f}:{}},y,T;try{y=await ee(G,async()=>{let u=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return O({executionId:o,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(n.parentAgent,J,{signal:n.signal}))}),T=y&&typeof y=="object"&&"state"in y?y.state:y}catch(c){throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(y&&typeof y=="object"&&y.stoppedExternally){await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:T,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:T,durationMs:Date.now()-v}}),{finalState:T,executionId:o}}function we(){try{if(!I(x))return{bytes:0,entries:0};let e=C(x),n=0;for(let r of e)try{n+=z(w(x,r))}catch{}return{bytes:n,entries:e.length}}catch{return{bytes:0,entries:0}}}function z(e){let n=0,r=[e];for(;r.length;){let t=r.pop(),a;try{a=N(t)}catch{continue}if(a.isDirectory()){let o;try{o=C(t)}catch{continue}for(let s of o)r.push(w(t,s))}else n+=a.size}return n}function se({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!I(x))return{evicted:0,freedBytes:0};let n=C(x),r=[],t=0;for(let i of n){let d=w(x,i),p;try{p=N(d)}catch{continue}let g=p.isDirectory()?z(d):p.size;t+=g,r.push({name:i,full:d,size:g,mtimeMs:p.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};r.sort((i,d)=>i.mtimeMs-d.mtimeMs);let a=Math.floor(e*.7),o=0,s=0;for(let i of r){if(t-o<=a)break;if(!I(w(i.full,".lock")))try{W(i.full,{recursive:!0,force:!0}),o+=i.size,s+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return s>0&&b.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:o,totalBytes:t-o}}catch(n){return b.debug(`[sub-graph cache] evict failed: ${n.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,se as evictCacheIfOver,we as getCacheStats,ye as runInProcessSubgraph};
|
|
1
|
+
import{mkdirSync as Y,existsSync as I,statSync as N,readdirSync as C,rmSync as W}from"node:fs";import{spawn as j}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as Z}from"node:url";import{AsyncLocalStorage as K}from"node:async_hooks";var R=()=>{},q={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k={impl:q};var b={debug:(...e)=>k.impl.debug?.(...e),info:(...e)=>k.impl.info?.(...e),warn:(...e)=>k.impl.warn?.(...e),error:(...e)=>k.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var _=new V;function B(){let e=_.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function O(e,n){let r=_.getStore()||B(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null});return _.run(t,n)}var A=new Map,$=new Map,P=new Map;function M(e,n,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof n!="function")throw new Error("subgraph-registry.register: factory must be a function");A.set(e,n),$.set(e,"ready"),P.set(e,{...r,cachedAt:Date.now()})}function D(e,n){$.set(e,"failed"),P.set(e,{error:n?.message||String(n),failedAt:Date.now()}),A.delete(e)}function U(e){return $.get(e)==="ready"?A.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Q(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(n,r){super(`in-process sub-graph fallback: ${n}${r?` (${r})`:""}`),this.fallback=!0,this.reason=n,this.detail=r||null,this.name="SubgraphFallback"}},L=new K,H=Promise.resolve();async function ee(e,n){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(r.length===0)return n();let t=L.getStore()===!0,s=null;if(!t){let a=H;H=new Promise(i=>{s=i}),await a}let o=new Map;try{for(let[a,i]of r)o.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return b.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${t?" (nested)":""}`),await L.run(!0,n)}finally{for(let[a,i]of o)i===void 0?delete process.env[a]:process.env[a]=i;s&&s()}}function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),n=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||n,t=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!r||!t||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:t,authToken:s}}async function ne({apiBase:e,authToken:n,body:r}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)})}catch(o){throw new l("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await t.json()}catch{}if(!t.ok){if(t.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(t.status===429){let o=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(t.status===400&&s?.validationErrors){let o=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=s.validationErrors,o.missing=s.missing,o}throw new l("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function E({apiBase:e,authToken:n,payload:r}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});t.ok||b.warn(`[in-process subgraph] finalize returned ${t.status} for ${r.childExecutionId}`)}catch(t){b.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function re(e,n){let r=w(n,".ready"),t=w(n,"graph.mjs");if(I(r)&&I(t))return;Y(n,{recursive:!0});let s=w(n,".lock"),o=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),d=a(s,"wx");i(d),o=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!o){let a=Date.now()+3e4;for(;Date.now()<a;){if(I(r)&&I(t))return;await new Promise(i=>setTimeout(i,100))}throw new l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let y=j("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=j("tar",["-xzf","-","-C",n],{stdio:["pipe","inherit","inherit"]});y.stdout.pipe(S.stdin);let f,m,h=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(m!==0)return p(new Error(`tar exited ${m}`));d()}};y.on("close",v=>{f=v,h()}),S.on("close",v=>{m=v,h()}),y.on("error",p),S.on("error",p)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(r,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new l("bundle-extract-failed",a.message)}}async function oe(e){let n=w(e,"graph.mjs");if(!I(n))throw new l("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(Z(n).href)}catch(s){throw new l("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let t=r.default||Object.values(r).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ge(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=B(),t;try{t=te()}catch(c){throw c}b.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await ne({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:n.input||{},...n.conversationId?{conversationId:n.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:y,bundleReady:S,nodeConfigs:f}=s,m=Q();if(a&&a!==m)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new l("runtime-mismatch",`${m} vs ${a}`);if(!S||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new l("no-bundle","workflow bundle not built yet");let h=U(e);if(!h){let c=w(x,`${y}@${p||"0"}`);try{await re(i,c);try{ae()}catch{}}catch(u){throw u.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{h=await oe(c),M(e,h,{workflowUuid:y,version:p,runtimeTag:a,cacheDir:c})}catch(u){throw D(e,u),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new l("import-failed",u.message)}}let v=Date.now(),G=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,F=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,J={...n.input||{},...F?{nodeConfigs:f}:{}},g,T;try{g=await ee(G,async()=>{let u=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return O({executionId:o,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(n.parentAgent,J,{signal:n.signal}))}),T=g&&typeof g=="object"&&"state"in g?g.state:g}catch(c){throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(g&&typeof g=="object"&&g.stoppedExternally){await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:T,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:T,durationMs:Date.now()-v}}),{finalState:T,executionId:o}}function we(){try{if(!I(x))return{bytes:0,entries:0};let e=C(x),n=0;for(let r of e)try{n+=z(w(x,r))}catch{}return{bytes:n,entries:e.length}}catch{return{bytes:0,entries:0}}}function z(e){let n=0,r=[e];for(;r.length;){let t=r.pop(),s;try{s=N(t)}catch{continue}if(s.isDirectory()){let o;try{o=C(t)}catch{continue}for(let a of o)r.push(w(t,a))}else n+=s.size}return n}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!I(x))return{evicted:0,freedBytes:0};let n=C(x),r=[],t=0;for(let i of n){let d=w(x,i),p;try{p=N(d)}catch{continue}let y=p.isDirectory()?z(d):p.size;t+=y,r.push({name:i,full:d,size:y,mtimeMs:p.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};r.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let i of r){if(t-o<=s)break;if(!I(w(i.full,".lock")))try{W(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&b.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:t-o}}catch(n){return b.debug(`[sub-graph cache] evict failed: ${n.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,ae as evictCacheIfOver,we as getCacheStats,ge as runInProcessSubgraph};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,45 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @zibby/workflow — graph-based AI agent workflow orchestration.
|
|
3
|
+
*
|
|
4
|
+
* Quick start:
|
|
5
|
+
*
|
|
6
|
+
* import { WorkflowGraph, AgentStrategy, registerStrategy } from '@zibby/workflow';
|
|
7
|
+
*
|
|
8
|
+
* // 1. Implement your agent
|
|
9
|
+
* class MyAgent extends AgentStrategy {
|
|
10
|
+
* constructor() { super('my-agent', 'My custom agent'); }
|
|
11
|
+
* canHandle() { return true; }
|
|
12
|
+
* async invoke(prompt, options) { ... }
|
|
13
|
+
* }
|
|
14
|
+
* registerStrategy(new MyAgent());
|
|
15
|
+
*
|
|
16
|
+
* // 2. Build a graph
|
|
17
|
+
* const graph = new WorkflowGraph();
|
|
18
|
+
* graph
|
|
19
|
+
* .addNode('step1', { name: 'step1', prompt: 'Do X', outputSchema: myZodSchema })
|
|
20
|
+
* .addNode('step2', { name: 'step2', prompt: 'Do Y', outputSchema: myZodSchema })
|
|
21
|
+
* .addEdge('step1', 'step2')
|
|
22
|
+
* .setEntryPoint('step1');
|
|
23
|
+
*
|
|
24
|
+
* // 3. Run
|
|
25
|
+
* const result = await graph.run(null, { agentType: 'my-agent', cwd: process.cwd() });
|
|
26
|
+
*/
|
|
27
|
+
export { WorkflowGraph, WorkflowGraph as Graph } from './graph.js';
|
|
28
|
+
export { dispatchSubgraph } from './sub-graph-executor.js';
|
|
29
|
+
export { generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession, } from './graph.js';
|
|
30
|
+
export { Node } from './node.js';
|
|
31
|
+
export { WorkflowState } from './state.js';
|
|
32
|
+
export { OutputParser, SchemaTypes } from './output-parser.js';
|
|
33
|
+
export { ContextLoader } from './context-loader.js';
|
|
34
|
+
export { compileGraph, validateGraphConfig, extractSteps, CompilationError } from './graph-compiler.js';
|
|
35
|
+
export { registerNode, getNodeImpl, hasNode, listNodeTypes, getNodeTemplate } from './node-registry.js';
|
|
36
|
+
export { registerSkill, getSkill, getSkillSource, hasSkill, getAllSkills, listSkillIds, clearSkills } from './skill-registry.js';
|
|
37
|
+
export { resolveNodeTools, getResolvedToolDefinitions, NODE_DEFAULT_TOOLS } from './tool-resolver.js';
|
|
38
|
+
export { validateStoreDefs, STORE_NAME_REGEX } from './stores.js';
|
|
39
|
+
export { AgentStrategy } from './agents/base.js';
|
|
40
|
+
export { registerStrategy, listStrategies, getAgentStrategy, invokeAgent } from './strategy-registry.js';
|
|
41
|
+
export { generateWorkflowCode, generateNodeConfigsJson } from './code-generator.js';
|
|
42
|
+
export { setLogger } from './logger.js';
|
|
43
|
+
export { NO_INTEGRATION_TOGGLEABLE_SKILL_IDS, DEFAULT_OUTPUT_BASE, SESSIONS_DIR, SESSION_INFO_FILE, STOP_REQUEST_FILE, RESULT_FILE, RAW_OUTPUT_FILE, EVENTS_FILE, CI_ENV_VARS, } from './constants.js';
|
|
44
|
+
export { timeline, Timeline, WORKFLOW_GRAPH_LOG_MARKER_PREFIX } from './timeline.js';
|
|
45
|
+
export { COMPOSE_KNOWLEDGE } from './compose-knowledge.js';
|