@zibby/agent-workflow 0.4.31 → 0.4.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graph-compiler.js +16 -16
- package/dist/graph.js +20 -20
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +22 -22
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph-compiler.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
1
|
+
var jt=Object.defineProperty;var ye=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ie=(o,e)=>()=>(o&&(e=o(o=0)),e);var Fe=(o,e)=>{for(var t in e)jt(o,t,{get:e[t],enumerable:!0})};var He,Ut,le,I,W=ie(()=>{He=()=>{},Ut={debug:He,info:He,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:Ut},I={debug:(...o)=>le.impl.debug?.(...o),info:(...o)=>le.impl.info?.(...o),warn:(...o)=>le.impl.warn?.(...o),error:(...o)=>le.impl.error?.(...o)}});var tt=ie(()=>{});var ot={};Fe(ot,{clearSkills:()=>zt,getAllSkills:()=>Yt,getSkill:()=>Q,hasSkill:()=>Jt,listSkillIds:()=>Zt,registerSkill:()=>Ht});function Ht(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");q.set(o.id,Object.freeze({...o}))}function Q(o){return q.get(o)||null}function Jt(o){return q.has(o)}function Yt(){return new Map(q)}function Zt(){return Array.from(q.keys())}function zt(){q.clear()}var be,q,de=ie(()=>{be=Symbol.for("@zibby/agent-workflow.skills");globalThis[be]||(globalThis[be]=new Map);q=globalThis[be]});var ee={};Fe(ee,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Kt});function Kt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function qt(){return G.map(o=>o.getName())}function rt(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}I.debug(`[workflow] agent selection: requested=${r}`);let a=G.find(s=>s.getName()===r);if(!a){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!a.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${a.getName()}`),a}async function Vt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},a={...e,state:r},s=rt(a),n=r.config||t.config||{},i=n.models||{},u=t.nodeName&&i[t.nodeName]||null,d=i.default||null,h=n.agent?.[s.name]?.model||null,l=u||d||h||t.model||null,c={...t,model:l,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},m=o,S=c.skills||[];if(S.length>0&&!t.skipPromptFragments){let E=S.map(g=>{let f=Q(g)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);E.length>0&&(m+=`
|
|
2
2
|
|
|
3
3
|
${E.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let E=_.length<=8,
|
|
5
|
+
`)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let E=_.length<=8,g=_.map(f=>{let y=f?.id??f?.storeId??"",p=(f?.name??"").toString().trim()||y,b=f?.type?` \xB7 ${f.type}`:"",A=(f?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${A||"(no description)"}${b} (id: ${y})`;if(E&&f?.schema&&typeof f.schema=="object"){let w=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);w.length&&(R+=`
|
|
6
6
|
fields: ${w.join(", ")}`)}return R});m+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
9
|
+
${g.join(`
|
|
10
10
|
`)}`}let v=r._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(m+=`
|
|
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
|
|
@@ -14,14 +14,14 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${v}
|
|
17
|
-
`),I.debug(`[workflow] prompt length: ${m.length} chars`),
|
|
17
|
+
`),I.debug(`[workflow] prompt length: ${m.length} chars`),s.invoke(m,c)}var $e,G,te=ie(()=>{tt();W();de();$e=Symbol.for("@zibby/agent-workflow.strategies");globalThis[$e]||(globalThis[$e]=[]);G=globalThis[$e]});var Lt=new Set(["__proto__","constructor","prototype"]);function we(o){if(Lt.has(o))throw new Error(`Invalid state key: "${o}"`)}var ae=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){we(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)we(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){we(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import F from"handlebars";var ce=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(a=>a[0]);for(let a of r)try{return this.validate(JSON.parse(a))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,a]of Object.entries(this.schema)){if(a.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&a.type){let s=typeof e[r];s!==a.type&&t.push(`Field '${r}' expected ${a.type}, got ${s}`)}if(a.validate&&r in e){let s=a.validate(e[r]);s&&t.push(`Field '${r}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}};W();import{writeFileSync as
|
|
20
|
-
`?(
|
|
21
|
-
${ze}`,e.col=Ke))}return o(
|
|
19
|
+
`)}`);return e}};W();import{writeFileSync as ve,readFileSync as nt,existsSync as st,mkdirSync as Xt}from"node:fs";import{join as Te,dirname as Qt}from"node:path";import x from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Gt=x.gray("\u250C"),Je=x.gray("\u2514"),_e=x.green("\u25C6"),Ye=x.hex("#c084fc")("\u25C6"),Ze=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),ze=`${X} `,Ke=2;function qe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ve(o,e){return(t,r,a)=>{if(typeof t!="string")return o(t,r,a);let s=process.stdout.columns||120,n="";for(let i=0;i<t.length;i++){let u=t[i];e.lineStart&&(n+=ze,e.col=Ke,e.lineStart=!1),u===`
|
|
20
|
+
`?(n+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,n+=u):e.inEsc?(n+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,n+=u,e.col>=s&&(n+=`
|
|
21
|
+
${ze}`,e.col=Ke))}return o(n,r,a)}}var Ee=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${
|
|
24
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Wt}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
@@ -29,22 +29,22 @@ ${ze}`,e.col=Ke))}return o(s,r,a)}}var Ee=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ye,e):process.stdout.write.bind(process.stdout)(`${X} ${Ye} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Ze,t):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${t}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${x.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Gt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:a}=t;if(a)for(let n of a)this._rawWrite(`${_e} ${n}`);let s=r?x.dim(` ${qe(r)}`):"";this._rawWrite(`${Je} ${x.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:a}=r,s=a?x.dim(` ${qe(a)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${Je} ${x.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var ue=".zibby/output",Xe="sessions",K=".session-info.json",Qe=".zibby-stop";var Ft={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Ho=Object.freeze([Ft.CODEBASE_MEMORY]),et=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",o=>Number(o)+1);F.helpers.json||F.registerHelper("json",o=>JSON.stringify(o,null,2));F.helpers.eq||F.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ce(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,a=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return I.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=a("_skillHints");n&&(s=`${n}
|
|
33
33
|
|
|
34
|
-
${n}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Ae(d,K);if(st(l)){let m=JSON.parse(nt(l,"utf-8"));m.currentNode=this.name,Te(l,JSON.stringify(m,null,2),"utf-8")}let c=Ae(d,"..",K);if(st(c))try{let m=JSON.parse(nt(c,"utf-8"));m.currentNode=this.name,Te(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let p=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},S=this.config.agent??m[this.name]??null,_={state:r()};S&&(_.preferredAgent=S);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let f=await E(n,_,v),h,y;if(typeof f=="string"?(h=f,y=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(h=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),d)try{let g=Ae(d,this.name,"raw_stream_output.txt");qt(Vt(g),{recursive:!0}),Te(g,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(g){I.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let g=y;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),y)}catch($){I.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:g,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:h}),raw:h}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(h);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),O.step("Output parsed"),{success:!0,output:g,raw:h}}return{success:!0,output:h,raw:h}}catch(c){p=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}};W();W();import{mkdirSync as eo,existsSync as J,statSync as pt,readdirSync as ft,rmSync as to}from"node:fs";import{spawn as dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as oo}from"node:url";import{AsyncLocalStorage as Xt}from"node:async_hooks";var ve=new Xt;function oe(){let o=ve.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function it(o,e){let t=ve.getStore()||oe(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return ve.run(r,e)}var ke=new Map,xe=new Map,at=new Map;function ct(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ke.set(o,e),xe.set(o,"ready"),at.set(o,{...t,cachedAt:Date.now()})}function lt(o,e){xe.set(o,"failed"),at.set(o,{error:e?.message||String(e),failedAt:Date.now()}),ke.delete(o)}function ut(o){return xe.get(o)==="ready"?ke.get(o):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ro(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function no(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!t||!r||!a)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:a}}async function so({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(n){throw new N("network",`begin fetch failed: ${n.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let n=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(r.status===429){let n=a?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=n,s}if(r.status===400&&a?.validationErrors){let n=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=a.validationErrors,n.missing=a.missing,n}throw new N("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function H({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function io(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;eo(e,{recursive:!0});let a=U(e,".lock"),n=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),u=s(a,"wx");i(u),n=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!n){let s=Date.now()+3e4;for(;Date.now()<s;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let p=dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(l.stdin);let c,m,S=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};p.on("close",_=>{c=_,S()}),l.on("close",_=>{m=_,S()}),p.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(t,"");try{i(a)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new N("bundle-extract-failed",s.message)}}async function ao(o){let e=U(o,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(oo(e).href)}catch(a){throw new N("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=t.default||Object.values(t).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new N("entry-class-missing","no buildGraph() class export found");return r}async function ht(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=no()}catch($){throw $}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let a=await so({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:n,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:p,bundleReady:l,nodeConfigs:c}=a,m=ro();if(s&&s!==m)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${m} vs ${s}`);if(!l||!i)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new N("no-bundle","workflow bundle not built yet");let S=ut(o);if(!S){let $=U(pe,`${p}@${d||"0"}`);try{await io(i,$);try{lo()}catch{}}catch(b){throw b.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{S=await ao($),ct(o,S,{workflowUuid:p,version:d,runtimeTag:s,cacheDir:$})}catch(b){throw lt(o,b),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let _=Date.now(),E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph(),f=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...f?{nodeConfigs:c}:{}},y,g;try{y=await it({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,h,{signal:e.signal})),g=y&&typeof y=="object"&&"state"in y?y.state:y}catch($){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:$.message,code:$.code||"CHILD_THREW",stack:$.stack},durationMs:Date.now()-_}}),$}if(y&&typeof y=="object"&&y.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-_}});let $=new Error(`Sub-graph '${o}' canceled by parent abort`);throw $.code="SUBGRAPH_CANCELED",$.subgraphJobId=n,$}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-_}}),{finalState:g,executionId:n}}function co(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),a;try{a=pt(r)}catch{continue}if(a.isDirectory()){let n;try{n=ft(r)}catch{continue}for(let s of n)t.push(U(r,s))}else e+=a.size}return e}function lo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=ft(pe),t=[],r=0;for(let i of e){let u=U(pe,i),d;try{d=pt(u)}catch{continue}let p=d.isDirectory()?co(u):d.size;r+=p,t.push({name:i,full:u,size:p,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,u)=>i.mtimeMs-u.mtimeMs);let a=Math.floor(o*.7),n=0,s=0;for(let i of t){if(r-n<=a)break;if(!J(U(i.full,".lock")))try{to(i.full,{recursive:!0,force:!0}),n+=i.size,s+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:n,totalBytes:r-n}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var uo=2e3,po=600*1e3,fo=new Set(["completed","failed","canceled","timeout"]);function ho(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function go(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function mo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function So(){return process.env.EXECUTION_ID||null}function gt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function mt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await ht(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),g=gt(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),g}catch(y){if(y instanceof N||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let a=ho(),n=go(),s=mo(),i=So(),u=`${a}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!p.ok){let y=null,g="";try{y=await p.json(),g=y?.error||y?.message||JSON.stringify(y)}catch{g=await p.text().catch(()=>"")}if(p.status===429){let b=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${b.used??"?"}/${b.limit??"?"} on plan ${b.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=b,R}if(p.status===400){let b=new Error(`Sub-graph '${o}' rejected input: ${g}`);throw b.code="SUBGRAPH_INVALID_INPUT",b.status=400,b.subgraph=o,b.validationErrors=y?.validationErrors||null,b.missing=y?.missing||null,b}let $=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${g}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=p.status,$.subgraph=o,$}let l=await p.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:po,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:uo,_=`${a}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,E="accepted",f=0;for(;Date.now()<v;){await new Promise(b=>setTimeout(b,S)),f+=1;let y=await fetch(_,{headers:{Authorization:`Bearer ${s}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let g=await y.json(),$=g?.data||g?.execution||g;if(E=$?.status||E,fo.has(E)){if(E!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${E}'`);throw w.subgraphJobId=c,w.subgraphStatus=E,w}let b=$?.finalState||$?.state||{},R=gt(b,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${f} polls`),R}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${E})`);throw h.subgraphJobId=c,h.subgraphStatus=E,h}import{existsSync as St,readFileSync as yo}from"node:fs";import{join as Oe,dirname as yt}from"node:path";var fe=class{static async loadContext(e,t,r={}){let a={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=yt(Oe(t,e));for(let u of n){let d=await this.findAndMergeContextFiles(u,i,t);if(d){let p=u.replace(/\.[^.]+$/,"").toLowerCase();a[p]=d}}}let s=r.discovery||{};for(let[i,u]of Object.entries(s))try{let d=Oe(t,u);St(d)&&(a[i]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${i}' from '${u}': ${d.message}`)}return a}static async findAndMergeContextFiles(e,t,r){let a=[],n=t;for(;n.startsWith(r);){let s=Oe(n,e);if(St(s))try{a.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let i=yt(n);if(i===n)break;n=i}return a.length===0?null:a.every(s=>typeof s=="string")?a.join(`
|
|
34
|
+
${s}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Te(d,K);if(st(l)){let m=JSON.parse(nt(l,"utf-8"));m.currentNode=this.name,ve(l,JSON.stringify(m,null,2),"utf-8")}let c=Te(d,"..",K);if(st(c))try{let m=JSON.parse(nt(c,"utf-8"));m.currentNode=this.name,ve(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},S=this.config.agent??m[this.name]??null,_={state:r()};S&&(_.preferredAgent=S);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let g=await E(s,_,v),f,y;if(typeof g=="string"?(f=g,y=null):g.structured?(f=g.raw||JSON.stringify(g.structured,null,2),y=g.structured):(f=g.raw||JSON.stringify(g,null,2),y=g.extracted||null),d)try{let p=Te(d,this.name,"raw_stream_output.txt");Xt(Qt(p),{recursive:!0}),ve(p,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),y)}catch(b){I.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:p,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:f}),raw:f}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(f);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:f}}return{success:!0,output:f,raw:f}}catch(c){h=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};W();W();import{mkdirSync as oo,existsSync as J,statSync as ht,readdirSync as gt,rmSync as ro}from"node:fs";import{spawn as dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as no}from"node:url";import{AsyncLocalStorage as so}from"node:async_hooks";import{AsyncLocalStorage as eo}from"node:async_hooks";var Ae=new eo;function oe(){let o=Ae.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function it(o,e){let t=Ae.getStore()||oe(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Ae.run(r,e)}var ke=new Map,xe=new Map,at=new Map;function ct(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ke.set(o,e),xe.set(o,"ready"),at.set(o,{...t,cachedAt:Date.now()})}function lt(o,e){xe.set(o,"failed"),at.set(o,{error:e?.message||String(e),failedAt:Date.now()}),ke.delete(o)}function ut(o){return xe.get(o)==="ready"?ke.get(o):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function io(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},pt=new so,ft=Promise.resolve();async function ao(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,i])=>typeof n=="string"&&n&&typeof i=="string"):[];if(t.length===0)return e();let r=pt.getStore()===!0,a=null;if(!r){let n=ft;ft=new Promise(i=>{a=i}),await n}let s=new Map;try{for(let[n,i]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=i;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await pt.run(!0,e)}finally{for(let[n,i]of s)i===void 0?delete process.env[n]:process.env[n]=i;a&&a()}}function co(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!t||!r||!a)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:a}}async function lo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new N("network",`begin fetch failed: ${s.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=a?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&a?.validationErrors){let s=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=a.validationErrors,s.missing=a.missing,s}throw new N("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function H({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function uo(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;oo(e,{recursive:!0});let a=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:i}=await import("node:fs"),u=n(a,"wx");i(u),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,m,S=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};h.on("close",_=>{c=_,S()}),l.on("close",_=>{m=_,S()}),h.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:i}=await import("node:fs");n(t,"");try{i(a)}catch{}}catch(n){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new N("bundle-extract-failed",n.message)}}async function po(o){let e=U(o,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(no(e).href)}catch(a){throw new N("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=t.default||Object.values(t).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new N("entry-class-missing","no buildGraph() class export found");return r}async function mt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=co()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let a=await lo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:i,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=a,m=io();if(n&&n!==m)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${m} vs ${n}`);if(!l||!i)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new N("no-bundle","workflow bundle not built yet");let S=ut(o);if(!S){let p=U(pe,`${h}@${d||"0"}`);try{await uo(i,p);try{ho()}catch{}}catch(b){throw b.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{S=await po(p),ct(o,S,{workflowUuid:h,version:d,runtimeTag:n,cacheDir:p})}catch(b){throw lt(o,b),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let _=Date.now(),v=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,E=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...E?{nodeConfigs:c}:{}},f,y;try{f=await ao(v,async()=>{let b=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return it({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>b.run(e.parentAgent,g,{signal:e.signal}))}),y=f&&typeof f=="object"&&"state"in f?f.state:f}catch(p){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-_}}),p}if(f&&typeof f=="object"&&f.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:y,durationMs:Date.now()-_}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-_}}),{finalState:y,executionId:s}}function fo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),a;try{a=ht(r)}catch{continue}if(a.isDirectory()){let s;try{s=gt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=a.size}return e}function ho({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=gt(pe),t=[],r=0;for(let i of e){let u=U(pe,i),d;try{d=ht(u)}catch{continue}let h=d.isDirectory()?fo(u):d.size;r+=h,t.push({name:i,full:u,size:h,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,u)=>i.mtimeMs-u.mtimeMs);let a=Math.floor(o*.7),s=0,n=0;for(let i of t){if(r-s<=a)break;if(!J(U(i.full,".lock")))try{ro(i.full,{recursive:!0,force:!0}),s+=i.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var go=2e3,mo=600*1e3,So=new Set(["completed","failed","canceled","timeout"]);function yo(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function wo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function _o(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Io(){return process.env.EXECUTION_ID||null}function St(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function yt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await mt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=St(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let a=yo(),s=wo(),n=_o(),i=Io(),u=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!h.ok){let y=null,p="";try{y=await h.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let A=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' 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 R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=A,R}if(h.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=y?.validationErrors||null,A.missing=y?.missing||null,A}let b=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${p}`);throw b.code="SUBGRAPH_TRIGGER_FAILED",b.status=h.status,b.subgraph=o,b}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:mo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:go,_=`${a}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,E="accepted",g=0;for(;Date.now()<v;){await new Promise(A=>setTimeout(A,S)),g+=1;let y=await fetch(_,{headers:{Authorization:`Bearer ${n}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),b=p?.data||p?.execution||p;if(E=b?.status||E,So.has(E)){if(E!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${E}'`);throw w.subgraphJobId=c,w.subgraphStatus=E,w}let A=b?.finalState||b?.state||{},R=St(A,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${g} polls`),R}}let f=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${E})`);throw f.subgraphJobId=c,f.subgraphStatus=E,f}import{existsSync as wt,readFileSync as Eo}from"node:fs";import{join as Oe,dirname as _t}from"node:path";var fe=class{static async loadContext(e,t,r={}){let a={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=_t(Oe(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,i,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();a[h]=d}}}let n=r.discovery||{};for(let[i,u]of Object.entries(n))try{let d=Oe(t,u);wt(d)&&(a[i]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${i}' from '${u}': ${d.message}`)}return a}static async findAndMergeContextFiles(e,t,r){let a=[],s=t;for(;s.startsWith(r);){let n=Oe(s,e);if(wt(n))try{a.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let i=_t(s);if(i===s)break;s=i}return a.length===0?null:a.every(n=>typeof n=="string")?a.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):a.every(
|
|
38
|
+
`):a.every(n=>typeof n=="object")?Object.assign({},...a):a[a.length-1]}static async loadFile(e){let t=Eo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),a=await import(r(e).href);return a.default||a}return t}};import{mkdirSync as bt,existsSync as Ne,writeFileSync as It,unlinkSync as bo}from"node:fs";import{join as Y,resolve as $t}from"node:path";import{config as $o}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import vo from"handlebars";function To({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:a}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${a?"yes":"no"} path=${t}`;if(console.log(i),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${p}`)}}function bo(){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 $o(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Et(String(e).trim())}catch{return String(e).trim()}}function To(){bo()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ao({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function vo(o={}){let e=et.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function ko({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,n=t.sessionTimestamp,s="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=Et(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,s="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,s="config.sessionId"):(i=vo(e),s="generated")}n=n??Date.now();let p=e.paths?.output||ue;a=Y(o,p,Xe,i)}let u=!Ne(a);return u&&It(a,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Eo({traceFrom:r,sessionId:i,sessionPath:a,idSource:s,mkdirFresh:u}),Ao({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:n}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let p=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(p):s.input&&typeof s.input=="object"?l=s.input:l={},mt(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(p):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:p?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,n=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return n.name=e,this.nodes.set(e,n),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,n){let s=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=s;s=()=>u(t,d,a,n)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let g=c.prompt({});typeof g=="string"&&g.trim()&&(S.prompt=g,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let g=null;if(typeof he?.toJSONSchema=="function")try{g=he.toJSONSchema(c.outputSchema)}catch{}if(!g)try{g=_t(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(S.skills=[...f]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(S.plugins=h.map(g=>g&&typeof g=="object"?{...g}:g));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,f=l;if(!E){let h=`${l}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),r.push({source:l,target:h}),f=h}for(let h of S){let y={source:f,target:h,data:{conditionalCode:m}};_[h]&&(y.label=_[h]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return _t(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let n=0;for(let l of r)if(l.target==="END"){n+=1;let c=`END__${n}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){n+=1;let c=`END__${n}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let s=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),p=a(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:p}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),n=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&n.has(l.target)&&(s.get(l.source).push(l.target),n.set(l.target,n.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>n.get(l)===0),p=[];for(;p.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),p.push(a.get(l));for(let c of s.get(l)||[])n.set(c,n.get(c)-1),n.get(c)<=0&&!i.has(c)&&d.push(c)}return p}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=n.exec(r))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=d.exec(r))!==null;)u.add(p[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},n=e.required||[];for(let[s,i]of Object.entries(a)){let u=t?`${t}.${s}`:s;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(s),optional:!n.includes(s)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,n]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${a}: ${n}`);else if(Array.isArray(n)){let s=n.length,i=n.filter(d=>d?.passed===!0).length,u=n.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${s} passed${s-i?`, ${s-i} failed`:""}`:`${a}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let n=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();_o({path:Y(s,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let T=Y(s,".zibby.config.js");Ne(T)&&(i=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let T=i?.agent;T?.provider?u=T.provider:T?.gemini?u="gemini":T?.claude?u="claude":T?.cursor?u="cursor":T?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},p=this._runtimeSchema();if(p){let T=p.safeParse(t);if(!T.success){let P=T.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=$o(),c=t.sessionPath||l;c||To();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=ko({cwd:s,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),g=i.skills&&typeof i.skills=="object"?i.skills:{},$=Object.values(g).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),b=T=>{for(let P of $)if(P.id===T)return P;return y(T)},R=new Set;for(let[,T]of this.nodes)for(let P of T.config?.skills||[])R.add(P);for(let T of R){let P=b(T);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&h.set(T,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,vt=0;try{for(;w&&w!=="END";){if(++vt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{wo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:
|
|
43
|
-
${
|
|
41
|
+
${h}`)}}function Ao(){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 ko(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return $t(String(e).trim())}catch{return String(e).trim()}}function xo(){Ao()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Oo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function No(o={}){let e=et.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function Po({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=$t(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,n="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,n="config.sessionId"):(i=No(e),n="generated")}s=s??Date.now();let h=e.paths?.output||ue;a=Y(o,h,Xe,i)}let u=!Ne(a);return u&&bt(a,{recursive:!0}),(u||n!=="initialState.sessionPath")&&To({traceFrom:r,sessionId:i,sessionPath:a,idSource:n,mkdirFresh:u}),Oo({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:s}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},yt(n.workflow,{input:l,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:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,s){let n=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=n;n=()=>u(t,d,a,s)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Et(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(S.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(S.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!E){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of S){let y={source:g,target:f,data:{conditionalCode:m}};_[f]&&(y.label=_[f]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return Et(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of r)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),h=a(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&s.has(l.target)&&(n.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>s.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),h.push(a.get(l));for(let c of n.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!i.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},s=e.required||[];for(let[n,i]of Object.entries(a)){let u=t?`${t}.${n}`:n;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(n),optional:!s.includes(n)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,s]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${a}: ${s}`);else if(Array.isArray(s)){let n=s.length,i=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${n} passed${n-i?`, ${n-i} failed`:""}`:`${a}: ${n} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();$o({path:Y(n,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let $=Y(n,".zibby.config.js");Ne($)&&(i=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let $=i?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let P=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=ko(),c=t.sessionPath||l;c||xo();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=Po({cwd:n,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),p=i.skills&&typeof i.skills=="object"?i.skills:{},b=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),A=$=>{for(let P of b)if(P.id===$)return P;return y($)},R=new Set;for(let[,$]of this.nodes)for(let P of $.config?.skills||[])R.add(P);for(let $ of R){let P=A($);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,xt=0;try{for(;w&&w!=="END";){if(++xt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{bo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let Me=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:w,createdAt:new Date().toISOString(),config:g.get("config")}),Ot=Y(m,K);It(Ot,Me,"utf-8");let De=g.get("config")?.paths?.output||ue,Nt=Y(n,De,K);bt(Y(n,De),{recursive:!0});try{It(Nt,Me,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:n,sessionPath:m,sessionId:_,outputBase:g.get("config")?.paths?.output||ue,currentNode:w})}catch{}let Pt=(this.resolvedToolsMap||{})[w]||null;g.set("_currentNodeTools",Pt);let Ct=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",Ct[w]||{}),O.nodeStart(w);let Le=Date.now(),ne=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,Se={},Bt=C.config?.skills||[];for(let k of Bt){let B=A(k);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Ue=async(k,B,T={})=>{let M=Rt(k,B,{...Se,...T,signal:a.signal});return M.catch(()=>{}),a.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let j=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);V.name="AbortError",z(V)},s)};a.signal.addEventListener("abort",j,{once:!0})})])},Mt=async(k={},B={})=>{let T=B.prompt||"";if(ne){let M=this._compiledPrompts.get(w);M||(M=vo.compile(ne,{noEscape:!0}),this._compiledPrompts.set(w,M));try{T=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Ue(T,{state:g.getAll(),images:B.images||[]},{model:B.model||g.get("model"),workspace:g.get("workspace"),schema:B.schema,...B,signal:a.signal})},We=g.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Dt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ge={...We,state:g,invokeAgent:Mt,_coreInvokeAgent:Ue,agent:e,nodeId:w,promptTemplate:ne,getPromptTemplate:()=>ne};try{let k=(C.config?.skills||[]).map(j=>f.get(j)).filter(Boolean),B=[...this.middleware,...k],T;B.length>0?T=await this._composeMiddleware(B,w,async()=>C.execute(Ge,g),g.getAll(),g):T=await C.execute(Ge,g);let M=Date.now()-Le;if(re.push({node:w,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(a.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};g.append("errors",{node:w,error:T.error});let j=C.config?.retries||0,V=`${w}_retries`,se=g.getAll()[V]||0;if(se<j){O.stepInfo(`Retrying (attempt ${se+1}/${j})`),g.update({[V]:se+1,[`${w}_raw`]:T.raw});continue}throw O.nodeFailed(w,T.error,{duration:M}),new Error(`Node '${w}' failed after ${se} attempts: ${T.error}`)}g.update({[w]:T.output});let Z=this._summarizeNodeOutput(w,T.output);O.nodeComplete(w,{duration:M,details:Z});let z=this.edges.get(w);if(!z)w="END";else if(z.conditional){let j=z.routes(g.getAll());O.route(w,j),w=j}else w=z}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Le}),g.set("failed",!0),g.set("failedAt",w),k}}O.graphComplete();let $={success:!0,state:g.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete($),$}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch($){console.warn(`[workflow] agent.cleanup() failed: ${$.message}`)}}}};var Pe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Pe]||(globalThis[Pe]=new Map);var Ce=globalThis[Pe];function Co(o,e){Ce.set(o,e)}function vt(o){return Ce.get(o)}function Re(o){return Ce.has(o)}Co("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let a=e.extraPromptInstructions||"Execute the task based on the current state.",s=Ro(a,t),n=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Ro(o,e){let t=/@([\w.]+)/g,r=new Set,a;for(;(a=t.exec(o))!==null;)r.add(a[1]);if(r.size===0)return o;let s=[],n=new Set;for(let i of r){let u=i.split(".")[0];if(n.has(u))continue;let d=i.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=i.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
|
|
43
|
+
${h}`),i.includes(".")||n.add(u)}return s.length===0?o:`${o}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
|
-
${
|
|
48
|
+
${s.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}de();W();var
|
|
50
|
+
`)}`}de();W();var Bo={};function At(o,e){if(Array.isArray(e))return Tt(e);let t=Bo[o];return!t||t.length===0?null:Tt(t)}function Tt(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let a of o){let s=Q(a);if(!s){I.warn(`[workflow] unknown skill "${a}" \u2014 skipping`);continue}r.push(a);for(let n of s.tools||[])e.push({name:n.name,description:n.description,input_schema:n.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let n=s.resolve();n&&(t[s.serverName]={...n,toolPrefix:a})}else{let n={};for(let i of s.envKeys||[]){let u=process.env[i];u&&(n[i]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:n,toolPrefix:a}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}W();function Fr(o,e={}){let{nodes:t,edges:r,nodeConfigs:a={}}=o;if(!Array.isArray(t)||t.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(r))throw new D("Graph edges must be an array");let s=new ge(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let n=new Set,i=new Map,u={};for(let c of t){let m=me(c);i.set(c.id,{...c,resolvedType:m}),m==="decision"&&n.add(c.id)}for(let[c,m]of i){if(n.has(c))continue;let S=m.resolvedType,_=a[c]||{},v=At(S,_.tools);v&&(u[c]=v);let E={};_.prompt&&(E.prompt=_.prompt);let g=Re(S);if(I.debug(`[workflow] compiler: node "${c}" type="${S}" registered=${g}`),_.customCode&&!g)s.addNode(c,kt(c,_.customCode,_),E),s.setNodeType(c,S);else if(g){let f=vt(S);f.factory?s.addNode(c,f.create(c,{..._,resolvedTools:v}),E):s.addNode(c,f,E),s.setNodeType(c,S)}else if(_.executeCode)s.addNode(c,kt(c,_.executeCode,_),E),s.setNodeType(c,S);else throw new D(`Unknown node type "${S}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of r)n.has(c.target)||d.add(c.target);let h=t.find(c=>!n.has(c.id)&&!d.has(c.id));if(!h)throw new D("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(h.id);let l=Mo(r,"source");for(let c of r)if(!n.has(c.source))if(n.has(c.target)){let m=c.target,S=l.get(m)||[];if(S.length===0)throw new D(`Decision node "${m}" has no outgoing edges`);let _=Do(m,S,n);s.addConditionalEdges(c.source,_)}else s.addEdge(c.source,c.target);return s}function Hr(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let i of o.nodes){let u=me(i);if(u==="decision"||Re(u))continue;let d=t[i.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${i.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(i=>i.id));for(let i of o.edges)r.has(i.source)||e.push(`Edge references unknown source node "${i.source}"`),r.has(i.target)||e.push(`Edge references unknown target node "${i.target}"`);let a=new Set(o.nodes.filter(i=>me(i)==="decision").map(i=>i.id)),s=new Set;for(let i of o.edges)a.has(i.target)||s.add(i.target);let n=o.nodes.filter(i=>!a.has(i.id)&&!s.has(i.id));n.length===0?e.push("No entry point found (every node has incoming edges)"):n.length>1&&e.push(`Multiple entry points found: ${n.map(i=>i.id).join(", ")}`);for(let i of a){let u=o.edges.filter(h=>h.source===i);u.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${i}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Jr(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>me(e)!=="decision").map(e=>e.id)}function me(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Mo(o,e){let t=new Map;for(let r of o){let a=r[e];t.has(a)||t.set(a,[]),t.get(a).push(r)}return t}function Do(o,e,t){let r=e.find(i=>i.data?.conditionalCode||i.conditionalCode);if(!r)throw new D(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let a=r.data?.conditionalCode||r.conditionalCode,s=new Set(e.map(i=>i.target).filter(i=>!t.has(i))),n;try{let u=new Function(`return (${a})`)();n=d=>{let h=u(d);return s.has(h)||I.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...s].join(", ")}`),h}}catch(i){throw new D(`Failed to compile conditionalCode for "${o}": ${i.message}`)}return n}function kt(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(n){throw new D(`Failed to compile customCode for node "${o}": ${n.message}`)}let a=r(async(...n)=>{let{invokeAgent:i}=await Promise.resolve().then(()=>(te(),ee));return i(...n)},typeof ye<"u"?ye:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async n=>{try{let i=await a(n);return typeof i=="object"&&"success"in i?i:{success:!0,output:i,raw:null}}catch(i){return{success:!1,error:i.message,raw:null}}}}}var D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{D as CompilationError,Fr as compileGraph,Jr as extractSteps,Hr as validateGraphConfig};
|
package/dist/graph.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ke=Object.defineProperty;var rt=(o,t)=>()=>(o&&(t=o(o=0)),t);var Mt=(o,t)=>{for(var e in t)ke(o,e,{get:t[e],enumerable:!0})};var Dt,xe,nt,_,V=rt(()=>{Dt=()=>{},xe={debug:Dt,info:Dt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},nt={impl:xe},_={debug:(...o)=>nt.impl.debug?.(...o),info:(...o)=>nt.impl.info?.(...o),warn:(...o)=>nt.impl.warn?.(...o),error:(...o)=>nt.impl.error?.(...o)}});var zt=rt(()=>{});var Kt={};Mt(Kt,{clearSkills:()=>Le,getAllSkills:()=>Me,getSkill:()=>mt,hasSkill:()=>Ce,listSkillIds:()=>De,registerSkill:()=>Be});function Be(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");z.set(o.id,Object.freeze({...o}))}function mt(o){return z.get(o)||null}function Ce(o){return z.has(o)}function Me(){return new Map(z)}function De(){return Array.from(z.keys())}function Le(){z.clear()}var gt,z,St=rt(()=>{gt=Symbol.for("@zibby/agent-workflow.skills");globalThis[gt]||(globalThis[gt]=new Map);z=globalThis[gt]});var wt={};Mt(wt,{getAgentStrategy:()=>Vt,invokeAgent:()=>We,listStrategies:()=>Ue,registerStrategy:()=>je});function je(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=U.findIndex(e=>e.getName()===o.getName());t>=0?U[t]=o:U.push(o)}function Ue(){return U.map(o=>o.getName())}function Vt(o={}){let{state:t={},preferredAgent:e=null}=o,r=e||t.agentType||process.env.AGENT_TYPE;if(!r){let i=U.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}_.debug(`[workflow] agent selection: requested=${r}`);let s=U.find(i=>i.getName()===r);if(!s){let i=U.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${s.getName()}`),s}async function We(o,t={},e={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},s={...t,state:r},i=Vt(s),n=r.config||e.config||{},a=n.models||{},u=e.nodeName&&a[e.nodeName]||null,p=a.default||null,g=n.agent?.[i.name]?.model||null,c=u||p||g||e.model||null,l={...e,model:c,workspace:r.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],plugins:e.plugins||t.plugins||[],config:n},y=o,w=l.skills||[];if(w.length>0&&!e.skipPromptFragments){let b=w.map(h=>{let f=mt(h)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);b.length>0&&(y+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${b.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let $=r._currentNodeConfig?.stores;if(Array.isArray($)&&$.length>0&&typeof $[0]=="object"){let b=$.length<=8,h=$.map(f=>{let m=f?.id??f?.storeId??"",d=(f?.name??"").toString().trim()||m,I=f?.type?` \xB7 ${f.type}`:"",A=(f?.description||"").toString().replace(/\s+/g," ").trim(),B=`- ${d} \xB7 ${A||"(no description)"}${I} (id: ${m})`;if(b&&f?.schema&&typeof f.schema=="object"){let S=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);S.length&&(B+=`
|
|
6
6
|
fields: ${S.join(", ")}`)}return B});y+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${h.join(`
|
|
10
|
+
`)}`}let v=r._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(y+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),
|
|
16
|
+
${v}
|
|
17
|
+
`),_.debug(`[workflow] prompt length: ${y.length} chars`),i.invoke(y,l)}var yt,U,_t=rt(()=>{zt();V();St();yt=Symbol.for("@zibby/agent-workflow.strategies");globalThis[yt]||(globalThis[yt]=[]);U=globalThis[yt]});var Oe=new Set(["__proto__","constructor","prototype"]);function pt(o){if(Oe.has(o))throw new Error(`Invalid state key: "${o}"`)}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){pt(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let r of e)pt(r);this._history.push({...this._state});for(let r of e)this._state[r]=t[r]}append(t,e){pt(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import W from"handlebars";var 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 r=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of r)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[r,s]of Object.entries(this.schema)){if(s.required&&!(r in t)&&e.push(`Missing required field: ${r}`),r in t&&s.type){let i=typeof t[r];i!==s.type&&e.push(`Field '${r}' expected ${s.type}, got ${i}`)}if(s.validate&&r in t){let i=s.validate(t[r]);i&&e.push(`Field '${r}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};
|
|
20
|
-
`?(
|
|
21
|
-
${Wt}`,t.col=Gt))}return o(
|
|
19
|
+
`)}`);return t}};V();import{writeFileSync as It,readFileSync as qt,existsSync as Xt,mkdirSync as Ge}from"node:fs";import{join as Et,dirname as Fe}from"node:path";import O from"chalk";var Pe="__WORKFLOW_GRAPH_LOG__",q=O.gray("\u2502"),Ne=O.gray("\u250C"),Lt=O.gray("\u2514"),dt=O.green("\u25C6"),jt=O.hex("#c084fc")("\u25C6"),Ut=O.hex("#2dd4bf")("\u25C6"),ft=O.red("\u25C6"),Wt=`${q} `,Gt=2;function Ft(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ht(o,t){return(e,r,s)=>{if(typeof e!="string")return o(e,r,s);let i=process.stdout.columns||120,n="";for(let a=0;a<e.length;a++){let u=e[a];t.lineStart&&(n+=Wt,t.col=Gt,t.lineStart=!1),u===`
|
|
20
|
+
`?(n+=u,t.lineStart=!0,t.col=0,t.inEsc=!1):u==="\x1B"?(t.inEsc=!0,n+=u):t.inEsc?(n+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(t.inEsc=!1)):(t.col++,n+=u,t.col>=i&&(n+=`
|
|
21
|
+
${Wt}`,t.col=Gt))}return o(n,r,s)}}var ht=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=Ht(this._origStdoutWrite,t),process.stderr.write=Ht(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
24
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
24
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Pe}${JSON.stringify(t)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(dt,t):process.stdout.write.bind(process.stdout)(`${
|
|
29
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(jt,t):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ut,e):process.stdout.write.bind(process.stdout)(`${
|
|
31
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ft,O.red(t)):process.stdout.write.bind(process.stdout)(`${
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(dt,t):process.stdout.write.bind(process.stdout)(`${q} ${dt} ${t}
|
|
29
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(jt,t):process.stdout.write.bind(process.stdout)(`${q} ${jt} ${t}
|
|
30
|
+
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ut,e):process.stdout.write.bind(process.stdout)(`${q} ${Ut} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ft,O.red(t)):process.stdout.write.bind(process.stdout)(`${q} ${ft} ${O.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ne} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:s}=e;if(s)for(let n of s)this._rawWrite(`${dt} ${n}`);let i=r?O.dim(` ${Ft(r)}`):"";this._rawWrite(`${Lt} ${O.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:s}=r,i=s?O.dim(` ${Ft(s)}`):"";this._rawWrite(`${ft} ${O.red(e)}`),this._rawWrite(`${Lt} ${O.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},x=new ht;var it=".zibby/output",Jt="sessions",Z=".session-info.json",Yt=".zibby-stop";var Re={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},kr=Object.freeze([Re.CODEBASE_MEMORY]),Zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",o=>Number(o)+1);W.helpers.json||W.registerHelper("json",o=>JSON.stringify(o,null,2));W.helpers.eq||W.registerHelper("eq",(o,t)=>o===t);var L=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!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 _.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return _.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
|
|
33
33
|
|
|
34
|
-
${n}`);let l=r(),u=l.cwd||process.cwd(),p=l.sessionPath;try{if(p){let a=Et(p,Z);if(Xt(a)){let y=JSON.parse(Vt(a,"utf-8"));y.currentNode=this.name,It(a,JSON.stringify(y,null,2),"utf-8")}let c=Et(p,"..",Z);if(Xt(c))try{let y=JSON.parse(Vt(c,"utf-8"));y.currentNode=this.name,It(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(a){I.debug(`[workflow] could not update session info: ${a.message}`)}let m=null;for(let a=0;a<=this.retries;a++)try{I.debug(`[workflow] node '${this.name}' attempt ${a}`);let c=r().config||{},y=c.agents||{},_=this.config.agent??y[this.name]??null,T={state:r()};_&&(T.preferredAgent=_);let k={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(wt(),_t))).invokeAgent);let f=await $(n,T,k),h,g;if(typeof f=="string"?(h=f,g=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),g=f.structured):(h=f.raw||JSON.stringify(f,null,2),g=f.extracted||null),p)try{let d=Et(p,this.name,"raw_stream_output.txt");Ue(We(d),{recursive:!0}),It(d,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&g){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let d=g;if(typeof this.onComplete=="function")try{d=await this.onComplete(r(),g)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:h}),raw:h}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(h);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),x.step("Output parsed"),{success:!0,output:d,raw:h}}return{success:!0,output:h,raw:h}}catch(c){m=c,a<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${a+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};q();q();import{mkdirSync as He,existsSync as F,statSync as ne,readdirSync as ie,rmSync as Je}from"node:fs";import{spawn as se}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ye}from"node:url";import{AsyncLocalStorage as Ge}from"node:async_hooks";var bt=new Ge;function X(){let o=bt.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function Qt(o,t){let e=bt.getStore()||X(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(o.executionId!==e.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:e.conversationId??null,dispatchMode:o.dispatchMode??null});return bt.run(r,t)}var $t=new Map,Tt=new Map,te=new Map;function ee(o,t,e={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");$t.set(o,t),Tt.set(o,"ready"),te.set(o,{...e,cachedAt:Date.now()})}function re(o,t){Tt.set(o,"failed"),te.set(o,{error:t?.message||String(t),failedAt:Date.now()}),$t.delete(o)}function oe(o){return Tt.get(o)==="ready"?$t.get(o):null}var at=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ze(){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"}};function ze(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=o||t,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:r,authToken:s}}async function Ke({apiBase:o,authToken:t,body:e}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new P("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){if(r.status===404){let n=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(r.status===429){let n=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=n,i}if(r.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new P("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function G({apiBase:o,authToken:t,payload:e}){try{let r=await fetch(`${o}/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 qe(o,t){let e=j(t,".ready"),r=j(t,"graph.mjs");if(F(e)&&F(r))return;He(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:l}=await import("node:fs"),u=i(s,"wx");l(u),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(F(e)&&F(r))return;await new Promise(l=>setTimeout(l,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let m=se("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),a=se("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(a.stdin);let c,y,_=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return p(new Error(`curl exited ${c}`));if(y!==0)return p(new Error(`tar exited ${y}`));u()}};m.on("close",T=>{c=T,_()}),a.on("close",T=>{y=T,_()}),m.on("error",p),a.on("error",p)});let{writeFileSync:i,unlinkSync:l}=await import("node:fs");i(e,"");try{l(s)}catch{}}catch(i){try{let{unlinkSync:l}=await import("node:fs");l(s)}catch{}throw new P("bundle-extract-failed",i.message)}}async function Ve(o){let t=j(o,"graph.mjs");if(!F(t))throw new P("entry-missing",`graph.mjs missing under ${o}`);let e;try{e=await import(Ye(t).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function ae(o,t={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=X(),r;try{r=ze()}catch(E){throw E}I.debug(`[in-process subgraph] begin '${o}' parent=${e.executionId||"<root>"}`);let s=await Ke({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:o,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:l,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:m,bundleReady:a,nodeConfigs:c}=s,y=Ze();if(i&&i!==y)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${y} vs ${i}`);if(!a||!l)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,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 _=oe(o);if(!_){let E=j(at,`${m}@${p||"0"}`);try{await qe(l,E);try{Qe()}catch{}}catch(w){throw w.fallback&&await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:w.message,code:w.reason}}}),w}try{_=await Ve(E),ee(o,_,{workflowUuid:m,version:p,runtimeTag:i,cacheDir:E})}catch(w){throw re(o,w),await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:w.message,code:w.reason||"IMPORT_FAILED"}}}),w.fallback?w:new P("import-failed",w.message)}}let T=Date.now(),$=await(typeof _=="function"&&_.prototype?.buildGraph?new _:_).buildGraph(),f=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...t.input||{},...f?{nodeConfigs:c}:{}},g,d;try{g=await Qt({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>$.run(t.parentAgent,h,{signal:t.signal})),d=g&&typeof g=="object"&&"state"in g?g.state:g}catch(E){throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:E.message,code:E.code||"CHILD_THREW",stack:E.stack},durationMs:Date.now()-T}}),E}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:d,durationMs:Date.now()-T}});let E=new Error(`Sub-graph '${o}' canceled by parent abort`);throw E.code="SUBGRAPH_CANCELED",E.subgraphJobId=n,E}return await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:d,durationMs:Date.now()-T}}),{finalState:d,executionId:n}}function Xe(o){let t=0,e=[o];for(;e.length;){let r=e.pop(),s;try{s=ne(r)}catch{continue}if(s.isDirectory()){let n;try{n=ie(r)}catch{continue}for(let i of n)e.push(j(r,i))}else t+=s.size}return t}function Qe({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(at))return{evicted:0,freedBytes:0};let t=ie(at),e=[],r=0;for(let l of t){let u=j(at,l),p;try{p=ne(u)}catch{continue}let m=p.isDirectory()?Xe(u):p.size;r+=m,e.push({name:l,full:u,size:m,mtimeMs:p.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};e.sort((l,u)=>l.mtimeMs-u.mtimeMs);let s=Math.floor(o*.7),n=0,i=0;for(let l of e){if(r-n<=s)break;if(!F(j(l.full,".lock")))try{Je(l.full,{recursive:!0,force:!0}),n+=l.size,i+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${l.name}: ${u.message}`)}}return i>0&&I.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:r-n}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var tr=2e3,er=600*1e3,rr=new Set(["completed","failed","canceled","timeout"]);function or(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function sr(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function nr(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function ir(){return process.env.EXECUTION_ID||null}function ce(o,t){return t==null?o:typeof t=="function"?t(o):typeof t=="string"?t.split(".").reduce((e,r)=>e==null?e:e[r],o):o}async function le(o,t={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=X(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): 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 '${o}'`);let{finalState:g}=await ae(o,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=ce(g,t.output);return I.info(`[sub-graph] '${o}' completed in-process`),d}catch(g){if(g instanceof P||g?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=or(),n=sr(),i=nr(),l=ir(),u=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,p={input:t.input||{},...l?{parentExecutionId:l}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${t.async?"async":"sync"}) from parent ${l||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(p)});if(!m.ok){let g=null,d="";try{g=await m.json(),d=g?.error||g?.message||JSON.stringify(g)}catch{d=await m.text().catch(()=>"")}if(m.status===429){let w=g?.quotaInfo||{},B=new Error(`Sub-graph '${o}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=o,B.quotaInfo=w,B}if(m.status===400){let w=new Error(`Sub-graph '${o}' rejected input: ${d}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=o,w.validationErrors=g?.validationErrors||null,w.missing=g?.missing||null,w}let E=new Error(`Sub-graph '${o}' trigger rejected (${m.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=m.status,E.subgraph=o,E}let a=await m.json(),c=a?.data?.jobId||a?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(a).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(t.timeoutMs)?t.timeoutMs:er,_=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:tr,T=`${s}/executions/${encodeURIComponent(c)}`,k=Date.now()+y,$="accepted",f=0;for(;Date.now()<k;){await new Promise(w=>setTimeout(w,_)),f+=1;let g=await fetch(T,{headers:{Authorization:`Bearer ${i}`}});if(!g.ok){if(g.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${g.status}`)}let d=await g.json(),E=d?.data||d?.execution||d;if($=E?.status||$,rr.has($)){if($!=="completed"){let S=new Error(`Sub-graph '${o}' (${c}) ended in status '${$}'`);throw S.subgraphJobId=c,S.subgraphStatus=$,S}let w=E?.finalState||E?.state||{},B=ce(w,t.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${f} polls`),B}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${$})`);throw h.subgraphJobId=c,h.subgraphStatus=$,h}import{existsSync as ue,readFileSync as ar}from"node:fs";import{join as At,dirname as pe}from"node:path";var ct=class{static async loadContext(t,e,r={}){let s={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(t){let l=pe(At(e,t));for(let u of n){let p=await this.findAndMergeContextFiles(u,l,e);if(p){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=p}}}let i=r.discovery||{};for(let[l,u]of Object.entries(i))try{let p=At(e,u);ue(p)&&(s[l]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${l}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(t,e,r){let s=[],n=e;for(;n.startsWith(r);){let i=At(n,t);if(ue(i))try{s.unshift(await this.loadFile(i))}catch(u){console.warn(`[workflow] could not load ${t} from ${i}: ${u.message}`)}let l=pe(n);if(l===n)break;n=l}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
34
|
+
${i}`);let a=r(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=Et(p,Z);if(Xt(c)){let y=JSON.parse(qt(c,"utf-8"));y.currentNode=this.name,It(c,JSON.stringify(y,null,2),"utf-8")}let l=Et(p,"..",Z);if(Xt(l))try{let y=JSON.parse(qt(l,"utf-8"));y.currentNode=this.name,It(l,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let g=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=r().config||{},y=l.agents||{},w=this.config.agent??y[this.name]??null,$={state:r()};w&&($.preferredAgent=w);let v={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},b=t?._coreInvokeAgent;b||(b=(await Promise.resolve().then(()=>(_t(),wt))).invokeAgent);let h=await b(i,$,v),f,m;if(typeof h=="string"?(f=h,m=null):h.structured?(f=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(f=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),p)try{let d=Et(p,this.name,"raw_stream_output.txt");Ge(Fe(d),{recursive:!0}),It(d,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(d){_.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){_.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(I){_.warn(`[workflow] onComplete hook failed: ${I.message}`)}return{success:!0,output:d,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:f}),raw:f}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(f);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),x.step("Output parsed"),{success:!0,output:d,raw:f}}return{success:!0,output:f,raw:f}}catch(l){g=l,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:g.message,raw:null}}};V();V();import{mkdirSync as Ye,existsSync as F,statSync as ae,readdirSync as ce,rmSync as Ze}from"node:fs";import{spawn as se}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as ze}from"node:url";import{AsyncLocalStorage as Ke}from"node:async_hooks";import{AsyncLocalStorage as He}from"node:async_hooks";var bt=new He;function X(){let o=bt.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function Qt(o,t){let e=bt.getStore()||X(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(o.executionId!==e.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:e.conversationId??null,dispatchMode:o.dispatchMode??null});return bt.run(r,t)}var $t=new Map,Tt=new Map,te=new Map;function ee(o,t,e={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");$t.set(o,t),Tt.set(o,"ready"),te.set(o,{...e,cachedAt:Date.now()})}function re(o,t){Tt.set(o,"failed"),te.set(o,{error:t?.message||String(t),failedAt:Date.now()}),$t.delete(o)}function oe(o){return Tt.get(o)==="ready"?$t.get(o):null}var at=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ve(){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"}},ne=new Ke,ie=Promise.resolve();async function qe(o,t){let e=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(e.length===0)return t();let r=ne.getStore()===!0,s=null;if(!r){let n=ie;ie=new Promise(a=>{s=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 _.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${r?" (nested)":""}`),await ne.run(!0,t)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;s&&s()}}function Xe(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=o||t,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:r,authToken:s}}async function Qe({apiBase:o,authToken:t,body:e}){let r;try{r=await fetch(`${o}/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 s=null;try{s=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=s?.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&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function G({apiBase:o,authToken:t,payload:e}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});r.ok||_.warn(`[in-process subgraph] finalize returned ${r.status} for ${e.childExecutionId}`)}catch(r){_.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function tr(o,t){let e=j(t,".ready"),r=j(t,"graph.mjs");if(F(e)&&F(r))return;Ye(t,{recursive:!0});let s=j(t,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(s,"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(F(e)&&F(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 g=se("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),c=se("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(c.stdin);let l,y,w=()=>{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()}};g.on("close",$=>{l=$,w()}),c.on("close",$=>{y=$,w()}),g.on("error",p),c.on("error",p)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(e,"");try{a(s)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",n.message)}}async function er(o){let t=j(o,"graph.mjs");if(!F(t))throw new P("entry-missing",`graph.mjs missing under ${o}`);let e;try{e=await import(ze(t).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function le(o,t={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=X(),r;try{r=Xe()}catch(d){throw d}_.debug(`[in-process subgraph] begin '${o}' parent=${e.executionId||"<root>"}`);let s=await Qe({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:o,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:g,bundleReady:c,nodeConfigs:l}=s,y=Ve();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 w=oe(o);if(!w){let d=j(at,`${g}@${p||"0"}`);try{await tr(a,d);try{or()}catch{}}catch(I){throw I.fallback&&await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:I.message,code:I.reason}}}),I}try{w=await er(d),ee(o,w,{workflowUuid:g,version:p,runtimeTag:n,cacheDir:d})}catch(I){throw re(o,I),await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:I.message,code:I.reason||"IMPORT_FAILED"}}}),I.fallback?I:new P("import-failed",I.message)}}let $=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,b=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,h={...t.input||{},...b?{nodeConfigs:l}:{}},f,m;try{f=await qe(v,async()=>{let I=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return Qt({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>I.run(t.parentAgent,h,{signal:t.signal}))}),m=f&&typeof f=="object"&&"state"in f?f.state:f}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()-$}}),d}if(f&&typeof f=="object"&&f.stoppedExternally){await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-$}});let d=new Error(`Sub-graph '${o}' 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()-$}}),{finalState:m,executionId:i}}function rr(o){let t=0,e=[o];for(;e.length;){let r=e.pop(),s;try{s=ae(r)}catch{continue}if(s.isDirectory()){let i;try{i=ce(r)}catch{continue}for(let n of i)e.push(j(r,n))}else t+=s.size}return t}function or({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(at))return{evicted:0,freedBytes:0};let t=ce(at),e=[],r=0;for(let a of t){let u=j(at,a),p;try{p=ae(u)}catch{continue}let g=p.isDirectory()?rr(u):p.size;r+=g,e.push({name:a,full:u,size:g,mtimeMs:p.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(o*.7),i=0,n=0;for(let a of e){if(r-i<=s)break;if(!F(j(a.full,".lock")))try{Ze(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){_.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&_.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 _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var sr=2e3,nr=600*1e3,ir=new Set(["completed","failed","canceled","timeout"]);function ar(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function cr(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function lr(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function ur(){return process.env.EXECUTION_ID||null}function ue(o,t){return t==null?o:typeof t=="function"?t(o):typeof t=="string"?t.split(".").reduce((e,r)=>e==null?e:e[r],o):o}async function pe(o,t={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=X(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): 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{_.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:m}=await le(o,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=ue(m,t.output);return _.info(`[sub-graph] '${o}' completed in-process`),d}catch(m){if(m instanceof P||m?.fallback)_.info(`[sub-graph] in-process fallback for '${o}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let s=ar(),i=cr(),n=lr(),a=ur(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${o}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(p)});if(!g.ok){let m=null,d="";try{m=await g.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await g.text().catch(()=>"")}if(g.status===429){let A=m?.quotaInfo||{},B=new Error(`Sub-graph '${o}' 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 B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=o,B.quotaInfo=A,B}if(g.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${d}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let I=new Error(`Sub-graph '${o}' trigger rejected (${g.status}): ${d}`);throw I.code="SUBGRAPH_TRIGGER_FAILED",I.status=g.status,I.subgraph=o,I}let c=await g.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:o};let y=Number.isFinite(t.timeoutMs)?t.timeoutMs:nr,w=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:sr,$=`${s}/executions/${encodeURIComponent(l)}`,v=Date.now()+y,b="accepted",h=0;for(;Date.now()<v;){await new Promise(A=>setTimeout(A,w)),h+=1;let m=await fetch($,{headers:{Authorization:`Bearer ${n}`}});if(!m.ok){if(m.status>=500){_.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(),I=d?.data||d?.execution||d;if(b=I?.status||b,ir.has(b)){if(b!=="completed"){let S=new Error(`Sub-graph '${o}' (${l}) ended in status '${b}'`);throw S.subgraphJobId=l,S.subgraphStatus=b,S}let A=I?.finalState||I?.state||{},B=ue(A,t.output);return _.info(`[sub-graph] '${o}' (${l}) completed after ${h} polls`),B}}let f=new Error(`Sub-graph '${o}' (${l}) timed out after ${Math.round(y/1e3)}s (last status: ${b})`);throw f.subgraphJobId=l,f.subgraphStatus=b,f}import{existsSync as de,readFileSync as pr}from"node:fs";import{join as At,dirname as fe}from"node:path";var ct=class{static async loadContext(t,e,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=fe(At(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let g=u.replace(/\.[^.]+$/,"").toLowerCase();s[g]=p}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let p=At(e,u);de(p)&&(s[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(t,e,r){let s=[],i=e;for(;i.startsWith(r);){let n=At(i,t);if(de(n))try{s.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${t} from ${n}: ${u.message}`)}let a=fe(i);if(a===i)break;i=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):s.every(
|
|
38
|
+
`):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=pr(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(t).href);return s.default||s}return e}};import{mkdirSync as Se,existsSync as vt,writeFileSync as he,unlinkSync as dr}from"node:fs";import{join as H,resolve as ye}from"node:path";import{config as fr}from"dotenv";import{zodToJsonSchema as ge}from"zod-to-json-schema";import{z as lt}from"zod";import hr from"handlebars";function gr({traceFrom:o,sessionId:t,sessionPath:e,idSource:r,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${t} source=${r} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let g=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${m}`)}}function dr(){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 fr(){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 me(String(t).trim())}catch{return String(t).trim()}}function hr(){dr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function gr({sessionPath:o,sessionId:t}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function mr(o={}){let t=Zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),r=t||`${Date.now()}_${e}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function Sr({cwd:o=process.cwd(),config:t={},initialState:e={},traceFrom:r="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=me(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,i="ZIBBY_SESSION_PATH")}catch{}let l;if(s)l=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)l=p,i="ZIBBY_SESSION_ID";else{let a=t.sessionId!=null?String(t.sessionId).trim():"";a&&a!=="last"?(l=a,i="config.sessionId"):(l=mr(t),i="generated")}n=n??Date.now();let m=t.paths?.output||it;s=H(o,m,Jt,l)}let u=!kt(s);return u&&ge(s,{recursive:!0}),(u||i!=="initialState.sessionPath")&&pr({traceFrom:r,sessionId:l,sessionPath:s,idSource:i,mkdirFresh:u}),gr({sessionPath:s,sessionId:l}),{sessionPath:s,sessionId:l,sessionTimestamp:n}}var he=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 L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let i=e,l={name:t,_isCustomCode:!0,dispatchesWorkflow:i.workflow,retries:i.retries,onComplete:i.onComplete,execute:async p=>{let m=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,a;return typeof i.input=="function"?a=i.input(m):i.input&&typeof i.input=="object"?a=i.input:a={},le(i.workflow,{input:a,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(m):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:m?._signal,parentAgent:p?.agent})}},u=new L(l);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 s=!(e instanceof L)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,n=e instanceof L?e:new L(s?{...e,_isRouter:!0}:e);return n.name=t,this.nodes.set(t,n),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,s,n){let i=r;for(let l=t.length-1;l>=0;l--){let u=t[l],p=i;i=()=>u(e,p,s,n)}return i()}serialize(){let t=[],e={};for(let[a,c]of this.nodes){let y=this.nodeTypeMap.get(a)||(c?.config?._isRouter===!0?"decision":a);t.push({id:a,type:y,data:{nodeType:y,label:a}});let _={};c._isCustomCode&&typeof c.execute=="function"&&(_.customCode=c.execute.toString());let T=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;T&&(_.description=T);let k=this.nodePrompts.get(a);if(k)_.prompt=k;else if(typeof c.prompt=="function")try{let d=c.prompt({});typeof d=="string"&&d.trim()&&(_.prompt=d,_.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(_.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(_.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let d=null;if(typeof lt?.toJSONSchema=="function")try{d=lt.toJSONSchema(c.outputSchema)}catch{}if(!d)try{d=fe(c.outputSchema,{target:"openApi3"})}catch{}_.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:c.outputSchema}}else _.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[a];$?.toolIds&&(_.tools=$.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(_.skills=[...f]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(_.plugins=h.map(d=>d&&typeof d=="object"?{...d}:d));let g=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;g&&g.length>0&&(_.stores=g.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(_).length>0&&(e[a]=_)}let r=[];for(let[a,c]of this.edges)if(typeof c=="string")r.push({source:a,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(a)||c.routes.toString(),_=this._inferConditionalTargets(c.routes,c.labels),T=c.labels||{},k=this.nodes.get(a),$=k?.config?._isRouter===!0||this.nodeTypeMap.get(a)==="decision"||!k,f=a;if(!$){let h=`${a}__branch`;t.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),r.push({source:a,target:h}),f=h}for(let h of _){let g={source:f,target:h,data:{conditionalCode:y}};T[h]&&(g.label=T[h]),r.push(g)}}let s=a=>{if(!a)return null;if(typeof lt?.toJSONSchema=="function")try{return lt.toJSONSchema(a)}catch{}try{return fe(a,{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 n=0;for(let a of r)if(a.target==="END"){n+=1;let c=`END__${n}`;a.target=c,t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let a of this.nodes.keys())if(!this.edges.has(a)){n+=1;let c=`END__${n}`;t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:a,target:c})}let i=this._topoOrderNodes(t,r),l=this._runtimeSchema(),u=s(l||this.stateSchema),p=s(this.inputSchema),m=s(this.contextSchema);return{nodes:i,edges:r,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:m}}_topoOrderNodes(t,e){let r=new Map(t.map((a,c)=>[a.id,c])),s=new Map(t.map(a=>[a.id,a])),n=new Map(t.map(a=>[a.id,0])),i=new Map(t.map(a=>[a.id,[]]));for(let a of e)i.has(a.source)&&n.has(a.target)&&(i.get(a.source).push(a.target),n.set(a.target,n.get(a.target)+1));let l=new Set,u=new Set(r.keys()),p=[...u].filter(a=>n.get(a)===0),m=[];for(;m.length<t.length;){let a;if(p.length>0){if(p.sort((c,y)=>r.get(c)-r.get(y)),a=p.shift(),l.has(a))continue}else a=[...u].sort((c,y)=>r.get(c)-r.get(y))[0];l.add(a),u.delete(a),m.push(s.get(a));for(let c of i.get(a)||[])n.set(c,n.get(c)-1),n.get(c)<=0&&!l.has(c)&&p.push(c)}return m}_inferConditionalTargets(t,e){let r=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(r))!==null;){let p=i[2]!==void 0?i[2]:i[3];p!==void 0&&p!==""&&s.add(p)}let l=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())l.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))l.add(p);let u=new Set;for(let p of s)l.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=p.exec(r))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let r=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");r=t.definitions[s]||t}return this._flattenSchema(r,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let r=[],s=t.properties||{},n=t.required||[];for(let[i,l]of Object.entries(s)){let u=e?`${e}.${i}`:i;r.push({path:u,type:l.type||"unknown",label:l.description||this._formatLabel(i),optional:!n.includes(i)}),l.type==="object"&&l.properties&&r.push(...this._flattenSchema(l,u)),l.type==="array"&&l.items?.type==="object"&&l.items.properties&&r.push(...this._flattenSchema(l.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[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,l=n.filter(p=>p?.passed===!0).length,u=n.some(p=>p?.passed!==void 0);r.push(u?`${s}: ${l}/${i} passed${i-l?`, ${i-l} failed`:""}`:`${s}: ${i} 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 s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=r.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();lr({path:H(i,".env")});let l=e.config||{};if(!l||Object.keys(l).length===0)try{let b=H(i,".zibby.config.js");kt(b)&&(l=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!l.agent?.strictMode&&(l.agent={...l.agent,strictMode:!0});let u=e.agentType;if(!u){let b=l?.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||"cursor"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||l?.context||{},m=this._runtimeSchema();if(m){let b=m.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(", ")}`)}x.step("State validated against schema")}let a=fr(),c=e.sessionPath||a;c||hr();let{sessionPath:y,sessionTimestamp:_,sessionId:T}=Sr({cwd:i,config:l,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:e.sessionTimestamp}});x.step(`Session ${T}`);let k=await ct.loadContext(e.specPath||"",i,p);Object.keys(k).length>0&&x.step(`Context loaded: ${Object.keys(k).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:l,agentType:u,outputPath:$,sessionPath:y,sessionTimestamp:_,context:k,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:g}=await Promise.resolve().then(()=>(St(),Kt)),d=l.skills&&typeof l.skills=="object"?l.skills:{},E=Object.values(d).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),w=b=>{for(let N of E)if(N.id===b)return N;return g(b)},B=new Set;for(let[,b]of this.nodes)for(let N of b.config?.skills||[])B.add(N);for(let b of B){let N=w(b);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&h.set(b,R)}catch{}}let S=this.entryPoint,Q=[],vt=l?.recursionLimit??100,Se=0;try{for(;S&&S!=="END";){if(++Se>vt)throw new Error(`Workflow exceeded recursion limit (${vt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(y,Yt);if(kt(N)){try{cr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:
|
|
41
|
+
${g}`)}}function mr(){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 Sr(){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 ye(String(t).trim())}catch{return String(t).trim()}}function yr(){mr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function wr({sessionPath:o,sessionId:t}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function _r(o={}){let t=Zt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),r=t||`${Date.now()}_${e}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function Ir({cwd:o=process.cwd(),config:t={},initialState:e={},traceFrom:r="resolveWorkflowSession"}={}){let s=e.sessionPath,i=e.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=ye(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).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=_r(t),n="generated")}i=i??Date.now();let g=t.paths?.output||it;s=H(o,g,Jt,a)}let u=!vt(s);return u&&Se(s,{recursive:!0}),(u||n!=="initialState.sessionPath")&&gr({traceFrom:r,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:u}),wr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var me=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 L)&&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 g=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof n.input=="function"?c=n.input(g):n.input&&typeof n.input=="object"?c=n.input:c={},pe(n.workflow,{input:c,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(g):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:g?._signal,parentAgent:p?.agent})}},u=new L(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 s=!(e instanceof L)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof L?e:new L(s?{...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,s,i){let n=r;for(let a=t.length-1;a>=0;a--){let u=t[a],p=n;n=()=>u(e,p,s,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 w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let $=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;$&&(w.description=$);let v=this.nodePrompts.get(c);if(v)w.prompt=v;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(w.prompt=d,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof lt?.toJSONSchema=="function")try{d=lt.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=ge(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let b=(this.resolvedToolsMap||{})[c];b?.toolIds&&(w.tools=b.toolIds);let h=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;h&&h.length>0&&(w.skills=[...h]);let f=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;f&&f.length>0&&(w.plugins=f.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&&(w.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(w).length>0&&(e[c]=w)}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(),w=this._inferConditionalTargets(l.routes,l.labels),$=l.labels||{},v=this.nodes.get(c),b=v?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!v,h=c;if(!b){let f=`${c}__branch`;t.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:c,target:f}),h=f}for(let f of w){let m={source:h,target:f,data:{conditionalCode:y}};$[f]&&(m.label=$[f]),r.push(m)}}let s=c=>{if(!c)return null;if(typeof lt?.toJSONSchema=="function")try{return lt.toJSONSchema(c)}catch{}try{return ge(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=s(a||this.stateSchema),p=s(this.inputSchema),g=s(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:g}}_topoOrderNodes(t,e){let r=new Map(t.map((c,l)=>[c.id,l])),s=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),g=[];for(;g.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),g.push(s.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 g}_inferConditionalTargets(t,e){let r=t.toString(),s=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!==""&&s.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 s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,g;for(;(g=p.exec(r))!==null;)u.add(g[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let r=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");r=t.definitions[s]||t}return this._flattenSchema(r,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let r=[],s=t.properties||{},i=t.required||[];for(let[n,a]of Object.entries(s)){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[s,i]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${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?`${s}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${s}: ${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 s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();fr({path:H(n,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let E=H(n,".zibby.config.js");vt(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let E=a?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},g=this._runtimeSchema();if(g){let E=g.safeParse(e);if(!E.success){let N=E.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(", ")}`)}x.step("State validated against schema")}let c=Sr(),l=e.sessionPath||c;l||yr();let{sessionPath:y,sessionTimestamp:w,sessionId:$}=Ir({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});x.step(`Session ${$}`);let v=await ct.loadContext(e.specPath||"",n,p);Object.keys(v).length>0&&x.step(`Context loaded: ${Object.keys(v).join(", ")}`);let b=e.outputPath;!b&&e.specPath&&(t?.calculateOutputPath?b=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let h=new ot({...e,config:a,agentType:u,outputPath:b,sessionPath:y,sessionTimestamp:w,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(St(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(d).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),A=E=>{for(let N of I)if(N.id===E)return N;return m(E)},B=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])B.add(N);for(let E of B){let N=A(E);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(E,R)}catch{}}let S=this.entryPoint,Q=[],kt=a?.recursionLimit??100,we=0;try{for(;S&&S!=="END";){if(++we>kt)throw new Error(`Workflow exceeded recursion limit (${kt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(y,Yt);if(vt(N)){try{dr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:Q,stoppedExternally:!0};let R=this.nodes.get(S);if(!R)throw new Error(`Node '${S}' not found in graph`);let Ot=JSON.stringify({sessionPath:y,sessionTimestamp:w,currentNode:S,createdAt:new Date().toISOString(),config:h.get("config")}),_e=H(y,Z);he(_e,Ot,"utf-8");let xt=h.get("config")?.paths?.output||it,Ie=H(n,xt,Z);Se(H(n,xt),{recursive:!0});try{he(Ie,Ot,"utf-8")}catch{}let Pt=e.onPipelineProgress;if(typeof Pt=="function")try{Pt({cwd:n,sessionPath:y,sessionId:$,outputBase:h.get("config")?.paths?.output||it,currentNode:S})}catch{}let Ee=(this.resolvedToolsMap||{})[S]||null;h.set("_currentNodeTools",Ee);let be=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",be[S]||{}),x.nodeStart(S);let Nt=Date.now(),tt=this.nodePrompts.get(S);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(_t(),wt));this._invokeAgent=k.invokeAgent}let $e=this._invokeAgent,ut={},Te=R.config?.skills||[];for(let k of Te){let C=A(k);if(typeof C?.invokeAgentOptions=="function")try{let T=C.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:S});T&&typeof T=="object"&&(ut={...ut,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Rt=async(k,C,T={})=>{let M=$e(k,C,{...ut,...T,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((J,Y)=>{let D=()=>{setTimeout(()=>{let K=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);K.name="AbortError",Y(K)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},Ae=async(k={},C={})=>{let T=C.prompt||"";if(tt){let M=this._compiledPrompts.get(S);M||(M=hr.compile(tt,{noEscape:!0}),this._compiledPrompts.set(S,M));try{T=M(k)}catch(J){throw console.error(`\u274C Template rendering failed for node '${S}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!T)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return Rt(T,{state:h.getAll(),images:C.images||[]},{model:C.model||h.get("model"),workspace:h.get("workspace"),schema:C.schema,...C,signal:s.signal})},Bt=h.getAll(),ve=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of ve)Object.prototype.hasOwnProperty.call(Bt,k)&&console.warn(`[workflow] node "${S}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ct={...Bt,state:h,invokeAgent:Ae,_coreInvokeAgent:Rt,agent:t,nodeId:S,promptTemplate:tt,getPromptTemplate:()=>tt};try{let k=(R.config?.skills||[]).map(D=>f.get(D)).filter(Boolean),C=[...this.middleware,...k],T;C.length>0?T=await this._composeMiddleware(C,S,async()=>R.execute(Ct,h),h.getAll(),h):T=await R.execute(Ct,h);let M=Date.now()-Nt;if(Q.push({node:S,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:Q,stoppedExternally:!0};h.append("errors",{node:S,error:T.error});let D=R.config?.retries||0,K=`${S}_retries`,et=h.getAll()[K]||0;if(et<D){x.stepInfo(`Retrying (attempt ${et+1}/${D})`),h.update({[K]:et+1,[`${S}_raw`]:T.raw});continue}throw x.nodeFailed(S,T.error,{duration:M}),new Error(`Node '${S}' failed after ${et} attempts: ${T.error}`)}h.update({[S]:T.output});let J=this._summarizeNodeOutput(S,T.output);x.nodeComplete(S,{duration:M,details:J});let Y=this.edges.get(S);if(!Y)S="END";else if(Y.conditional){let D=Y.routes(h.getAll());x.route(S,D),S=D}else S=Y}catch(k){throw x.isInsideNode&&x.nodeFailed(S,k.message,{duration:Date.now()-Nt}),h.set("failed",!0),h.set("failedAt",S),k}}x.graphComplete();let E={success:!0,state:h.getAll(),executionLog:Q};return t&&typeof t.onComplete=="function"&&await t.onComplete(E),E}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};export{me as WorkflowGraph,yr as clearInheritedSessionEnvForFreshRun,_r as generateWorkflowSessionId,Sr as readPinnedSessionPathFromEnv,Ir as resolveWorkflowSession,mr as shouldTrustInheritedSessionEnv,wr as syncProcessEnvToSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as X,existsSync as I,statSync as N,readdirSync as C,rmSync as Y}from"node:fs";import{spawn as j}from"node:child_process";import{join as y}from"node:path";import{pathToFileURL as V}from"node:url";var R=()=>{},F={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k={impl:F};var E={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 J}from"node:async_hooks";var B=new J;function v(){let e=B.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=B.getStore()||v(),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 B.run(t,n)}var $=new Map,A=new Map,P=new Map;function D(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");$.set(e,n),A.set(e,"ready"),P.set(e,{...r,cachedAt:Date.now()})}function M(e,n){A.set(e,"failed"),P.set(e,{error:n?.message||String(n),failedAt:Date.now()}),$.delete(e)}function U(e){return A.get(e)==="ready"?$.get(e):null}var T=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function W(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var u=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"}};function Z(){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 u("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:t,authToken:s}}async function K({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 u("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 u("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function x({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||E.warn(`[in-process subgraph] finalize returned ${t.status} for ${r.childExecutionId}`)}catch(t){E.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function Q(e,n){let r=y(n,".ready"),t=y(n,"graph.mjs");if(I(r)&&I(t))return;X(n,{recursive:!0});let s=y(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 u("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,l)=>{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 l(new Error(`curl exited ${f}`));if(m!==0)return l(new Error(`tar exited ${m}`));d()}};g.on("close",b=>{f=b,h()}),S.on("close",b=>{m=b,h()}),g.on("error",l),S.on("error",l)});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 u("bundle-extract-failed",a.message)}}async function ee(e){let n=y(e,"graph.mjs");if(!I(n))throw new u("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(V(n).href)}catch(s){throw new u("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 u("entry-class-missing","no buildGraph() class export found");return t}async function pe(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=v(),t;try{t=Z()}catch(c){throw c}E.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await K({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:l,workflowUuid:g,bundleReady:S,nodeConfigs:f}=s,m=W();if(a&&a!==m)throw await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new u("runtime-mismatch",`${m} vs ${a}`);if(!S||!i)throw await x({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 u("no-bundle","workflow bundle not built yet");let h=U(e);if(!h){let c=y(T,`${g}@${l||"0"}`);try{await Q(i,c);try{te()}catch{}}catch(p){throw p.fallback&&await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:p.message,code:p.reason}}}),p}try{h=await ee(c),D(e,h,{workflowUuid:g,version:l,runtimeTag:a,cacheDir:c})}catch(p){throw M(e,p),await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:p.message,code:p.reason||"IMPORT_FAILED"}}}),p.fallback?p:new u("import-failed",p.message)}}let b=Date.now(),H=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),L=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,G={...n.input||{},...L?{nodeConfigs:f}:{}},w,_;try{w=await O({executionId:o,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>H.run(n.parentAgent,G,{signal:n.signal})),_=w&&typeof w=="object"&&"state"in w?w.state:w}catch(c){throw await x({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()-b}}),c}if(w&&typeof w=="object"&&w.stoppedExternally){await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:_,durationMs:Date.now()-b}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:_,durationMs:Date.now()-b}}),{finalState:_,executionId:o}}function fe(){try{if(!I(T))return{bytes:0,entries:0};let e=C(T),n=0;for(let r of e)try{n+=z(y(T,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(y(t,a))}else n+=s.size}return n}function te({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!I(T))return{evicted:0,freedBytes:0};let n=C(T),r=[],t=0;for(let i of n){let d=y(T,i),l;try{l=N(d)}catch{continue}let g=l.isDirectory()?z(d):l.size;t+=g,r.push({name:i,full:d,size:g,mtimeMs:l.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(y(i.full,".lock")))try{Y(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){E.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&E.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 E.debug(`[sub-graph cache] evict failed: ${n.message}`),{evicted:0,freedBytes:0}}}export{u as SubgraphFallback,te as evictCacheIfOver,fe as getCacheStats,pe 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(([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};
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ao=Object.defineProperty;var Ee=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var he=(o,e)=>()=>(o&&(e=o(o=0)),e);var ot=(o,e)=>{for(var t in e)ao(o,t,{get:e[t],enumerable:!0})};function uo(o){ne.impl={...rt,...o}}var nt,rt,ne,E,F=he(()=>{nt=()=>{},rt={debug:nt,info:nt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ne={impl:rt};E={debug:(...o)=>ne.impl.debug?.(...o),info:(...o)=>ne.impl.info?.(...o),warn:(...o)=>ne.impl.warn?.(...o),error:(...o)=>ne.impl.error?.(...o)}});var xe,Ne=he(()=>{xe=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var wt={};ot(wt,{clearSkills:()=>yt,getAllSkills:()=>mt,getSkill:()=>q,hasSkill:()=>gt,listSkillIds:()=>St,registerSkill:()=>ht});function ht(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");V.set(o.id,Object.freeze({...o}))}function q(o){return V.get(o)||null}function gt(o){return V.has(o)}function mt(){return new Map(V)}function St(){return Array.from(V.keys())}function yt(){V.clear()}var Oe,V,ie=he(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills");globalThis[Oe]||(globalThis[Oe]=new Map);V=globalThis[Oe]});var ae={};ot(ae,{getAgentStrategy:()=>Ce,invokeAgent:()=>Et,listStrategies:()=>It,registerStrategy:()=>_t});function _t(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=W.findIndex(t=>t.getName()===o.getName());e>=0?W[e]=o:W.push(o)}function It(){return W.map(o=>o.getName())}function Ce(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let s=W.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${n}`);let i=W.find(s=>s.getName()===n);if(!i){let s=W.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${s}`)}if(!i.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${i.getName()}`),i}async function Et(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:n},s=Ce(i),r=n.config||t.config||{},a=r.models||{},l=t.nodeName&&a[t.nodeName]||null,d=a.default||null,f=r.agent?.[s.name]?.model||null,u=l||d||f||t.model||null,c={...t,model:u,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:r},S=o,g=c.skills||[];if(g.length>0&&!t.skipPromptFragments){let _=g.map(m=>{let h=q(m)?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);_.length>0&&(S+=`
|
|
2
2
|
|
|
3
3
|
${_.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let w=n._currentNodeConfig?.stores;if(Array.isArray(w)&&w.length>0&&typeof w[0]=="object"){let _=w.length<=8,
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let w=n._currentNodeConfig?.stores;if(Array.isArray(w)&&w.length>0&&typeof w[0]=="object"){let _=w.length<=8,m=w.map(h=>{let y=h?.id??h?.storeId??"",p=(h?.name??"").toString().trim()||y,$=h?.type?` \xB7 ${h.type}`:"",A=(h?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${A||"(no description)"}${$} (id: ${y})`;if(_&&h?.schema&&typeof h.schema=="object"){let I=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);I.length&&(R+=`
|
|
6
|
+
fields: ${I.join(", ")}`)}return R});S+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
9
|
+
${m.join(`
|
|
10
10
|
`)}`}let b=n._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(S+=`
|
|
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
|
|
@@ -14,9 +14,9 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${b}
|
|
17
|
-
`),
|
|
17
|
+
`),E.debug(`[workflow] prompt length: ${S.length} chars`),s.invoke(S,c)}var Pe,W,X=he(()=>{Ne();F();ie();Pe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Pe]||(globalThis[Pe]=[]);W=globalThis[Pe]});var co=new Set(["__proto__","constructor","prototype"]);function be(o){if(co.has(o))throw new Error(`Invalid state key: "${o}"`)}var te=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){be(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)be(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){be(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import H from"handlebars";var oe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(i=>i[0]);for(let i of n)try{return this.validate(JSON.parse(i))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,i]of Object.entries(this.schema)){if(i.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&i.type){let s=typeof e[n];s!==i.type&&t.push(`Field '${n}' expected ${i.type}, got ${s}`)}if(i.validate&&n in e){let s=i.validate(e[n]);s&&t.push(`Field '${n}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}},
|
|
19
|
+
`)}`);return e}},lo={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};F();import{writeFileSync as Re,readFileSync as bt,existsSync as $t,mkdirSync as So}from"node:fs";import{join as Be,dirname as yo}from"node:path";import N from"chalk";var pt="__WORKFLOW_GRAPH_LOG__",re=N.gray("\u2502"),po=N.gray("\u250C"),st=N.gray("\u2514"),$e=N.green("\u25C6"),it=N.hex("#c084fc")("\u25C6"),at=N.hex("#2dd4bf")("\u25C6"),Te=N.red("\u25C6"),ct=`${re} `,lt=2;function ut(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function dt(o,e){return(t,n,i)=>{if(typeof t!="string")return o(t,n,i);let s=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=ct,e.col=lt,e.lineStart=!1),l===`
|
|
20
20
|
`?(r+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,r+=l):e.inEsc?(r+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,r+=l,e.col>=s&&(r+=`
|
|
21
21
|
${ct}`,e.col=lt))}return o(r,n,i)}}var ge=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=dt(this._origStdoutWrite,e),process.stderr.write=dt(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
@@ -25,35 +25,35 @@ ${ct}`,e.col=lt))}return o(r,n,i)}}var ge=class{constructor(){this._currentNode=
|
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot($e,e):process.stdout.write.bind(process.stdout)(`${re} ${$e} ${e}
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(it,e):process.stdout.write.bind(process.stdout)(`${re} ${it} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(at,t):process.stdout.write.bind(process.stdout)(`${re} ${at} ${t}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Te,N.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Te} ${N.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${po} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:i}=t;if(i)for(let r of i)this._rawWrite(`${$e} ${r}`);let s=n?N.dim(` ${ut(n)}`):"";this._rawWrite(`${st} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:i}=n,s=i?N.dim(` ${ut(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${st} ${N.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new ge;var se=".zibby/output",ve="sessions",U=".session-info.json",Ae=".zibby-stop",fo="result.json",ho="raw_stream_output.txt",go="events.json",ft={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},mo=Object.freeze([ft.CODEBASE_MEMORY]),ke=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",o=>Number(o)+1);H.helpers.json||H.registerHelper("json",o=>JSON.stringify(o,null,2));H.helpers.eq||H.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new oe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let u=await this.customExecute(e);return typeof u=="object"&&u!==null&&u.success===!1?{success:!1,error:u.error||"Node execution failed",raw:u.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){return E.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(u.issues||u.errors,null,2)}`),{success:!1,error:u.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let r=i("_skillHints");r&&(s=`${r}
|
|
33
33
|
|
|
34
|
-
${s}`);let a=n(),l=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=Be(d,U);if(bt(u)){let S=JSON.parse($t(u,"utf-8"));S.currentNode=this.name,Re(u,JSON.stringify(S,null,2),"utf-8")}let c=Be(d,"..",U);if(bt(c))try{let S=JSON.parse($t(c,"utf-8"));S.currentNode=this.name,Re(c,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(u){I.debug(`[workflow] could not update session info: ${u.message}`)}let p=null;for(let u=0;u<=this.retries;u++)try{I.debug(`[workflow] node '${this.name}' attempt ${u}`);let c=n().config||{},S=c.agents||{},f=this.config.agent??S[this.name]??null,w={state:n()};f&&(w.preferredAgent=f);let b={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let h=await _(s,w,b),g,y;if(typeof h=="string"?(g=h,y=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),y=h.structured):(g=h.raw||JSON.stringify(h,null,2),y=h.extracted||null),d)try{let m=Be(d,this.name,"raw_stream_output.txt");go(mo(m),{recursive:!0}),Re(m,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(m){I.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let m=y;if(typeof this.onComplete=="function")try{m=await this.onComplete(n(),y)}catch(T){I.warn(`[workflow] onComplete hook failed: ${T.message}`)}return{success:!0,output:m,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),x.step("Output parsed"),{success:!0,output:m,raw:g}}return{success:!0,output:g,raw:g}}catch(c){p=c,u<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}};F();F();import{mkdirSync as wo,existsSync as Y,statSync as Ot,readdirSync as Pt,rmSync as _o}from"node:fs";import{spawn as Nt}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Eo}from"node:url";import{AsyncLocalStorage as So}from"node:async_hooks";var Me=new So;function ce(){let o=Me.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function Tt(o,e){let t=Me.getStore()||ce(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Me.run(n,e)}var De=new Map,je=new Map,At=new Map;function vt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");De.set(o,e),je.set(o,"ready"),At.set(o,{...t,cachedAt:Date.now()})}function kt(o,e){je.set(o,"failed"),At.set(o,{error:e?.message||String(e),failedAt:Date.now()}),De.delete(o)}function xt(o){return je.get(o)==="ready"?De.get(o):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Io(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function $o(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!n||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:i}}async function bo({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=i?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=s,r}if(n.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function To(o,e){let t=G(e,".ready"),n=G(e,"graph.mjs");if(Y(t)&&Y(n))return;wo(e,{recursive:!0});let i=G(e,".lock"),s=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(i,"wx");a(l),s=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!s){let r=Date.now()+3e4;for(;Date.now()<r;){if(Y(t)&&Y(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((l,d)=>{let p=Nt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),u=Nt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(u.stdin);let c,S,f=()=>{if(c!==void 0&&S!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(S!==0)return d(new Error(`tar exited ${S}`));l()}};p.on("close",w=>{c=w,f()}),u.on("close",w=>{S=w,f()}),p.on("error",d),u.on("error",d)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(i)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",r.message)}}async function Ao(o){let e=G(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(Eo(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function Ct(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ce(),n;try{n=$o()}catch(T){throw T}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:p,bundleReady:u,nodeConfigs:c}=i,S=Io();if(r&&r!==S)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${r}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${S} vs ${r}`);if(!u||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,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 f=xt(o);if(!f){let T=G(me,`${p}@${d||"0"}`);try{await To(a,T);try{ko()}catch{}}catch($){throw $.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{f=await Ao(T),vt(o,f,{workflowUuid:p,version:d,runtimeTag:r,cacheDir:T})}catch($){throw kt(o,$),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let w=Date.now(),_=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),h=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...h?{nodeConfigs:c}:{}},y,m;try{y=await Tt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>_.run(e.parentAgent,g,{signal:e.signal})),m=y&&typeof y=="object"&&"state"in y?y.state:y}catch(T){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:T.message,code:T.code||"CHILD_THREW",stack:T.stack},durationMs:Date.now()-w}}),T}if(y&&typeof y=="object"&&y.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:m,durationMs:Date.now()-w}});let T=new Error(`Sub-graph '${o}' canceled by parent abort`);throw T.code="SUBGRAPH_CANCELED",T.subgraphJobId=s,T}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:s}}function vo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),i;try{i=Ot(n)}catch{continue}if(i.isDirectory()){let s;try{s=Pt(n)}catch{continue}for(let r of s)t.push(G(n,r))}else e+=i.size}return e}function ko({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=Pt(me),t=[],n=0;for(let a of e){let l=G(me,a),d;try{d=Ot(l)}catch{continue}let p=d.isDirectory()?vo(l):d.size;n+=p,t.push({name:a,full:l,size:p,mtimeMs:d.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,r=0;for(let a of t){if(n-s<=i)break;if(!Y(G(a.full,".lock")))try{_o(a.full,{recursive:!0,force:!0}),s+=a.size,r+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&I.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:s,totalBytes:n-s}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var xo=2e3,No=600*1e3,Oo=new Set(["completed","failed","canceled","timeout"]);function Po(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function Co(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Ro(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Bo(){return process.env.EXECUTION_ID||null}function Rt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Le(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await Ct(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),m=Rt(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),m}catch(y){if(y instanceof O||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Po(),s=Co(),r=Ro(),a=Bo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(d)});if(!p.ok){let y=null,m="";try{y=await p.json(),m=y?.error||y?.message||JSON.stringify(y)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let $=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${$.used??"?"}/${$.limit??"?"} on plan ${$.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=$,R}if(p.status===400){let $=new Error(`Sub-graph '${o}' rejected input: ${m}`);throw $.code="SUBGRAPH_INVALID_INPUT",$.status=400,$.subgraph=o,$.validationErrors=y?.validationErrors||null,$.missing=y?.missing||null,$}let T=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${m}`);throw T.code="SUBGRAPH_TRIGGER_FAILED",T.status=p.status,T.subgraph=o,T}let u=await p.json(),c=u?.data?.jobId||u?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(u).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:No,f=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:xo,w=`${i}/executions/${encodeURIComponent(c)}`,b=Date.now()+S,_="accepted",h=0;for(;Date.now()<b;){await new Promise($=>setTimeout($,f)),h+=1;let y=await fetch(w,{headers:{Authorization:`Bearer ${r}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let m=await y.json(),T=m?.data||m?.execution||m;if(_=T?.status||_,Oo.has(_)){if(_!=="completed"){let E=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw E.subgraphJobId=c,E.subgraphStatus=_,E}let $=T?.finalState||T?.state||{},R=Rt($,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(S/1e3)}s (last status: ${_})`);throw g.subgraphJobId=c,g.subgraphStatus=_,g}import{existsSync as Bt,readFileSync as Mo}from"node:fs";import{join as Fe,dirname as Mt}from"node:path";var le=class{static async loadContext(e,t,n={}){let i={},s=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Mt(Fe(t,e));for(let l of s){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let p=l.replace(/\.[^.]+$/,"").toLowerCase();i[p]=d}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let d=Fe(t,l);Bt(d)&&(i[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return i}static async findAndMergeContextFiles(e,t,n){let i=[],s=t;for(;s.startsWith(n);){let r=Fe(s,e);if(Bt(r))try{i.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Mt(s);if(a===s)break;s=a}return i.length===0?null:i.every(r=>typeof r=="string")?i.join(`
|
|
34
|
+
${s}`);let a=n(),l=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=Be(d,U);if($t(u)){let S=JSON.parse(bt(u,"utf-8"));S.currentNode=this.name,Re(u,JSON.stringify(S,null,2),"utf-8")}let c=Be(d,"..",U);if($t(c))try{let S=JSON.parse(bt(c,"utf-8"));S.currentNode=this.name,Re(c,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(u){E.debug(`[workflow] could not update session info: ${u.message}`)}let f=null;for(let u=0;u<=this.retries;u++)try{E.debug(`[workflow] node '${this.name}' attempt ${u}`);let c=n().config||{},S=c.agents||{},g=this.config.agent??S[this.name]??null,w={state:n()};g&&(w.preferredAgent=g);let b={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let m=await _(s,w,b),h,y;if(typeof m=="string"?(h=m,y=null):m.structured?(h=m.raw||JSON.stringify(m.structured,null,2),y=m.structured):(h=m.raw||JSON.stringify(m,null,2),y=m.extracted||null),d)try{let p=Be(d,this.name,"raw_stream_output.txt");So(yo(p),{recursive:!0}),Re(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),y)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(c){f=c,u<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as Io,existsSync as Y,statSync as Ct,readdirSync as Rt,rmSync as Eo}from"node:fs";import{spawn as Nt}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as bo}from"node:url";import{AsyncLocalStorage as $o}from"node:async_hooks";import{AsyncLocalStorage as wo}from"node:async_hooks";var Me=new wo;function ce(){let o=Me.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function Tt(o,e){let t=Me.getStore()||ce(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Me.run(n,e)}var je=new Map,De=new Map,vt=new Map;function At(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");je.set(o,e),De.set(o,"ready"),vt.set(o,{...t,cachedAt:Date.now()})}function kt(o,e){De.set(o,"failed"),vt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),je.delete(o)}function xt(o){return De.get(o)==="ready"?je.get(o):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function To(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},Ot=new $o,Pt=Promise.resolve();async function vo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Ot.getStore()===!0,i=null;if(!n){let r=Pt;Pt=new Promise(a=>{i=a}),await r}let s=new Map;try{for(let[r,a]of t)s.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Ot.run(!0,e)}finally{for(let[r,a]of s)a===void 0?delete process.env[r]:process.env[r]=a;i&&i()}}function Ao(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!n||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:i}}async function ko({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=i?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=s,r}if(n.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function xo(o,e){let t=G(e,".ready"),n=G(e,"graph.mjs");if(Y(t)&&Y(n))return;Io(e,{recursive:!0});let i=G(e,".lock"),s=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(i,"wx");a(l),s=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!s){let r=Date.now()+3e4;for(;Date.now()<r;){if(Y(t)&&Y(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((l,d)=>{let f=Nt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),u=Nt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(u.stdin);let c,S,g=()=>{if(c!==void 0&&S!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(S!==0)return d(new Error(`tar exited ${S}`));l()}};f.on("close",w=>{c=w,g()}),u.on("close",w=>{S=w,g()}),f.on("error",d),u.on("error",d)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(i)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",r.message)}}async function No(o){let e=G(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(bo(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function Bt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ce(),n;try{n=Ao()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await ko({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:f,bundleReady:u,nodeConfigs:c}=i,S=To();if(r&&r!==S)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${r}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${S} vs ${r}`);if(!u||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,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 g=xt(o);if(!g){let p=G(me,`${f}@${d||"0"}`);try{await xo(a,p);try{Po()}catch{}}catch($){throw $.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await No(p),At(o,g,{workflowUuid:f,version:d,runtimeTag:r,cacheDir:p})}catch($){throw kt(o,$),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let w=Date.now(),b=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},h,y;try{h=await vo(b,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Tt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),y=h&&typeof h=="object"&&"state"in h?h.state:h}catch(p){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-w}}),p}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:y,durationMs:Date.now()-w}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-w}}),{finalState:y,executionId:s}}function Oo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let s;try{s=Rt(n)}catch{continue}for(let r of s)t.push(G(n,r))}else e+=i.size}return e}function Po({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=Rt(me),t=[],n=0;for(let a of e){let l=G(me,a),d;try{d=Ct(l)}catch{continue}let f=d.isDirectory()?Oo(l):d.size;n+=f,t.push({name:a,full:l,size:f,mtimeMs:d.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,r=0;for(let a of t){if(n-s<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),s+=a.size,r+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&E.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:s,totalBytes:n-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Co=2e3,Ro=600*1e3,Bo=new Set(["completed","failed","canceled","timeout"]);function Mo(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function jo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Do(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Lo(){return process.env.EXECUTION_ID||null}function Mt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Le(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await Bt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Mt(y,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(y){if(y instanceof O||y?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Mo(),s=jo(),r=Do(),a=Lo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(d)});if(!f.ok){let y=null,p="";try{y=await f.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let A=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' 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 R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=A,R}if(f.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=y?.validationErrors||null,A.missing=y?.missing||null,A}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let u=await f.json(),c=u?.data?.jobId||u?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(u).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:Ro,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Co,w=`${i}/executions/${encodeURIComponent(c)}`,b=Date.now()+S,_="accepted",m=0;for(;Date.now()<b;){await new Promise(A=>setTimeout(A,g)),m+=1;let y=await fetch(w,{headers:{Authorization:`Bearer ${r}`}});if(!y.ok){if(y.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Bo.has(_)){if(_!=="completed"){let I=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw I.subgraphJobId=c,I.subgraphStatus=_,I}let A=$?.finalState||$?.state||{},R=Mt(A,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),R}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(S/1e3)}s (last status: ${_})`);throw h.subgraphJobId=c,h.subgraphStatus=_,h}import{existsSync as jt,readFileSync as Fo}from"node:fs";import{join as Fe,dirname as Dt}from"node:path";var le=class{static async loadContext(e,t,n={}){let i={},s=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Dt(Fe(t,e));for(let l of s){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=d}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let d=Fe(t,l);jt(d)&&(i[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return i}static async findAndMergeContextFiles(e,t,n){let i=[],s=t;for(;s.startsWith(n);){let r=Fe(s,e);if(jt(r))try{i.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Dt(s);if(a===s)break;s=a}return i.length===0?null:i.every(r=>typeof r=="string")?i.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):i.every(r=>typeof r=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let t=
|
|
38
|
+
`):i.every(r=>typeof r=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let t=Fo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),i=await import(n(e).href);return i.default||i}return t}};import{mkdirSync as Gt,existsSync as Ge,writeFileSync as Lt,unlinkSync as Go}from"node:fs";import{join as z,resolve as Ut}from"node:path";import{config as Uo}from"dotenv";import{zodToJsonSchema as Ft}from"zod-to-json-schema";import{z as Se}from"zod";import Wo from"handlebars";function Ho({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${n} mkdir=${i?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let f=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${p}`)}}function Gt(){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 Ut(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ft(String(e).trim())}catch{return String(e).trim()}}function Wt(){Gt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ht({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Jt(o={}){let e=ke.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${n}`:n}function Yt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,r="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let d=Ft(String(process.env.ZIBBY_SESSION_PATH));d&&(i=d,r="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,r="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=Jt(e),r="generated")}s=s??Date.now();let p=e.paths?.output||se;i=z(o,p,Ae,a)}let l=!Ge(i);return l&&Lt(i,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Fo({traceFrom:n,sessionId:a,sessionPath:i,idSource:r,mkdirFresh:l}),Ht({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async d=>{let p=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof r.input=="function"?u=r.input(p):r.input&&typeof r.input=="object"?u=r.input:u={},Le(r.workflow,{input:u,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(p):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:p?._signal,parentAgent:d?.agent})}},l=new L(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,i,s){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],d=r;r=()=>l(t,d,i,s)}return r()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let S=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:S,data:{nodeType:S,label:u}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(f.description=w);let b=this.nodePrompts.get(u);if(b)f.prompt=b;else if(typeof c.prompt=="function")try{let m=c.prompt({});typeof m=="string"&&m.trim()&&(f.prompt=m,f.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(f.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let m=null;if(typeof Se?.toJSONSchema=="function")try{m=Se.toJSONSchema(c.outputSchema)}catch{}if(!m)try{m=jt(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=m?{jsonSchema:m,variables:this._flattenJsonSchemaToVariables(m)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[u];_?.toolIds&&(f.tools=_.toolIds);let h=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;h&&h.length>0&&(f.skills=[...h]);let g=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;g&&g.length>0&&(f.plugins=g.map(m=>m&&typeof m=="object"?{...m}:m));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(f.stores=y.map(m=>m&&typeof m=="object"?{...m}:m)),Object.keys(f).length>0&&(t[u]=f)}let n=[];for(let[u,c]of this.edges)if(typeof c=="string")n.push({source:u,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(u)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},b=this.nodes.get(u),_=b?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!b,h=u;if(!_){let g=`${u}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:u,target:g}),h=g}for(let g of f){let y={source:h,target:g,data:{conditionalCode:S}};w[g]&&(y.label=w[g]),n.push(y)}}let i=u=>{if(!u)return null;if(typeof Se?.toJSONSchema=="function")try{return Se.toJSONSchema(u)}catch{}try{return jt(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let s=0;for(let u of n)if(u.target==="END"){s+=1;let c=`END__${s}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:u,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=i(a||this.stateSchema),d=i(this.inputSchema),p=i(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:p}}_topoOrderNodes(e,t){let n=new Map(e.map((u,c)=>[u.id,c])),i=new Map(e.map(u=>[u.id,u])),s=new Map(e.map(u=>[u.id,0])),r=new Map(e.map(u=>[u.id,[]]));for(let u of t)r.has(u.source)&&s.has(u.target)&&(r.get(u.source).push(u.target),s.set(u.target,s.get(u.target)+1));let a=new Set,l=new Set(n.keys()),d=[...l].filter(u=>s.get(u)===0),p=[];for(;p.length<e.length;){let u;if(d.length>0){if(d.sort((c,S)=>n.get(c)-n.get(S)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,S)=>n.get(c)-n.get(S))[0];a.add(u),l.delete(u),p.push(i.get(u));for(let c of r.get(u)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return p}_inferConditionalTargets(e,t){let n=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=s.exec(n))!==null;){let d=r[2]!==void 0?r[2]:r[3];d!==void 0&&d!==""&&i.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of i)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=d.exec(n))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},s=e.required||[];for(let[r,a]of Object.entries(i)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!s.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)n.push(`${i}: ${s}`);else if(Array.isArray(s)){let r=s.length,a=s.filter(d=>d?.passed===!0).length,l=s.some(d=>d?.passed!==void 0);n.push(l?`${i}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${i}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();jo({path:z(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let A=z(r,".zibby.config.js");Ge(A)&&(a=(await import(A)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let A=a?.agent;A?.provider?l=A.provider:A?.gemini?l="gemini":A?.claude?l="claude":A?.cursor?l="cursor":A?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let A=p.safeParse(t);if(!A.success){let P=A.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let u=Ut(),c=t.sessionPath||u;c||Wt();let{sessionPath:S,sessionTimestamp:f,sessionId:w}=Yt({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${w}`);let b=await le.loadContext(t.specPath||"",r,d);Object.keys(b).length>0&&x.step(`Context loaded: ${Object.keys(b).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let h=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:S,sessionTimestamp:f,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ie(),wt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},T=Object.values(m).filter(A=>A&&typeof A=="object"&&typeof A.id=="string"),$=A=>{for(let P of T)if(P.id===A)return P;return y(A)},R=new Set;for(let[,A]of this.nodes)for(let P of A.config?.skills||[])R.add(P);for(let A of R){let P=$(A);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&g.set(A,C)}catch{}}let E=this.entryPoint,de=[],Ze=a?.recursionLimit??100,Vt=0;try{for(;E&&E!=="END";){if(++Vt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=z(S,ve);if(Ge(P)){try{Do(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:
|
|
43
|
-
${
|
|
41
|
+
${f}`)}}function Wt(){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 Ht(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Ut(String(e).trim())}catch{return String(e).trim()}}function Jt(){Wt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Yt({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function zt(o={}){let e=ke.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${n}`:n}function Zt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,r="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let d=Ut(String(process.env.ZIBBY_SESSION_PATH));d&&(i=d,r="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,r="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=zt(e),r="generated")}s=s??Date.now();let f=e.paths?.output||se;i=z(o,f,ve,a)}let l=!Ge(i);return l&&Gt(i,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Ho({traceFrom:n,sessionId:a,sessionPath:i,idSource:r,mkdirFresh:l}),Yt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async d=>{let f=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof r.input=="function"?u=r.input(f):r.input&&typeof r.input=="object"?u=r.input:u={},Le(r.workflow,{input:u,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:d?.agent})}},l=new L(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,i,s){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],d=r;r=()=>l(t,d,i,s)}return r()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let S=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:S,data:{nodeType:S,label:u}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(g.description=w);let b=this.nodePrompts.get(u);if(b)g.prompt=b;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof Se?.toJSONSchema=="function")try{p=Se.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ft(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[u];_?.toolIds&&(g.tools=_.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(g.skills=[...m]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(g.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(g.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[u]=g)}let n=[];for(let[u,c]of this.edges)if(typeof c=="string")n.push({source:u,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(u)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},b=this.nodes.get(u),_=b?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!b,m=u;if(!_){let h=`${u}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),n.push({source:u,target:h}),m=h}for(let h of g){let y={source:m,target:h,data:{conditionalCode:S}};w[h]&&(y.label=w[h]),n.push(y)}}let i=u=>{if(!u)return null;if(typeof Se?.toJSONSchema=="function")try{return Se.toJSONSchema(u)}catch{}try{return Ft(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let s=0;for(let u of n)if(u.target==="END"){s+=1;let c=`END__${s}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:u,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=i(a||this.stateSchema),d=i(this.inputSchema),f=i(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:f}}_topoOrderNodes(e,t){let n=new Map(e.map((u,c)=>[u.id,c])),i=new Map(e.map(u=>[u.id,u])),s=new Map(e.map(u=>[u.id,0])),r=new Map(e.map(u=>[u.id,[]]));for(let u of t)r.has(u.source)&&s.has(u.target)&&(r.get(u.source).push(u.target),s.set(u.target,s.get(u.target)+1));let a=new Set,l=new Set(n.keys()),d=[...l].filter(u=>s.get(u)===0),f=[];for(;f.length<e.length;){let u;if(d.length>0){if(d.sort((c,S)=>n.get(c)-n.get(S)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,S)=>n.get(c)-n.get(S))[0];a.add(u),l.delete(u),f.push(i.get(u));for(let c of r.get(u)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return f}_inferConditionalTargets(e,t){let n=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=s.exec(n))!==null;){let d=r[2]!==void 0?r[2]:r[3];d!==void 0&&d!==""&&i.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of i)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=d.exec(n))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},s=e.required||[];for(let[r,a]of Object.entries(i)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!s.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)n.push(`${i}: ${s}`);else if(Array.isArray(s)){let r=s.length,a=s.filter(d=>d?.passed===!0).length,l=s.some(d=>d?.passed!==void 0);n.push(l?`${i}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${i}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Uo({path:z(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=z(r,".zibby.config.js");Ge(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let T=f.safeParse(t);if(!T.success){let P=T.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let u=Ht(),c=t.sessionPath||u;c||Jt();let{sessionPath:S,sessionTimestamp:g,sessionId:w}=Zt({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${w}`);let b=await le.loadContext(t.specPath||"",r,d);Object.keys(b).length>0&&x.step(`Context loaded: ${Object.keys(b).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:S,sessionTimestamp:g,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ie(),wt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let P of $)if(P.id===T)return P;return y(T)},R=new Set;for(let[,T]of this.nodes)for(let P of T.config?.skills||[])R.add(P);for(let T of R){let P=A(T);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&h.set(T,C)}catch{}}let I=this.entryPoint,de=[],Ze=a?.recursionLimit??100,Xt=0;try{for(;I&&I!=="END";){if(++Xt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=z(S,Ae);if(Ge(P)){try{Go(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:de,stoppedExternally:!0};let C=this.nodes.get(I);if(!C)throw new Error(`Node '${I}' not found in graph`);let Ke=JSON.stringify({sessionPath:S,sessionTimestamp:g,currentNode:I,createdAt:new Date().toISOString(),config:m.get("config")}),Qt=z(S,U);Lt(Qt,Ke,"utf-8");let Ve=m.get("config")?.paths?.output||se,eo=z(r,Ve,U);Gt(z(r,Ve),{recursive:!0});try{Lt(eo,Ke,"utf-8")}catch{}let qe=t.onPipelineProgress;if(typeof qe=="function")try{qe({cwd:r,sessionPath:S,sessionId:w,outputBase:m.get("config")?.paths?.output||se,currentNode:I})}catch{}let to=(this.resolvedToolsMap||{})[I]||null;m.set("_currentNodeTools",to);let oo=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",oo[I]||{}),x.nodeStart(I);let Xe=Date.now(),pe=this.nodePrompts.get(I);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(X(),ae));this._invokeAgent=k.invokeAgent}let no=this._invokeAgent,Ie={},ro=C.config?.skills||[];for(let k of ro){let B=A(k);if(typeof B?.invokeAgentOptions=="function")try{let v=B.invokeAgentOptions(m.getAll(),{agentType:m.get("agentType"),nodeName:I});v&&typeof v=="object"&&(Ie={...Ie,...v})}catch(v){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${v.message}`)}}let Qe=async(k,B,v={})=>{let M=no(k,B,{...Ie,...v,signal:i.signal});return M.catch(()=>{}),i.signal.aborted?M:Promise.race([M,new Promise((Z,K)=>{let D=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);ee.name="AbortError",K(ee)},s)};i.signal.addEventListener("abort",D,{once:!0})})])},so=async(k={},B={})=>{let v=B.prompt||"";if(pe){let M=this._compiledPrompts.get(I);M||(M=Wo.compile(pe,{noEscape:!0}),this._compiledPrompts.set(I,M));try{v=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${I}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!v)throw new Error(`No prompt template configured for node '${I}' and no prompt provided in options`);return Qe(v,{state:m.getAll(),images:B.images||[]},{model:B.model||m.get("model"),workspace:m.get("workspace"),schema:B.schema,...B,signal:i.signal})},et=m.getAll(),io=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of io)Object.prototype.hasOwnProperty.call(et,k)&&console.warn(`[workflow] node "${I}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let tt={...et,state:m,invokeAgent:so,_coreInvokeAgent:Qe,agent:e,nodeId:I,promptTemplate:pe,getPromptTemplate:()=>pe};try{let k=(C.config?.skills||[]).map(D=>h.get(D)).filter(Boolean),B=[...this.middleware,...k],v;B.length>0?v=await this._composeMiddleware(B,I,async()=>C.execute(tt,m),m.getAll(),m):v=await C.execute(tt,m);let M=Date.now()-Xe;if(de.push({node:I,success:v.success,duration:M,timestamp:new Date().toISOString()}),!v.success){if(i.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:de,stoppedExternally:!0};m.append("errors",{node:I,error:v.error});let D=C.config?.retries||0,ee=`${I}_retries`,fe=m.getAll()[ee]||0;if(fe<D){x.stepInfo(`Retrying (attempt ${fe+1}/${D})`),m.update({[ee]:fe+1,[`${I}_raw`]:v.raw});continue}throw x.nodeFailed(I,v.error,{duration:M}),new Error(`Node '${I}' failed after ${fe} attempts: ${v.error}`)}m.update({[I]:v.output});let Z=this._summarizeNodeOutput(I,v.output);x.nodeComplete(I,{duration:M,details:Z});let K=this.edges.get(I);if(!K)I="END";else if(K.conditional){let D=K.routes(m.getAll());x.route(I,D),I=D}else I=K}catch(k){throw x.isInsideNode&&x.nodeFailed(I,k.message,{duration:Date.now()-Xe}),m.set("failed",!0),m.set("failedAt",I),k}}x.graphComplete();let T={success:!0,state:m.getAll(),executionLog:de};return e&&typeof e.onComplete=="function"&&await e.onComplete(T),T}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(T){console.warn(`[workflow] agent.cleanup() failed: ${T.message}`)}}}};var Ue=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ue]||(globalThis[Ue]=new Map);var ue=globalThis[Ue];function Kt(o,e){ue.set(o,e)}function We(o){return ue.get(o)}function ye(o){return ue.has(o)}function Jo(){return Array.from(ue.keys())}function He(o){let e=ue.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Kt("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",s=Yo(i,t),r=await n(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function Yo(o,e){let t=/@([\w.]+)/g,n=new Set,i;for(;(i=t.exec(o))!==null;)n.add(i[1]);if(n.size===0)return o;let s=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let d=a.split(".").reduce((c,S)=>c?.[S],e);if(d===void 0)continue;let f=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${u}
|
|
43
|
+
${f}`),a.includes(".")||r.add(l)}return s.length===0?o:`${o}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
48
|
${s.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}ie();F();var we={};function Ye(o,e){if(Array.isArray(e))return Je(e);let t=we[o];return!t||t.length===0?null:Je(t)}function Je(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let i of o){let s=q(i);if(!s){
|
|
51
|
-
`)}function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`).map((
|
|
50
|
+
`)}`}ie();F();var we={};function Ye(o,e){if(Array.isArray(e))return Je(e);let t=we[o];return!t||t.length===0?null:Je(t)}function Je(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let i of o){let s=q(i);if(!s){E.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}n.push(i);for(let r of s.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let r=s.resolve();r&&(t[s.serverName]={...r,toolPrefix:i})}else{let r={};for(let a of s.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:r,toolPrefix:i}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}F();function zo(o,e={}){let{nodes:t,edges:n,nodeConfigs:i={}}=o;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(n))throw new j("Graph edges must be an array");let s=new Q(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let S=_e(c);a.set(c.id,{...c,resolvedType:S}),S==="decision"&&r.add(c.id)}for(let[c,S]of a){if(r.has(c))continue;let g=S.resolvedType,w=i[c]||{},b=Ye(g,w.tools);b&&(l[c]=b);let _={};w.prompt&&(_.prompt=w.prompt);let m=ye(g);if(E.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${m}`),w.customCode&&!m)s.addNode(c,Vt(c,w.customCode,w),_),s.setNodeType(c,g);else if(m){let h=We(g);h.factory?s.addNode(c,h.create(c,{...w,resolvedTools:b}),_):s.addNode(c,h,_),s.setNodeType(c,g)}else if(w.executeCode)s.addNode(c,Vt(c,w.executeCode,w),_),s.setNodeType(c,g);else throw new j(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=l;let d=new Set;for(let c of n)r.has(c.target)||d.add(c.target);let f=t.find(c=>!r.has(c.id)&&!d.has(c.id));if(!f)throw new j("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(f.id);let u=Vo(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let S=c.target,g=u.get(S)||[];if(g.length===0)throw new j(`Decision node "${S}" has no outgoing edges`);let w=qo(S,g,r);s.addConditionalEdges(c.source,w)}else s.addEdge(c.source,c.target);return s}function Zo(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=_e(a);if(l==="decision"||ye(l))continue;let d=t[a.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let i=new Set(o.nodes.filter(a=>_e(a)==="decision").map(a=>a.id)),s=new Set;for(let a of o.edges)i.has(a.target)||s.add(a.target);let r=o.nodes.filter(a=>!i.has(a.id)&&!s.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of i){let l=o.edges.filter(f=>f.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Ko(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>_e(e)!=="decision").map(e=>e.id)}function _e(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Vo(o,e){let t=new Map;for(let n of o){let i=n[e];t.has(i)||t.set(i,[]),t.get(i).push(n)}return t}function qo(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new j(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let i=n.data?.conditionalCode||n.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${i})`)();r=d=>{let f=l(d);return s.has(f)||E.warn(`[workflow] conditional route from "${o}" returned "${f}" which is not in valid targets: ${[...s].join(", ")}`),f}}catch(a){throw new j(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function Vt(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new j(`Failed to compile customCode for node "${o}": ${r.message}`)}let i=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),ae));return a(...r)},typeof Ee<"u"?Ee:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async r=>{try{let a=await i(r);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ie();var ze=/^[a-z][a-z0-9_]{0,40}$/;function Xo(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,i)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${i}] must be an object { name, description }`);return}let{name:s}=n;if(typeof s!="string"||s.length===0){e.push(`stores[${i}] is missing a string "name"`);return}ze.test(s)||e.push(`stores[${i}] name "${s}" is invalid \u2014 must match ${ze} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(s)?e.push(`stores[${i}] duplicate store name "${s}" (also at index ${t.get(s)}) \u2014 store names must be unique within a workflow`):t.set(s,i)}),e}Ne();X();function Qo(o,e={}){let{nodes:t,edges:n,nodeConfigs:i={}}=o,s=new Set,r=[],a=new Map;for(let b of t){let _=b.data?.nodeType||b.type;a.set(b.id,_),_==="decision"?s.add(b.id):r.push({id:b.id,nodeType:_,label:b.data?.label||b.id})}let l=r.some(b=>{let _=i[b.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:d,toolIdsByVar:f}=cn(r,i),{simpleEdges:u,conditionalEdges:c}=ln(n,s),S=un(r,n,s),g=[],w=e.workflowType||"workflow";return g.push(tn(e)),g.push(on(w,{usesRegisteredNodes:l})),g.push(nn(f)),g.push(rn(w)),g.push(sn(r,i)),g.push(an(r,S,u,c,d,w)),g.filter(Boolean).join(`
|
|
51
|
+
`)}function en(o){let e={};for(let[t,n]of Object.entries(o)){let{tools:i,...s}=n;Object.keys(s).length>0&&(e[t]=s)}return e}function tn(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
|
+
`)}function on(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
53
|
+
`)}function nn(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,n]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
|
|
54
|
+
`)}function rn(o){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
55
|
+
`)}function sn(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let n of o){let i=qt(n.id),s=e[n.id]?.customCode;if(s)t.push(`// @custom \u2014 modified from default "${n.nodeType}" template`),t.push(`const ${i}_execute = ${s};`);else{let r=He(n.nodeType);r?(t.push(`// Default "${n.nodeType}" implementation`),t.push(`const ${i}_execute = ${r};`)):(t.push(`// No template for "${n.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
56
|
+
`)}function an(o,e,t,n,i,s){let r=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let l of o){let d=qt(l.id);r.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${d}_execute });`),r.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||n.length>0)&&r.push(" // Edges");for(let l of t)r.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of n){let d=l.code.split(`
|
|
57
|
+
`).map((f,u)=>u===0?f:` ${f}`).join(`
|
|
58
58
|
`);r.push(` graph.addConditionalEdges('${l.source}', ${d});`)}let a=[];for(let l of o){let d=i.get(l.id);d&&a.push(` '${l.id}': ${d},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
|
|
59
|
-
`)}function
|
|
59
|
+
`)}function cn(o,e){let t=new Map,n=new Map;for(let i of o){let s=e[i.id]?.tools,r;if(Array.isArray(s)&&s.length>0)r=[...s].sort();else{let a=we[i.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,a),n.has(a)||n.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:n}}function ln(o,e){let t=[],n=[],i=new Map,s=new Set;for(let r of o)i.has(r.source)||i.set(r.source,[]),i.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(s.has(r.target))continue;s.add(r.target);let l=(i.get(r.target)||[]).find(d=>d.data?.conditionalCode||d.conditionalCode);l&&n.push({source:r.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:n}}function un(o,e,t){let n=new Set;for(let s of e)t.has(s.target)||n.add(s.target);let i=o.find(s=>!n.has(s.id));return i?i.id:o[0]?.id}function qt(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}F();export{xe as AgentStrategy,ke as CI_ENV_VARS,j as CompilationError,le as ContextLoader,se as DEFAULT_OUTPUT_BASE,go as EVENTS_FILE,Q as Graph,we as NODE_DEFAULT_TOOLS,mo as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,L as Node,oe as OutputParser,ho as RAW_OUTPUT_FILE,fo as RESULT_FILE,ve as SESSIONS_DIR,U as SESSION_INFO_FILE,ft as SKILLS,Ae as STOP_REQUEST_FILE,ze as STORE_NAME_REGEX,lo as SchemaTypes,ge as Timeline,pt as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,Q as WorkflowGraph,te as WorkflowState,Jt as clearInheritedSessionEnvForFreshRun,yt as clearSkills,zo as compileGraph,Le as dispatchSubgraph,Ko as extractSteps,en as generateNodeConfigsJson,Qo as generateWorkflowCode,zt as generateWorkflowSessionId,Ce as getAgentStrategy,mt as getAllSkills,We as getNodeImpl,He as getNodeTemplate,Je as getResolvedToolDefinitions,q as getSkill,ye as hasNode,gt as hasSkill,Et as invokeAgent,Jo as listNodeTypes,St as listSkillIds,It as listStrategies,Ht as readPinnedSessionPathFromEnv,Kt as registerNode,ht as registerSkill,_t as registerStrategy,Ye as resolveNodeTools,Zt as resolveWorkflowSession,uo as setLogger,Wt as shouldTrustInheritedSessionEnv,Yt as syncProcessEnvToSession,x as timeline,Zo as validateGraphConfig,Xo as validateStoreDefs};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var M=()=>{},Y={debug:M,info:M,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Y};var f={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as K,existsSync as x,statSync as F,readdirSync as q,rmSync as W}from"node:fs";import{spawn as z}from"node:child_process";import{join as $}from"node:path";import{pathToFileURL as Q}from"node:url";import{AsyncLocalStorage as Z}from"node:async_hooks";var O=new Z;function A(){let e=O.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 j(e,t){let n=O.getStore()||A(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null});return O.run(r,t)}var U=new Map,k=new Map,L=new Map;function G(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");U.set(e,t),k.set(e,"ready"),L.set(e,{...n,cachedAt:Date.now()})}function H(e,t){k.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),U.delete(e)}function J(e){return k.get(e)==="ready"?U.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ee(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var g=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}};function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!n||!r||!s)throw new g("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:s}}async function re({apiBase:e,authToken:t,body:n}){let r;try{r=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(o){throw new g("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await r.json()}catch{}if(!r.ok){if(r.status===404){let o=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(r.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(r.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 g("begin-status",`begin returned ${r.status}`)}return s?.data||s}async function _({apiBase:e,authToken:t,payload:n}){try{let r=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});r.ok||f.warn(`[in-process subgraph] finalize returned ${r.status} for ${n.childExecutionId}`)}catch(r){f.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ne(e,t){let n=$(t,".ready"),r=$(t,"graph.mjs");if(x(n)&&x(r))return;K(t,{recursive:!0});let s=$(t,".lock"),o=!1;try{let{openSync:a,closeSync:u}=await import("node:fs"),b=a(s,"wx");u(b),o=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!o){let a=Date.now()+3e4;for(;Date.now()<a;){if(x(n)&&x(r))return;await new Promise(u=>setTimeout(u,100))}throw new g("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((b,I)=>{let l=z("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),m=z("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});l.stdout.pipe(m.stdin);let p,w,y=()=>{if(p!==void 0&&w!==void 0){if(p!==0)return I(new Error(`curl exited ${p}`));if(w!==0)return I(new Error(`tar exited ${w}`));b()}};l.on("close",S=>{p=S,y()}),m.on("close",S=>{w=S,y()}),l.on("error",I),m.on("error",I)});let{writeFileSync:a,unlinkSync:u}=await import("node:fs");a(n,"");try{u(s)}catch{}}catch(a){try{let{unlinkSync:u}=await import("node:fs");u(s)}catch{}throw new g("bundle-extract-failed",a.message)}}async function oe(e){let t=$(e,"graph.mjs");if(!x(t))throw new g("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Q(t).href)}catch(s){throw new g("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=n.default||Object.values(n).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new g("entry-class-missing","no buildGraph() class export found");return r}async function N(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=A(),r;try{r=te()}catch(d){throw d}f.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let s=await re({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:u,sourcesPresignedUrl:b,workflowVersion:I,workflowUuid:l,bundleReady:m,nodeConfigs:p}=s,w=ee();if(a&&a!==w)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${w} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new g("runtime-mismatch",`${w} vs ${a}`);if(!m||!u)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new g("no-bundle","workflow bundle not built yet");let y=J(e);if(!y){let d=$(P,`${l}@${I||"0"}`);try{await ne(u,d);try{ae()}catch{}}catch(c){throw c.fallback&&await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{y=await oe(d),G(e,y,{workflowUuid:l,version:I,runtimeTag:a,cacheDir:d})}catch(c){throw H(e,c),await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new g("import-failed",c.message)}}let S=Date.now(),E=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph(),B=p&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,v={...t.input||{},...B?{nodeConfigs:p}:{}},i,h;try{i=await j({executionId:o,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,v,{signal:t.signal})),h=i&&typeof i=="object"&&"state"in i?i.state:i}catch(d){throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-S}}),d}if(i&&typeof i=="object"&&i.stoppedExternally){await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",finalState:h,durationMs:Date.now()-S}});let d=new Error(`Sub-graph '${e}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=o,d}return await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"completed",finalState:h,durationMs:Date.now()-S}}),{finalState:h,executionId:o}}function se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),s;try{s=F(r)}catch{continue}if(s.isDirectory()){let o;try{o=q(r)}catch{continue}for(let a of o)n.push($(r,a))}else t+=s.size}return t}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!x(P))return{evicted:0,freedBytes:0};let t=q(P),n=[],r=0;for(let u of t){let b=$(P,u),I;try{I=F(b)}catch{continue}let l=I.isDirectory()?se(b):I.size;r+=l,n.push({name:u,full:b,size:l,mtimeMs:I.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((u,b)=>u.mtimeMs-b.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let u of n){if(r-o<=s)break;if(!x($(u.full,".lock")))try{W(u.full,{recursive:!0,force:!0}),o+=u.size,a+=1}catch(b){f.debug(`[sub-graph cache] evict skip ${u.name}: ${b.message}`)}}return a>0&&f.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:r-o}}catch(t){return f.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ie=2e3,ce=600*1e3,ue=new Set(["completed","failed","canceled","timeout"]);function de(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function pe(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function le(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function he(){return process.env.EXECUTION_ID||null}function X(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}async function ve(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=A(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{f.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:i}=await N(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),h=X(i,t.output);return f.info(`[sub-graph] '${e}' completed in-process`),h}catch(i){if(i instanceof g||i?.fallback)f.info(`[sub-graph] in-process fallback for '${e}': ${i.reason||"unknown"} \u2014 using HTTP`);else throw i}let s=de(),o=pe(),a=le(),u=he(),b=`${s}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(e)}/trigger`,I={input:t.input||{},...u?{parentExecutionId:u}:{},...t.conversationId?{conversationId:t.conversationId}:{}};f.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${u||"<none>"}`);let l=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(I)});if(!l.ok){let i=null,h="";try{i=await l.json(),h=i?.error||i?.message||JSON.stringify(i)}catch{h=await l.text().catch(()=>"")}if(l.status===429){let c=i?.quotaInfo||{},T=new Error(`Sub-graph '${e}' blocked by execution quota (${c.used??"?"}/${c.limit??"?"} on plan ${c.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw T.code="SUBGRAPH_QUOTA_EXCEEDED",T.status=429,T.subgraph=e,T.quotaInfo=c,T}if(l.status===400){let c=new Error(`Sub-graph '${e}' rejected input: ${h}`);throw c.code="SUBGRAPH_INVALID_INPUT",c.status=400,c.subgraph=e,c.validationErrors=i?.validationErrors||null,c.missing=i?.missing||null,c}let d=new Error(`Sub-graph '${e}' trigger rejected (${l.status}): ${h}`);throw d.code="SUBGRAPH_TRIGGER_FAILED",d.status=l.status,d.subgraph=e,d}let m=await l.json(),p=m?.data?.jobId||m?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(m).slice(0,200)}`);if(t.async)return f.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let w=Number.isFinite(t.timeoutMs)?t.timeoutMs:ce,y=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ie,S=`${s}/executions/${encodeURIComponent(p)}`,D=Date.now()+w,E="accepted",B=0;for(;Date.now()<D;){await new Promise(c=>setTimeout(c,y)),B+=1;let i=await fetch(S,{headers:{Authorization:`Bearer ${a}`}});if(!i.ok){if(i.status>=500){f.warn(`[sub-graph] status poll for ${p} returned ${i.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${i.status}`)}let h=await i.json(),d=h?.data||h?.execution||h;if(E=d?.status||E,ue.has(E)){if(E!=="completed"){let C=new Error(`Sub-graph '${e}' (${p}) ended in status '${E}'`);throw C.subgraphJobId=p,C.subgraphStatus=E,C}let c=d?.finalState||d?.state||{},T=X(c,t.output);return f.info(`[sub-graph] '${e}' (${p}) completed after ${B} polls`),T}}let v=new Error(`Sub-graph '${e}' (${p}) timed out after ${Math.round(w/1e3)}s (last status: ${E})`);throw v.subgraphJobId=p,v.subgraphStatus=E,v}export{ve as dispatchSubgraph};
|
|
1
|
+
var D=()=>{},Z={debug:D,info:D,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Z};var h={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as W,existsSync as x,statSync as N,readdirSync as X,rmSync as ee}from"node:fs";import{spawn as z}from"node:child_process";import{join as v}from"node:path";import{pathToFileURL as te}from"node:url";import{AsyncLocalStorage as re}from"node:async_hooks";import{AsyncLocalStorage as K}from"node:async_hooks";var U=new K;function A(){let e=U.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 j(e,t){let n=U.getStore()||A(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null});return U.run(r,t)}var k=new Map,M=new Map,L=new Map;function H(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");k.set(e,t),M.set(e,"ready"),L.set(e,{...n,cachedAt:Date.now()})}function G(e,t){M.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),k.delete(e)}function J(e){return M.get(e)==="ready"?k.get(e):null}var P=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ne(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var g=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}},F=new re,q=Promise.resolve();async function oe(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(n.length===0)return t();let r=F.getStore()===!0,a=null;if(!r){let s=q;q=new Promise(i=>{a=i}),await s}let o=new Map;try{for(let[s,i]of n)o.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return h.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await F.run(!0,t)}finally{for(let[s,i]of o)i===void 0?delete process.env[s]:process.env[s]=i;a&&a()}}function se(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!n||!r||!a)throw new g("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:a}}async function ae({apiBase:e,authToken:t,body:n}){let r;try{r=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})}catch(o){throw new g("network",`begin fetch failed: ${o.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let o=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(r.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(r.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 g("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function _({apiBase:e,authToken:t,payload:n}){try{let r=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});r.ok||h.warn(`[in-process subgraph] finalize returned ${r.status} for ${n.childExecutionId}`)}catch(r){h.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ie(e,t){let n=v(t,".ready"),r=v(t,"graph.mjs");if(x(n)&&x(r))return;W(t,{recursive:!0});let a=v(t,".lock"),o=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),y=s(a,"wx");i(y),o=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!o){let s=Date.now()+3e4;for(;Date.now()<s;){if(x(n)&&x(r))return;await new Promise(i=>setTimeout(i,100))}throw new g("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,b)=>{let l=z("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=z("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});l.stdout.pipe(S.stdin);let p,E,w=()=>{if(p!==void 0&&E!==void 0){if(p!==0)return b(new Error(`curl exited ${p}`));if(E!==0)return b(new Error(`tar exited ${E}`));y()}};l.on("close",$=>{p=$,w()}),S.on("close",$=>{E=$,w()}),l.on("error",b),S.on("error",b)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(n,"");try{i(a)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new g("bundle-extract-failed",s.message)}}async function ce(e){let t=v(e,"graph.mjs");if(!x(t))throw new g("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(te(t).href)}catch(a){throw new g("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=n.default||Object.values(n).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new g("entry-class-missing","no buildGraph() class export found");return r}async function Y(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=A(),r;try{r=se()}catch(c){throw c}h.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let a=await ae({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:o,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:y,workflowVersion:b,workflowUuid:l,bundleReady:S,nodeConfigs:p}=a,E=ne();if(s&&s!==E)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${E} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new g("runtime-mismatch",`${E} vs ${s}`);if(!S||!i)throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new g("no-bundle","workflow bundle not built yet");let w=J(e);if(!w){let c=v(P,`${l}@${b||"0"}`);try{await ie(i,c);try{de()}catch{}}catch(d){throw d.fallback&&await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:d.message,code:d.reason}}}),d}try{w=await ce(c),H(e,w,{workflowUuid:l,version:b,runtimeTag:s,cacheDir:c})}catch(d){throw G(e,d),await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:d.message,code:d.reason||"IMPORT_FAILED"}}}),d.fallback?d:new g("import-failed",d.message)}}let $=Date.now(),C=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,m=p&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,B={...t.input||{},...m?{nodeConfigs:p}:{}},I,u;try{I=await oe(C,async()=>{let d=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return j({executionId:o,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>d.run(t.parentAgent,B,{signal:t.signal}))}),u=I&&typeof I=="object"&&"state"in I?I.state:I}catch(c){throw await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-$}}),c}if(I&&typeof I=="object"&&I.stoppedExternally){await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"canceled",finalState:u,durationMs:Date.now()-$}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await _({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:o,status:"completed",finalState:u,durationMs:Date.now()-$}}),{finalState:u,executionId:o}}function ue(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),a;try{a=N(r)}catch{continue}if(a.isDirectory()){let o;try{o=X(r)}catch{continue}for(let s of o)n.push(v(r,s))}else t+=a.size}return t}function de({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!x(P))return{evicted:0,freedBytes:0};let t=X(P),n=[],r=0;for(let i of t){let y=v(P,i),b;try{b=N(y)}catch{continue}let l=b.isDirectory()?ue(y):b.size;r+=l,n.push({name:i,full:y,size:l,mtimeMs:b.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,y)=>i.mtimeMs-y.mtimeMs);let a=Math.floor(e*.7),o=0,s=0;for(let i of n){if(r-o<=a)break;if(!x(v(i.full,".lock")))try{ee(i.full,{recursive:!0,force:!0}),o+=i.size,s+=1}catch(y){h.debug(`[sub-graph cache] evict skip ${i.name}: ${y.message}`)}}return s>0&&h.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:o,totalBytes:r-o}}catch(t){return h.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var pe=2e3,le=600*1e3,he=new Set(["completed","failed","canceled","timeout"]);function fe(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function ge(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function ye(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function be(){return process.env.EXECUTION_ID||null}function V(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}async function Ce(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=A(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{h.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await Y(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),c=V(u,t.output);return h.info(`[sub-graph] '${e}' completed in-process`),c}catch(u){if(u instanceof g||u?.fallback)h.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let a=fe(),o=ge(),s=ye(),i=be(),y=`${a}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(e)}/trigger`,b={input:t.input||{},...i?{parentExecutionId:i}:{},...t.conversationId?{conversationId:t.conversationId}:{}};h.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${i||"<none>"}`);let l=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(b)});if(!l.ok){let u=null,c="";try{u=await l.json(),c=u?.error||u?.message||JSON.stringify(u)}catch{c=await l.text().catch(()=>"")}if(l.status===429){let f=u?.quotaInfo||{},T=new Error(`Sub-graph '${e}' blocked by execution quota (${f.used??"?"}/${f.limit??"?"} on plan ${f.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw T.code="SUBGRAPH_QUOTA_EXCEEDED",T.status=429,T.subgraph=e,T.quotaInfo=f,T}if(l.status===400){let f=new Error(`Sub-graph '${e}' rejected input: ${c}`);throw f.code="SUBGRAPH_INVALID_INPUT",f.status=400,f.subgraph=e,f.validationErrors=u?.validationErrors||null,f.missing=u?.missing||null,f}let d=new Error(`Sub-graph '${e}' trigger rejected (${l.status}): ${c}`);throw d.code="SUBGRAPH_TRIGGER_FAILED",d.status=l.status,d.subgraph=e,d}let S=await l.json(),p=S?.data?.jobId||S?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(S).slice(0,200)}`);if(t.async)return h.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let E=Number.isFinite(t.timeoutMs)?t.timeoutMs:le,w=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:pe,$=`${a}/executions/${encodeURIComponent(p)}`,C=Date.now()+E,m="accepted",B=0;for(;Date.now()<C;){await new Promise(f=>setTimeout(f,w)),B+=1;let u=await fetch($,{headers:{Authorization:`Bearer ${s}`}});if(!u.ok){if(u.status>=500){h.warn(`[sub-graph] status poll for ${p} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${u.status}`)}let c=await u.json(),d=c?.data||c?.execution||c;if(m=d?.status||m,he.has(m)){if(m!=="completed"){let O=new Error(`Sub-graph '${e}' (${p}) ended in status '${m}'`);throw O.subgraphJobId=p,O.subgraphStatus=m,O}let f=d?.finalState||d?.state||{},T=V(f,t.output);return h.info(`[sub-graph] '${e}' (${p}) completed after ${B} polls`),T}}let I=new Error(`Sub-graph '${e}' (${p}) timed out after ${Math.round(E/1e3)}s (last status: ${m})`);throw I.subgraphJobId=p,I.subgraphStatus=m,I}export{Ce as dispatchSubgraph};
|