@zibby/agent-workflow 0.4.38 → 0.4.39

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/constants.js CHANGED
@@ -1 +1 @@
1
- var o=".zibby/output",t="sessions",_=".session-info.json",s=".zibby-stop",e="result.json",I="raw_stream_output.txt",E="events.json",n=Object.freeze(["codebase-memory","code-scan"]),S=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{S as CI_ENV_VARS,o as DEFAULT_OUTPUT_BASE,E as EVENTS_FILE,n as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,I as RAW_OUTPUT_FILE,e as RESULT_FILE,t as SESSIONS_DIR,_ as SESSION_INFO_FILE,s as STOP_REQUEST_FILE};
1
+ var t=".zibby/output",o="sessions",_=".session-info.json",s=".zibby-stop",e="result.json",I="raw_stream_output.txt",E="events.json",n=Object.freeze(["codebase-memory","code-scan","artifact"]),r=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{r as CI_ENV_VARS,t as DEFAULT_OUTPUT_BASE,E as EVENTS_FILE,n as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,I as RAW_OUTPUT_FILE,e as RESULT_FILE,o as SESSIONS_DIR,_ as SESSION_INFO_FILE,s as STOP_REQUEST_FILE};
@@ -29,7 +29,7 @@ ${Ke}`,e.col=Ve))}return o(n,r,s)}}var Ee=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ze,e):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${e}
30
30
  `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(qe,t):process.stdout.write.bind(process.stdout)(`${X} ${qe} ${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(`${Jt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let n of s)this._rawWrite(`${be} ${n}`);let i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var zo=Object.freeze(["codebase-memory","code-scan"]),ot=["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 le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Jt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let n of s)this._rawWrite(`${be} ${n}`);let i=r?x.dim(` ${Xe(r)}`):"";this._rawWrite(`${ze} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Xe(s)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${ze} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var de=".zibby/output",et="sessions",K=".session-info.json",tt=".zibby-stop";var zo=Object.freeze(["codebase-memory","code-scan","artifact"]),ot=["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 le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return b.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){b.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(b.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return b.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&b.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
33
33
 
34
34
  ${i}`);let a=r(),u=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let l=Ae(d,K);if(ct(l)){let y=JSON.parse(at(l,"utf-8"));y.currentNode=this.name,ke(l,JSON.stringify(y,null,2),"utf-8")}let c=Ae(d,"..",K);if(ct(c))try{let y=JSON.parse(at(c,"utf-8"));y.currentNode=this.name,ke(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(l){b.debug(`[workflow] could not update session info: ${l.message}`)}let f=null;for(let l=0;l<=this.retries;l++)try{b.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},y=c.agents||{},g=this.config.agent??y[this.name]??null,m={state:r()};g&&(m.preferredAgent=g);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},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(oe(),te))).invokeAgent);let h=await I(i,m,v),S,w;if(typeof h=="string"?(S=h,w=null):h.structured?(S=h.raw||JSON.stringify(h.structured,null,2),w=h.structured):(S=h.raw||JSON.stringify(h,null,2),w=h.extracted||null),d)try{let p=Ae(d,this.name,"raw_stream_output.txt");to(oo(p),{recursive:!0}),ke(p,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(p){b.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){b.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),w)}catch($){b.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:S}),raw:S}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(S);return b.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:S}}return{success:!0,output:S,raw:S}}catch(c){f=c,l<this.retries&&b.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as so,existsSync as Y,statSync as yt,readdirSync as St,rmSync as io}from"node:fs";import{spawn as ht}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as ao}from"node:url";import{AsyncLocalStorage as co}from"node:async_hooks";import{AsyncLocalStorage as ro}from"node:async_hooks";var xe=new ro;function re(){let o=xe.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 lt(o,e){let t=xe.getStore()||re(),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 xe.run(r,e)}var Oe=new Map,Pe=new Map,ut=new Map;function dt(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");Oe.set(o,e),Pe.set(o,"ready"),ut.set(o,{...t,cachedAt:Date.now()})}function pt(o,e){Pe.set(o,"failed"),ut.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Oe.delete(o)}function ft(o){return Pe.get(o)==="ready"?Oe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function lo(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},gt=new co,mt=Promise.resolve();async function uo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=gt.getStore()===!0,s=null;if(!r){let n=mt;mt=new Promise(a=>{s=a}),await n}let i=new Map;try{for(let[n,a]of t)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return b.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await gt.run(!0,e)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;s&&s()}}function po(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function fo({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(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 '${t.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 J({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||b.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){b.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ho(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;so(e,{recursive:!0});let s=U(e,".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(Y(t)&&Y(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,d)=>{let f=ht("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=ht("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(l.stdin);let c,y,g=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(y!==0)return d(new Error(`tar exited ${y}`));u()}};f.on("close",m=>{c=m,g()}),l.on("close",m=>{y=m,g()}),f.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");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 go(o){let e=U(o,"graph.mjs");if(!Y(e))throw new P("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(ao(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).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 wt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=po()}catch(p){throw p}b.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await fo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:f,bundleReady:l,nodeConfigs:c}=s,y=lo();if(n&&n!==y)throw await J({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(!l||!a)throw await J({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 g=ft(o);if(!g){let p=U(fe,`${f}@${d||"0"}`);try{await ho(a,p);try{yo()}catch{}}catch($){throw $.fallback&&await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await go(p),dt(o,g,{workflowUuid:f,version:d,runtimeTag:n,cacheDir:p})}catch($){throw pt(o,$),await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new P("import-failed",$.message)}}let m=Date.now(),v=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},S,w;try{S=await uo(v,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return lt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,h,{signal:e.signal}))}),w=S&&typeof S=="object"&&"state"in S?S.state:S}catch(p){throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),p}if(S&&typeof S=="object"&&S.stoppedExternally){await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:w,durationMs:Date.now()-m}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=i,p}return await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:w,durationMs:Date.now()-m}}),{finalState:w,executionId:i}}function mo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=yt(r)}catch{continue}if(s.isDirectory()){let i;try{i=St(r)}catch{continue}for(let n of i)t.push(U(r,n))}else e+=s.size}return e}function yo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(fe))return{evicted:0,freedBytes:0};let e=St(fe),t=[],r=0;for(let a of e){let u=U(fe,a),d;try{d=yt(u)}catch{continue}let f=d.isDirectory()?mo(u):d.size;r+=f,t.push({name:a,full:u,size:f,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(o*.7),i=0,n=0;for(let a of t){if(r-i<=s)break;if(!Y(U(a.full,".lock")))try{io(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){b.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&b.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(e){return b.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var So=2e3,wo=600*1e3,_o=new Set(["completed","failed","canceled","timeout"]);function bo(){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 Io(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Eo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function $o(){return process.env.EXECUTION_ID||null}function _t(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 bt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re(),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{b.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:w}=await wt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=_t(w,e.output);return b.info(`[sub-graph] '${o}' completed in-process`),p}catch(w){if(w instanceof P||w?.fallback)b.info(`[sub-graph] in-process fallback for '${o}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let s=bo(),i=Io(),n=Eo(),a=$o(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};b.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!f.ok){let w=null,p="";try{w=await f.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=w?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=w?.validationErrors||null,k.missing=w?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let l=await f.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 b.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:wo,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:So,m=`${s}/executions/${encodeURIComponent(c)}`,v=Date.now()+y,I="accepted",h=0;for(;Date.now()<v;){await new Promise(k=>setTimeout(k,g)),h+=1;let w=await fetch(m,{headers:{Authorization:`Bearer ${n}`}});if(!w.ok){if(w.status>=500){b.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),$=p?.data||p?.execution||p;if(I=$?.status||I,_o.has(I)){if(I!=="completed"){let _=new Error(`Sub-graph '${o}' (${c}) ended in status '${I}'`);throw _.subgraphJobId=c,_.subgraphStatus=I,_}let k=$?.finalState||$?.state||{},M=_t(k,e.output);return b.info(`[sub-graph] '${o}' (${c}) completed after ${h} polls`),M}}let S=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${I})`);throw S.subgraphJobId=c,S.subgraphStatus=I,S}import{existsSync as It,readFileSync as vo}from"node:fs";import{join as Ne,dirname as Et}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Et(Ne(t,e));for(let u of i){let d=await this.findAndMergeContextFiles(u,a,t);if(d){let f=u.replace(/\.[^.]+$/,"").toLowerCase();s[f]=d}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let d=Ne(t,u);It(d)&&(s[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${u}': ${d.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let n=Ne(i,e);if(It(n))try{s.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let a=Et(i);if(a===i)break;i=a}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
35
35
 
package/dist/graph.js CHANGED
@@ -29,7 +29,7 @@ ${Gt}`,t.col=Ht))}return s(n,r,o)}}var gt=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Wt,t):process.stdout.write.bind(process.stdout)(`${K} ${Wt} ${t}
30
30
  `)}stepMemory(t){let e=x.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ft,e):process.stdout.write.bind(process.stdout)(`${K} ${Ft} ${e}
31
31
  `)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,x.red(t)):process.stdout.write.bind(process.stdout)(`${K} ${ht} ${x.red(t)}
32
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:o}=e;if(o)for(let n of o)this._rawWrite(`${ft} ${n}`);let i=r?x.dim(` ${Jt(r)}`):"";this._rawWrite(`${Ut} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:o}=r,i=o?x.dim(` ${Jt(o)}`):"";this._rawWrite(`${ht} ${x.red(e)}`),this._rawWrite(`${Ut} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(x.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},O=new gt;var at=".zibby/output",Zt="sessions",z=".session-info.json",zt=".zibby-stop";var Pr=Object.freeze(["codebase-memory","code-scan"]),qt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",s=>Number(s)+1);F.helpers.json||F.registerHelper("json",s=>JSON.stringify(s,null,2));F.helpers.eq||F.registerHelper("eq",(s,t)=>s===t);var D=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return I.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=o("_skillHints");n&&(i=`${n}
32
+ `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Ce} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:r,details:o}=e;if(o)for(let n of o)this._rawWrite(`${ft} ${n}`);let i=r?x.dim(` ${Jt(r)}`):"";this._rawWrite(`${Ut} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,r={}){this._stopIntercepting();let{duration:o}=r,i=o?x.dim(` ${Jt(o)}`):"";this._rawWrite(`${ht} ${x.red(e)}`),this._rawWrite(`${Ut} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(x.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},O=new gt;var at=".zibby/output",Zt="sessions",z=".session-info.json",zt=".zibby-stop";var Pr=Object.freeze(["codebase-memory","code-scan","artifact"]),qt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",s=>Number(s)+1);F.helpers.json||F.registerHelper("json",s=>JSON.stringify(s,null,2));F.helpers.eq||F.registerHelper("eq",(s,t)=>s===t);var D=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>e&&typeof e.getAll=="function"?e.getAll():t,o=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return I.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(r())):i=this.prompt;let n=o("_skillHints");n&&(i=`${n}
33
33
 
34
34
  ${i}`);let a=r(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=$t(p,z);if(ee(c)){let y=JSON.parse(te(c,"utf-8"));y.currentNode=this.name,Et(c,JSON.stringify(y,null,2),"utf-8")}let l=$t(p,"..",z);if(ee(l))try{let y=JSON.parse(te(l,"utf-8"));y.currentNode=this.name,Et(l,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(c){I.debug(`[workflow] could not update session info: ${c.message}`)}let h=null;for(let c=0;c<=this.retries;c++)try{I.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=r().config||{},y=l.agents||{},S=this.config.agent??y[this.name]??null,w={state:r()};S&&(w.preferredAgent=S);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(bt(),It))).invokeAgent);let f=await $(i,w,T),g,m;if(typeof f=="string"?(g=f,m=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),m=f.structured):(g=f.raw||JSON.stringify(f,null,2),m=f.extracted||null),p)try{let d=$t(p,this.name,"raw_stream_output.txt");Je(Ye(d),{recursive:!0}),Et(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let d=m;if(typeof this.onComplete=="function")try{d=await this.onComplete(r(),m)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){h=l,c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};V();V();import{mkdirSync as qe,existsSync as H,statSync as ue,readdirSync as pe,rmSync as Ve}from"node:fs";import{spawn as ae}from"node:child_process";import{join as L}from"node:path";import{pathToFileURL as Ke}from"node:url";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{AsyncLocalStorage as Ze}from"node:async_hooks";var vt=new Ze;function Q(){let s=vt.getStore();return s||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function re(s,t){let e=vt.getStore()||Q(),r=Object.freeze({executionId:s.executionId,parentExecutionId:s.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(s.executionId!==e.executionId?1:0),conversationId:s.conversationId!==void 0?s.conversationId:e.conversationId??null,dispatchMode:s.dispatchMode??null});return vt.run(r,t)}var Tt=new Map,At=new Map,se=new Map;function oe(s,t,e={}){if(!s||typeof s!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(s,t),At.set(s,"ready"),se.set(s,{...e,cachedAt:Date.now()})}function ne(s,t){At.set(s,"failed"),se.set(s,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(s)}function ie(s){return At.get(s)==="ready"?Tt.get(s):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Qe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}},ce=new Xe,le=Promise.resolve();async function tr(s,t){let e=s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(e.length===0)return t();let r=ce.getStore()===!0,o=null;if(!r){let n=le;le=new Promise(a=>{o=a}),await n}let i=new Map;try{for(let[n,a]of e)i.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return I.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${r?" (nested)":""}`),await ce.run(!0,t)}finally{for(let[n,a]of i)a===void 0?delete process.env[n]:process.env[n]=a;o&&o()}}function er(){let s=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=s||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!e||!r||!o)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:r,authToken:o}}async function rr({apiBase:s,authToken:t,body:e}){let r;try{r=await fetch(`${s}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let o=null;try{o=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=o?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(r.status===400&&o?.validationErrors){let i=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=o.validationErrors,i.missing=o.missing,i}throw new P("begin-status",`begin returned ${r.status}`)}return o?.data||o}async function G({apiBase:s,authToken:t,payload:e}){try{let r=await fetch(`${s}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${e.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function sr(s,t){let e=L(t,".ready"),r=L(t,"graph.mjs");if(H(e)&&H(r))return;qe(t,{recursive:!0});let o=L(t,".lock"),i=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),u=n(o,"wx");a(u),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(H(e)&&H(r))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let h=ae("curl",["-fsSL",s],{stdio:["ignore","pipe","inherit"]}),c=ae("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(c.stdin);let l,y,S=()=>{if(l!==void 0&&y!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(y!==0)return p(new Error(`tar exited ${y}`));u()}};h.on("close",w=>{l=w,S()}),c.on("close",w=>{y=w,S()}),h.on("error",p),c.on("error",p)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(e,"");try{a(o)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new P("bundle-extract-failed",n.message)}}async function or(s){let t=L(s,"graph.mjs");if(!H(t))throw new P("entry-missing",`graph.mjs missing under ${s}`);let e;try{e=await import(Ke(t).href)}catch(o){throw new P("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=e.default||Object.values(e).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function de(s,t={}){if(!s||typeof s!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),r;try{r=er()}catch(d){throw d}I.debug(`[in-process subgraph] begin '${s}' parent=${e.executionId||"<root>"}`);let o=await rr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:s,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:h,bundleReady:c,nodeConfigs:l}=o,y=Qe();if(n&&n!==y)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${y} vs ${n}`);if(!c||!a)throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let S=ie(s);if(!S){let d=L(ct,`${h}@${p||"0"}`);try{await sr(a,d);try{ir()}catch{}}catch(E){throw E.fallback&&await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{S=await or(d),oe(s,S,{workflowUuid:h,version:p,runtimeTag:n,cacheDir:d})}catch(E){throw ne(s,E),await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new P("import-failed",E.message)}}let w=Date.now(),T=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...t.input||{},...$?{nodeConfigs:l}:{}},g,m;try{g=await tr(T,async()=>{let E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return re({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,f,{signal:t.signal}))}),m=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-w}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-w}});let d=new Error(`Sub-graph '${s}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await G({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function nr(s){let t=0,e=[s];for(;e.length;){let r=e.pop(),o;try{o=ue(r)}catch{continue}if(o.isDirectory()){let i;try{i=pe(r)}catch{continue}for(let n of i)e.push(L(r,n))}else t+=o.size}return t}function ir({cap:s=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!H(ct))return{evicted:0,freedBytes:0};let t=pe(ct),e=[],r=0;for(let a of t){let u=L(ct,a),p;try{p=ue(u)}catch{continue}let h=p.isDirectory()?nr(u):p.size;r+=h,e.push({name:a,full:u,size:h,mtimeMs:p.mtimeMs})}if(r<=s)return{evicted:0,freedBytes:0,totalBytes:r};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let o=Math.floor(s*.7),i=0,n=0;for(let a of e){if(r-i<=o)break;if(!H(L(a.full,".lock")))try{Ve(a.full,{recursive:!0,force:!0}),i+=a.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:r-i}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var ar=2e3,cr=600*1e3,lr=new Set(["completed","failed","canceled","timeout"]);function ur(){let s=process.env.PROGRESS_API_URL;if(!s)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return s.replace(/\/executions\/?$/,"")}function pr(){let s=process.env.PROJECT_ID;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return s}function dr(){let s=process.env.PROJECT_API_TOKEN;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return s}function fr(){return process.env.EXECUTION_ID||null}function fe(s,t){return t==null?s:typeof t=="function"?t(s):typeof t=="string"?t.split(".").reduce((e,r)=>e==null?e:e[r],s):s}async function he(s,t={}){if(!s||typeof s!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=r)throw new Error(`dispatchSubgraph('${s}'): sub-graph depth ${e.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{I.debug(`[sub-graph] trying in-process for '${s}'`);let{finalState:m}=await de(s,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=fe(m,t.output);return I.info(`[sub-graph] '${s}' completed in-process`),d}catch(m){if(m instanceof P||m?.fallback)I.info(`[sub-graph] in-process fallback for '${s}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let o=ur(),i=pr(),n=dr(),a=fr(),u=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(s)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${s}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(p)});if(!h.ok){let m=null,d="";try{m=await h.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await h.text().catch(()=>"")}if(h.status===429){let A=m?.quotaInfo||{},M=new Error(`Sub-graph '${s}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=s,M.quotaInfo=A,M}if(h.status===400){let A=new Error(`Sub-graph '${s}' rejected input: ${d}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=s,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let E=new Error(`Sub-graph '${s}' trigger rejected (${h.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=s,E}let c=await h.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${s}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${s}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:s};let y=Number.isFinite(t.timeoutMs)?t.timeoutMs:cr,S=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:ar,w=`${o}/executions/${encodeURIComponent(l)}`,T=Date.now()+y,$="accepted",f=0;for(;Date.now()<T;){await new Promise(A=>setTimeout(A,S)),f+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${n}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${l} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${m.status}`)}let d=await m.json(),E=d?.data||d?.execution||d;if($=E?.status||$,lr.has($)){if($!=="completed"){let _=new Error(`Sub-graph '${s}' (${l}) ended in status '${$}'`);throw _.subgraphJobId=l,_.subgraphStatus=$,_}let A=E?.finalState||E?.state||{},M=fe(A,t.output);return I.info(`[sub-graph] '${s}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${s}' (${l}) timed out after ${Math.round(y/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as ge,readFileSync as hr}from"node:fs";import{join as kt,dirname as me}from"node:path";var lt=class{static async loadContext(t,e,r={}){let o={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=me(kt(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let h=u.replace(/\.[^.]+$/,"").toLowerCase();o[h]=p}}}let n=r.discovery||{};for(let[a,u]of Object.entries(n))try{let p=kt(e,u);ge(p)&&(o[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return o}static async findAndMergeContextFiles(t,e,r){let o=[],i=e;for(;i.startsWith(r);){let n=kt(i,t);if(ge(n))try{o.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${t} from ${n}: ${u.message}`)}let a=me(i);if(a===i)break;i=a}return o.length===0?null:o.every(n=>typeof n=="string")?o.join(`
35
35
 
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ ${dt}`,e.col=ut))}return o(n,r,i)}}var me=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${ne} ${ct} ${e}
30
30
  `)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${ne} ${lt} ${t}
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(Te,N.red(e)):process.stdout.write.bind(process.stdout)(`${ne} ${Te} ${N.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:i}=t;if(i)for(let n of i)this._rawWrite(`${$e} ${n}`);let s=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:i}=r,s=i?N.dim(` ${pt(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${at} ${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 me;var se=".zibby/output",ke="sessions",W=".session-info.json",Ae=".zibby-stop",mo="result.json",yo="raw_stream_output.txt",wo="events.json",So=Object.freeze(["codebase-memory","code-scan"]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var 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 r=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return E.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=i("_skillHints");n&&(s=`${n}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:i}=t;if(i)for(let n of i)this._rawWrite(`${$e} ${n}`);let s=r?N.dim(` ${pt(r)}`):"";this._rawWrite(`${at} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:i}=r,s=i?N.dim(` ${pt(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${at} ${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 me;var se=".zibby/output",ke="sessions",W=".session-info.json",Ae=".zibby-stop",mo="result.json",yo="raw_stream_output.txt",wo="events.json",So=Object.freeze(["codebase-memory","code-scan","artifact"]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var 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 r=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return E.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=i("_skillHints");n&&(s=`${n}
33
33
 
34
34
  ${s}`);let a=r(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Me(u,W);if(kt(d)){let y=JSON.parse(Tt(d,"utf-8"));y.currentNode=this.name,Be(d,JSON.stringify(y,null,2),"utf-8")}let c=Me(u,"..",W);if(kt(c))try{let y=JSON.parse(Tt(c,"utf-8"));y.currentNode=this.name,Be(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(d){E.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{E.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=r().config||{},y=c.agents||{},h=this.config.agent??y[this.name]??null,g={state:r()};h&&(g.preferredAgent=h);let I={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let m=await _(s,g,I),w,S;if(typeof m=="string"?(w=m,S=null):m.structured?(w=m.raw||JSON.stringify(m.structured,null,2),S=m.structured):(w=m.raw||JSON.stringify(m,null,2),S=m.extracted||null),u)try{let p=Me(u,this.name,"raw_stream_output.txt");_o(bo(p),{recursive:!0}),Be(p,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),S)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(w);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:w}}return{success:!0,output:w,raw:w}}catch(c){f=c,d<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as vo,existsSync as Y,statSync as Bt,readdirSync as Mt,rmSync as $o}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as To}from"node:url";import{AsyncLocalStorage as ko}from"node:async_hooks";import{AsyncLocalStorage as Eo}from"node:async_hooks";var De=new Eo;function le(){let o=De.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 At(o,e){let t=De.getStore()||le(),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 De.run(r,e)}var Le=new Map,Fe=new Map,xt=new Map;function Nt(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");Le.set(o,e),Fe.set(o,"ready"),xt.set(o,{...t,cachedAt:Date.now()})}function Ot(o,e){Fe.set(o,"failed"),xt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(o)}function Pt(o){return Fe.get(o)==="ready"?Le.get(o):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ao(){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"}},Rt=new ko,jt=Promise.resolve();async function xo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=Rt.getStore()===!0,i=null;if(!r){let n=jt;jt=new Promise(a=>{i=a}),await n}let s=new Map;try{for(let[n,a]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[n,a]of s)a===void 0?delete process.env[n]:process.env[n]=a;i&&i()}}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,i=process.env.PROJECT_API_TOKEN;if(!t||!r||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:i}}async function Oo({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 O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=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=i?.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&&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 ${r.status}`)}return i?.data||i}async function z({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||E.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){E.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function Po(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;vo(e,{recursive:!0});let i=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),l=n(i,"wx");a(l),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))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,u)=>{let f=Ct("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,y,h=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};f.on("close",g=>{c=g,h()}),d.on("close",g=>{y=g,h()}),f.on("error",u),d.on("error",u)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(i)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",n.message)}}async function Co(o){let e=U(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(To(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let r=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function Dt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),r;try{r=No()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await Oo({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:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=i,y=Ao();if(n&&n!==y)throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${n}`);if(!d||!a)throw await z({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 O("no-bundle","workflow bundle not built yet");let h=Pt(o);if(!h){let p=U(ye,`${f}@${u||"0"}`);try{await Po(a,p);try{jo()}catch{}}catch($){throw $.fallback&&await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await Co(p),Nt(o,h,{workflowUuid:f,version:u,runtimeTag:n,cacheDir:p})}catch($){throw Ot(o,$),await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let g=Date.now(),I=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}:{}},w,S;try{w=await xo(I,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return At({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),S=w&&typeof w=="object"&&"state"in w?w.state:w}catch(p){throw await z({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()-g}}),p}if(w&&typeof w=="object"&&w.stoppedExternally){await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:S,durationMs:Date.now()-g}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:S,durationMs:Date.now()-g}}),{finalState:S,executionId:s}}function Ro(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),i;try{i=Bt(r)}catch{continue}if(i.isDirectory()){let s;try{s=Mt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=i.size}return e}function jo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Mt(ye),t=[],r=0;for(let a of e){let l=U(ye,a),u;try{u=Bt(l)}catch{continue}let f=u.isDirectory()?Ro(l):u.size;r+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,n=0;for(let a of t){if(r-s<=i)break;if(!Y(U(a.full,".lock")))try{$o(a.full,{recursive:!0,force:!0}),s+=a.size,n+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return n>0&&E.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 E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bo=2e3,Mo=600*1e3,Do=new Set(["completed","failed","canceled","timeout"]);function Lo(){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 Fo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Uo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Wo(){return process.env.EXECUTION_ID||null}function Lt(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 Ue(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le(),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{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await Dt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Lt(S,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof O||S?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let i=Lo(),s=Fo(),n=Uo(),a=Wo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,u={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 ${n}`},body:JSON.stringify(u)});if(!f.ok){let S=null,p="";try{S=await f.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=S?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=S?.validationErrors||null,k.missing=S?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:Mo,h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bo,g=`${i}/executions/${encodeURIComponent(c)}`,I=Date.now()+y,_="accepted",m=0;for(;Date.now()<I;){await new Promise(k=>setTimeout(k,h)),m+=1;let S=await fetch(g,{headers:{Authorization:`Bearer ${n}`}});if(!S.ok){if(S.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Do.has(_)){if(_!=="completed"){let b=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw b.subgraphJobId=c,b.subgraphStatus=_,b}let k=$?.finalState||$?.state||{},M=Lt(k,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),M}}let w=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${_})`);throw w.subgraphJobId=c,w.subgraphStatus=_,w}import{existsSync as Ft,readFileSync as Go}from"node:fs";import{join as We,dirname as Ut}from"node:path";var de=class{static async loadContext(e,t,r={}){let i={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ut(We(t,e));for(let l of s){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=u}}}let n=r.discovery||{};for(let[a,l]of Object.entries(n))try{let u=We(t,l);Ft(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,t,r){let i=[],s=t;for(;s.startsWith(r);){let n=We(s,e);if(Ft(n))try{i.unshift(await this.loadFile(n))}catch(l){console.warn(`[workflow] could not load ${e} from ${n}: ${l.message}`)}let a=Ut(s);if(a===s)break;s=a}return i.length===0?null:i.every(n=>typeof n=="string")?i.join(`
35
35
 
package/dist/node.js CHANGED
@@ -29,6 +29,6 @@ ${U}`,t.col=B))}return r(a,o,n)}}var R=class{constructor(){this._currentNode=nul
29
29
  `)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(H,t):process.stdout.write.bind(process.stdout)(`${k} ${H} ${t}
30
30
  `)}stepMemory(t){let e=d.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(J,e):process.stdout.write.bind(process.stdout)(`${k} ${J} ${e}
31
31
  `)}stepFail(t){this._origStdoutWrite?this._writeDot(x,d.red(t)):process.stdout.write.bind(process.stdout)(`${k} ${x} ${d.red(t)}
32
- `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${ut} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:n}=e;if(n)for(let a of n)this._rawWrite(`${v} ${a}`);let s=o?d.dim(` ${K(o)}`):"";this._rawWrite(`${G} ${d.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:n}=o,s=n?d.dim(` ${K(n)}`):"";this._rawWrite(`${x} ${d.red(e)}`),this._rawWrite(`${G} ${d.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(d.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},Z=new R;var L=".session-info.json";var Et=Object.freeze(["codebase-memory","code-scan"]);$.helpers.inc||$.registerHelper("inc",r=>Number(r)+1);$.helpers.json||$.registerHelper("json",r=>JSON.stringify(r,null,2));$.helpers.eq||$.registerHelper("eq",(r,t)=>r===t);var it=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 T(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 p.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,n=i=>e&&typeof e.get=="function"?e.get(i):t?.[i];if(typeof this.customExecute=="function"){p.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let i=await this.customExecute(t);return typeof i=="object"&&i!==null&&i.success===!1?{success:!1,error:i.error||"Node execution failed",raw:i.raw||null}:this.isZodSchema?(p.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(i),raw:null}):{success:!0,output:i,raw:null}}catch(i){return p.error(`[workflow] node '${this.name}' failed: ${i.message}`),i.name==="ZodError"&&p.error(`Schema errors: ${JSON.stringify(i.issues||i.errors,null,2)}`),{success:!1,error:i.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=$.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let a=n("_skillHints");a&&(s=`${a}
32
+ `)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${ut} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:n}=e;if(n)for(let a of n)this._rawWrite(`${v} ${a}`);let s=o?d.dim(` ${K(o)}`):"";this._rawWrite(`${G} ${d.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:n}=o,s=n?d.dim(` ${K(n)}`):"";this._rawWrite(`${x} ${d.red(e)}`),this._rawWrite(`${G} ${d.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(d.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},Z=new R;var L=".session-info.json";var Et=Object.freeze(["codebase-memory","code-scan","artifact"]);$.helpers.inc||$.registerHelper("inc",r=>Number(r)+1);$.helpers.json||$.registerHelper("json",r=>JSON.stringify(r,null,2));$.helpers.eq||$.registerHelper("eq",(r,t)=>r===t);var it=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 T(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 p.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,n=i=>e&&typeof e.get=="function"?e.get(i):t?.[i];if(typeof this.customExecute=="function"){p.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let i=await this.customExecute(t);return typeof i=="object"&&i!==null&&i.success===!1?{success:!1,error:i.error||"Node execution failed",raw:i.raw||null}:this.isZodSchema?(p.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(i),raw:null}):{success:!0,output:i,raw:null}}catch(i){return p.error(`[workflow] node '${this.name}' failed: ${i.message}`),i.name==="ZodError"&&p.error(`Schema errors: ${JSON.stringify(i.issues||i.errors,null,2)}`),{success:!1,error:i.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=$.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let a=n("_skillHints");a&&(s=`${a}
33
33
 
34
34
  ${s}`);let S=o(),u=S.cwd||process.cwd(),h=S.sessionPath;try{if(h){let i=j(h,L);if(ot(i)){let g=JSON.parse(rt(i,"utf-8"));g.currentNode=this.name,F(i,JSON.stringify(g,null,2),"utf-8")}let m=j(h,"..",L);if(ot(m))try{let g=JSON.parse(rt(m,"utf-8"));g.currentNode=this.name,F(m,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(i){p.debug(`[workflow] could not update session info: ${i.message}`)}let b=null;for(let i=0;i<=this.retries;i++)try{p.debug(`[workflow] node '${this.name}' attempt ${i}`);let m=o().config||{},g=m.agents||{},E=this.config.agent??g[this.name]??null,l={state:o()};E&&(l.preferredAgent=E);let I={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:h,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},O=t?._coreInvokeAgent;O||(O=(await Promise.resolve().then(()=>(et(),tt))).invokeAgent);let w=await O(s,l,I),f,_;if(typeof w=="string"?(f=w,_=null):w.structured?(f=w.raw||JSON.stringify(w.structured,null,2),_=w.structured):(f=w.raw||JSON.stringify(w,null,2),_=w.extracted||null),h)try{let c=j(h,this.name,"raw_stream_output.txt");mt(gt(c),{recursive:!0}),F(c,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(c){p.debug(`[workflow] could not save raw output: ${c.message}`)}if(this.isZodSchema&&_){p.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(_,null,2)}`);let c=_;if(typeof this.onComplete=="function")try{c=await this.onComplete(o(),_)}catch(st){p.warn(`[workflow] onComplete hook failed: ${st.message}`)}return{success:!0,output:c,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(c){throw new Error(`onComplete failed: ${c.message}`,{cause:c})}if(this.parser){let c=this.parser.parse(f);return p.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(c,null,2)}`),Z.step("Output parsed"),{success:!0,output:c,raw:f}}return{success:!0,output:f,raw:f}}catch(m){b=m,i<this.retries&&p.info(`[workflow] node '${this.name}' failed, retrying (${i+1}/${this.retries})\u2026`)}return{success:!1,error:b.message,raw:null}}};export{it as Node};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/agent-workflow",
3
- "version": "0.4.38",
3
+ "version": "0.4.39",
4
4
  "description": "Graph-based AI agent workflow orchestration. Bring your own agent strategies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",