@zibby/agent-workflow 0.4.24 → 0.4.25
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.d.ts +1 -0
- package/dist/constants.js +1 -1
- package/dist/graph-compiler.js +1 -1
- package/dist/graph.js +1 -1
- package/dist/index.js +7 -7
- package/dist/node.js +1 -1
- package/package.json +1 -1
package/dist/constants.d.ts
CHANGED
package/dist/constants.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=".zibby/output",t="sessions",E=".session-info.json",e=".zibby-stop",_="result.json",s="raw_stream_output.txt",r="events.json",o={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},O=Object.freeze([o.CODEBASE_MEMORY]),n=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{n as CI_ENV_VARS,I as DEFAULT_OUTPUT_BASE,r as EVENTS_FILE,O as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,s as RAW_OUTPUT_FILE,_ as RESULT_FILE,t as SESSIONS_DIR,E as SESSION_INFO_FILE,o as SKILLS,e as STOP_REQUEST_FILE};
|
|
1
|
+
var I=".zibby/output",t="sessions",E=".session-info.json",e=".zibby-stop",_="result.json",s="raw_stream_output.txt",r="events.json",o={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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},O=Object.freeze([o.CODEBASE_MEMORY]),n=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{n as CI_ENV_VARS,I as DEFAULT_OUTPUT_BASE,r as EVENTS_FILE,O as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,s as RAW_OUTPUT_FILE,_ as RESULT_FILE,t as SESSIONS_DIR,E as SESSION_INFO_FILE,o as SKILLS,e as STOP_REQUEST_FILE};
|
package/dist/graph-compiler.js
CHANGED
|
@@ -29,7 +29,7 @@ ${Ke}`,e.col=qe))}return o(a,r,s)}}var be=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=k.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(Ee,k.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ee} ${k.red(e)}
|
|
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:s}=t;if(s)for(let a of s)this._rawWrite(`${Ie} ${a}`);let n=r?k.dim(` ${Ve(r)}`):"";this._rawWrite(`${Ye} ${k.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?k.dim(` ${Ve(s)}`):"";this._rawWrite(`${Ee} ${k.red(t)}`),this._rawWrite(`${Ye} ${k.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(k.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new be;var de=".zibby/output",Qe="sessions",K=".session-info.json",et=".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",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Go=Object.freeze([Ft.CODEBASE_MEMORY]),tt=["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,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)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){let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);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 n;typeof this.prompt=="function"?n=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(r())):n=this.prompt;let a=s("_skillHints");a&&(n=`${a}
|
|
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:s}=t;if(s)for(let a of s)this._rawWrite(`${Ie} ${a}`);let n=r?k.dim(` ${Ve(r)}`):"";this._rawWrite(`${Ye} ${k.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?k.dim(` ${Ve(s)}`):"";this._rawWrite(`${Ee} ${k.red(t)}`),this._rawWrite(`${Ye} ${k.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(k.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new be;var de=".zibby/output",Qe="sessions",K=".session-info.json",et=".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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Go=Object.freeze([Ft.CODEBASE_MEMORY]),tt=["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,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)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){let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);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 n;typeof this.prompt=="function"?n=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(r())):n=this.prompt;let a=s("_skillHints");a&&(n=`${a}
|
|
33
33
|
|
|
34
34
|
${n}`);let i=r(),l=i.cwd||process.cwd(),u=i.sessionPath;try{if(u){let c=Ae(u,K);if(it(c)){let f=JSON.parse(st(c,"utf-8"));f.currentNode=this.name,ve(c,JSON.stringify(f,null,2),"utf-8")}let d=Ae(u,"..",K);if(it(d))try{let f=JSON.parse(st(d,"utf-8"));f.currentNode=this.name,ve(d,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let d=r().config||{},f=d.agents||{},I=this.config.agent??f[this.name]??null,w={state:r()};I&&(w.preferredAgent=I);let $={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let h=await E(n,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let S=Ae(u,this.name,"raw_stream_output.txt");Vt(Xt(S),{recursive:!0}),ve(S,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(S){_.debug(`[workflow] could not save raw output: ${S.message}`)}if(this.isZodSchema&&m){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let S=m;if(typeof this.onComplete=="function")try{S=await this.onComplete(r(),m)}catch(N){_.warn(`[workflow] onComplete hook failed: ${N.message}`)}return{success:!0,output:S,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(S){throw new Error(`onComplete failed: ${S.message}`,{cause:S})}if(this.parser){let S=this.parser.parse(g);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(S,null,2)}`),x.step("Output parsed"),{success:!0,output:S,raw:g}}return{success:!0,output:g,raw:g}}catch(d){p=d,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},oe=class extends L{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}};G();G();import{mkdirSync as to,existsSync as J,statSync as ft,readdirSync as ht,rmSync as oo}from"node:fs";import{spawn as pt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as ro}from"node:url";import{AsyncLocalStorage as Qt}from"node:async_hooks";var ke=new Qt;function re(){let o=ke.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=ke.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 ke.run(r,e)}var xe=new Map,Oe=new Map,ct=new Map;function lt(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");xe.set(o,e),Oe.set(o,"ready"),ct.set(o,{...t,cachedAt:Date.now()})}function ut(o,e){Oe.set(o,"failed"),ct.set(o,{error:e?.message||String(e),failedAt:Date.now()}),xe.delete(o)}function dt(o){return Oe.get(o)==="ready"?xe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function no(){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 so(){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 O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function io({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 O("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 '${t.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(r.status===429){let n=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=n,a}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 O("begin-status",`begin returned ${r.status}`)}return s?.data||s}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||_.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){_.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ao(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;to(e,{recursive:!0});let s=U(e,".lock"),n=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),l=a(s,"wx");i(l),n=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!n){let a=Date.now()+3e4;for(;Date.now()<a;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=pt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),c=pt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let d,f,I=()=>{if(d!==void 0&&f!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(f!==0)return u(new Error(`tar exited ${f}`));l()}};p.on("close",w=>{d=w,I()}),c.on("close",w=>{f=w,I()}),p.on("error",u),c.on("error",u)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(t,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new O("bundle-extract-failed",a.message)}}async function co(o){let e=U(o,"graph.mjs");if(!J(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(ro(e).href)}catch(s){throw new O("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 O("entry-class-missing","no buildGraph() class export found");return r}async function gt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=so()}catch(m){throw m}_.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await io({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:n,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,d=no();if(a&&a!==d)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${d} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${d} vs ${a}`);if(!c||!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 O("no-bundle","workflow bundle not built yet");let f=dt(o);if(!f){let m=U(fe,`${p}@${u||"0"}`);try{await ao(i,m);try{uo()}catch{}}catch(S){throw S.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{f=await co(m),lt(o,f,{workflowUuid:p,version:u,runtimeTag:a,cacheDir:m})}catch(S){throw ut(o,S),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new O("import-failed",S.message)}}let I=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await at({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-I}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-I}});let m=new Error(`Sub-graph '${o}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=n,m}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-I}}),{finalState:g,executionId:n}}function lo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=ft(r)}catch{continue}if(s.isDirectory()){let n;try{n=ht(r)}catch{continue}for(let a of n)t.push(U(r,a))}else e+=s.size}return e}function uo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(fe))return{evicted:0,freedBytes:0};let e=ht(fe),t=[],r=0;for(let i of e){let l=U(fe,i),u;try{u=ft(l)}catch{continue}let p=u.isDirectory()?lo(l):u.size;r+=p,t.push({name:i,full:l,size:p,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,l)=>i.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),n=0,a=0;for(let i of t){if(r-n<=s)break;if(!J(U(i.full,".lock")))try{oo(i.full,{recursive:!0,force:!0}),n+=i.size,a+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${i.name}: ${l.message}`)}}return a>0&&_.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:n,totalBytes:r-n}}catch(e){return _.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var po=2e3,fo=600*1e3,ho=new Set(["completed","failed","canceled","timeout"]);function go(){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 mo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function So(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function yo(){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,r)=>t==null?t:t[r],o):o}async function St(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{_.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:m}=await gt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),S=mt(m,e.output);return _.info(`[sub-graph] '${o}' completed in-process`),S}catch(m){if(m instanceof O||m?.fallback)_.info(`[sub-graph] in-process fallback for '${o}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let s=go(),n=mo(),a=So(),i=yo(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};_.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(u)});if(!p.ok){let m=null,S="";try{m=await p.json(),S=m?.error||m?.message||JSON.stringify(m)}catch{S=await p.text().catch(()=>"")}if(p.status===429){let v=m?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.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=v,R}if(p.status===400){let v=new Error(`Sub-graph '${o}' rejected input: ${S}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=o,v.validationErrors=m?.validationErrors||null,v.missing=m?.missing||null,v}let N=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${S}`);throw N.code="SUBGRAPH_TRIGGER_FAILED",N.status=p.status,N.subgraph=o,N}let c=await p.json(),d=c?.data?.jobId||c?.jobId;if(!d)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return _.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:o};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:fo,I=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:po,w=`${s}/executions/${encodeURIComponent(d)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(v=>setTimeout(v,I)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${a}`}});if(!m.ok){if(m.status>=500){_.warn(`[sub-graph] status poll for ${d} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${m.status}`)}let S=await m.json(),N=S?.data||S?.execution||S;if(E=N?.status||E,ho.has(E)){if(E!=="completed"){let y=new Error(`Sub-graph '${o}' (${d}) ended in status '${E}'`);throw y.subgraphJobId=d,y.subgraphStatus=E,y}let v=N?.finalState||N?.state||{},R=mt(v,e.output);return _.info(`[sub-graph] '${o}' (${d}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=d,g.subgraphStatus=E,g}import{existsSync as yt,readFileSync as wo}from"node:fs";import{join as Ne,dirname as wt}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=wt(Ne(t,e));for(let l of n){let u=await this.findAndMergeContextFiles(l,i,t);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let a=r.discovery||{};for(let[i,l]of Object.entries(a))try{let u=Ne(t,l);yt(u)&&(s[i]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${i}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],n=t;for(;n.startsWith(r);){let a=Ne(n,e);if(yt(a))try{s.unshift(await this.loadFile(a))}catch(l){console.warn(`[workflow] could not load ${e} from ${a}: ${l.message}`)}let i=wt(n);if(i===n)break;n=i}return s.length===0?null:s.every(a=>typeof a=="string")?s.join(`
|
|
35
35
|
|
package/dist/graph.js
CHANGED
|
@@ -29,7 +29,7 @@ ${Gt}`,t.col=Ft))}return r(i,o,s)}}var gt=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Ut,t):process.stdout.write.bind(process.stdout)(`${q} ${Ut} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Wt,e):process.stdout.write.bind(process.stdout)(`${q} ${Wt} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,O.red(t)):process.stdout.write.bind(process.stdout)(`${q} ${ht} ${O.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?O.dim(` ${Ht(o)}`):"";this._rawWrite(`${jt} ${O.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?O.dim(` ${Ht(s)}`):"";this._rawWrite(`${ht} ${O.red(e)}`),this._rawWrite(`${jt} ${O.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},k=new gt;var at=".zibby/output",Yt="sessions",Z=".session-info.json",Zt=".zibby-stop";var Ne={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Tr=Object.freeze([Ne.CODEBASE_MEMORY]),zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",r=>Number(r)+1);W.helpers.json||W.registerHelper("json",r=>JSON.stringify(r,null,2));W.helpers.eq||W.registerHelper("eq",(r,t)=>r===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)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){let o=()=>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 n;typeof this.prompt=="function"?n=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(o())):n=this.prompt;let i=s("_skillHints");i&&(n=`${i}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?O.dim(` ${Ht(o)}`):"";this._rawWrite(`${jt} ${O.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?O.dim(` ${Ht(s)}`):"";this._rawWrite(`${ht} ${O.red(e)}`),this._rawWrite(`${jt} ${O.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},k=new gt;var at=".zibby/output",Yt="sessions",Z=".session-info.json",Zt=".zibby-stop";var Ne={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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Tr=Object.freeze([Ne.CODEBASE_MEMORY]),zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",r=>Number(r)+1);W.helpers.json||W.registerHelper("json",r=>JSON.stringify(r,null,2));W.helpers.eq||W.registerHelper("eq",(r,t)=>r===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)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){let o=()=>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 n;typeof this.prompt=="function"?n=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(o())):n=this.prompt;let i=s("_skillHints");i&&(n=`${i}
|
|
33
33
|
|
|
34
34
|
${n}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let c=bt(u,Z);if(Qt(c)){let h=JSON.parse(Xt(c,"utf-8"));h.currentNode=this.name,Et(c,JSON.stringify(h,null,2),"utf-8")}let S=bt(u,"..",Z);if(Qt(S))try{let h=JSON.parse(Xt(S,"utf-8"));h.currentNode=this.name,Et(S,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let S=o().config||{},h=S.agents||{},b=this.config.agent??h[this.name]??null,E={state:o()};b&&(E.preferredAgent=b);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let d=await I(n,E,A),f,g;if(typeof d=="string"?(f=d,g=null):d.structured?(f=d.raw||JSON.stringify(d.structured,null,2),g=d.structured):(f=d.raw||JSON.stringify(d,null,2),g=d.extracted||null),u)try{let m=bt(u,this.name,"raw_stream_output.txt");We(Ge(m),{recursive:!0}),Et(m,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let m=g;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),g)}catch(P){_.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:m,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(f);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:f}}return{success:!0,output:f,raw:f}}catch(S){p=S,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},X=class extends L{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};V();V();import{mkdirSync as Je,existsSync as F,statSync as ie,readdirSync as ae,rmSync as Ye}from"node:fs";import{spawn as ne}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ze}from"node:url";import{AsyncLocalStorage as Fe}from"node:async_hooks";var $t=new Fe;function Q(){let r=$t.getStore();return r||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function te(r,t){let e=$t.getStore()||Q(),o=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return $t.run(o,t)}var Tt=new Map,At=new Map,ee=new Map;function re(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),At.set(r,"ready"),ee.set(r,{...e,cachedAt:Date.now()})}function oe(r,t){At.set(r,"failed"),ee.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function se(r){return At.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var x=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 Ke(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!o||!s)throw new x("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Ve({apiBase:r,authToken:t,body:e}){let o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new x("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.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(o.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(o.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 x("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function G({apiBase:r,authToken:t,payload:e}){try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function qe(r,t){let e=j(t,".ready"),o=j(t,"graph.mjs");if(F(e)&&F(o))return;Je(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),l=i(s,"wx");a(l),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(o))return;await new Promise(a=>setTimeout(a,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let S,h,b=()=>{if(S!==void 0&&h!==void 0){if(S!==0)return u(new Error(`curl exited ${S}`));if(h!==0)return u(new Error(`tar exited ${h}`));l()}};p.on("close",E=>{S=E,b()}),c.on("close",E=>{h=E,b()}),p.on("error",u),c.on("error",u)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(e,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new x("bundle-extract-failed",i.message)}}async function Xe(r){let t=j(r,"graph.mjs");if(!F(t))throw new x("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ze(t).href)}catch(s){throw new x("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new x("entry-class-missing","no buildGraph() class export found");return o}async function ce(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),o;try{o=Ke()}catch(g){throw g}_.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await Ve({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,S=ze();if(i&&i!==S)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new x("runtime-mismatch",`${S} vs ${i}`);if(!c||!a)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new x("no-bundle","workflow bundle not built yet");let h=se(r);if(!h){let g=j(ct,`${p}@${u||"0"}`);try{await qe(a,g);try{tr()}catch{}}catch(m){throw m.fallback&&await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason}}}),m}try{h=await Xe(g),re(r,h,{workflowUuid:p,version:u,runtimeTag:i,cacheDir:g})}catch(m){throw oe(r,m),await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason||"IMPORT_FAILED"}}}),m.fallback?m:new x("import-failed",m.message)}}let b=Date.now(),A=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),I={...t.input||{}},d,f;try{d=await te({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>A.run(t.parentAgent,I,{signal:t.signal})),f=d&&typeof d=="object"&&"state"in d?d.state:d}catch(g){throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-b}}),g}if(d&&typeof d=="object"&&d.stoppedExternally){await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:f,durationMs:Date.now()-b}});let g=new Error(`Sub-graph '${r}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=n,g}return await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:f,durationMs:Date.now()-b}}),{finalState:f,executionId:n}}function Qe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ie(o)}catch{continue}if(s.isDirectory()){let n;try{n=ae(o)}catch{continue}for(let i of n)e.push(j(o,i))}else t+=s.size}return t}function tr({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(ct))return{evicted:0,freedBytes:0};let t=ae(ct),e=[],o=0;for(let a of t){let l=j(ct,a),u;try{u=ie(l)}catch{continue}let p=u.isDirectory()?Qe(l):u.size;o+=p,e.push({name:a,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let a of e){if(o-n<=s)break;if(!F(j(a.full,".lock")))try{Ye(a.full,{recursive:!0,force:!0}),n+=a.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:o-n}}catch(t){return _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var er=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","timeout"]);function sr(){let r=process.env.PROGRESS_API_URL;if(!r)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return r.replace(/\/executions\/?$/,"")}function nr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function ir(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ar(){return process.env.EXECUTION_ID||null}function le(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],r):r}async function ue(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=o)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${o}. 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 '${r}'`);let{finalState:g}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(g,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(g){if(g instanceof x||g?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=sr(),n=nr(),i=ir(),a=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(u)});if(!p.ok){let g=null,m="";try{g=await p.json(),m=g?.error||g?.message||JSON.stringify(g)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let T=g?.quotaInfo||{},B=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=r,B.quotaInfo=T,B}if(p.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${m}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=g?.validationErrors||null,T.missing=g?.missing||null,T}let P=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${m}`);throw P.code="SUBGRAPH_TRIGGER_FAILED",P.status=p.status,P.subgraph=r,P}let c=await p.json(),S=c?.data?.jobId||c?.jobId;if(!S)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${S} (not waiting)`),{jobId:S,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:rr,b=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:er,E=`${s}/executions/${encodeURIComponent(S)}`,A=Date.now()+h,I="accepted",d=0;for(;Date.now()<A;){await new Promise(T=>setTimeout(T,b)),d+=1;let g=await fetch(E,{headers:{Authorization:`Bearer ${i}`}});if(!g.ok){if(g.status>=500){_.warn(`[sub-graph] status poll for ${S} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${S}: ${g.status}`)}let m=await g.json(),P=m?.data||m?.execution||m;if(I=P?.status||I,or.has(I)){if(I!=="completed"){let y=new Error(`Sub-graph '${r}' (${S}) ended in status '${I}'`);throw y.subgraphJobId=S,y.subgraphStatus=I,y}let T=P?.finalState||P?.state||{},B=le(T,t.output);return _.info(`[sub-graph] '${r}' (${S}) completed after ${d} polls`),B}}let f=new Error(`Sub-graph '${r}' (${S}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw f.subgraphJobId=S,f.subgraphStatus=I,f}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as vt,dirname as de}from"node:path";var lt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=de(vt(e,t));for(let l of n){let u=await this.findAndMergeContextFiles(l,a,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let u=vt(e,l);pe(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=vt(n,t);if(pe(i))try{s.unshift(await this.loadFile(i))}catch(l){console.warn(`[workflow] could not load ${t} from ${i}: ${l.message}`)}let a=de(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
35
35
|
|
package/dist/index.js
CHANGED
|
@@ -29,17 +29,17 @@ ${lt}`,e.col=ut))}return t(s,n,i)}}var me=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(at,e):process.stdout.write.bind(process.stdout)(`${re} ${at} ${e}
|
|
30
30
|
`)}stepMemory(e){let o=k.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ct,o):process.stdout.write.bind(process.stdout)(`${re} ${ct} ${o}
|
|
31
31
|
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,k.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Ae} ${k.red(e)}
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${uo} ${e}`),this._startIntercepting()}nodeComplete(e,o={}){this._stopIntercepting();let{duration:n,details:i}=o;if(i)for(let s of i)this._rawWrite(`${be} ${s}`);let r=n?k.dim(` ${dt(n)}`):"";this._rawWrite(`${it} ${k.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,o,n={}){this._stopIntercepting();let{duration:i}=n,r=i?k.dim(` ${dt(i)}`):"";this._rawWrite(`${Ae} ${k.red(o)}`),this._rawWrite(`${it} ${k.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,o){this._rawWrite(k.dim(` ${e} \u2192 ${o}`)),this._rawWrite("")}graphComplete(){}},x=new me;var se=".zibby/output",ve="sessions",U=".session-info.json",xe=".zibby-stop",po="result.json",fo="raw_stream_output.txt",ho="events.json",ht={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},go=Object.freeze([ht.CODEBASE_MEMORY]),ke=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",t=>Number(t)+1);H.helpers.json||H.registerHelper("json",t=>JSON.stringify(t,null,2));H.helpers.eq||H.registerHelper("eq",(t,e)=>t===e);var j=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)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,o){let n=()=>o&&typeof o.getAll=="function"?o.getAll():e,i=l=>o&&typeof o.get=="function"?o.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 r;typeof this.prompt=="function"?r=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),r=this._compiledPrompt(n())):r=this.prompt;let s=i("_skillHints");s&&(r=`${s}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${uo} ${e}`),this._startIntercepting()}nodeComplete(e,o={}){this._stopIntercepting();let{duration:n,details:i}=o;if(i)for(let s of i)this._rawWrite(`${be} ${s}`);let r=n?k.dim(` ${dt(n)}`):"";this._rawWrite(`${it} ${k.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,o,n={}){this._stopIntercepting();let{duration:i}=n,r=i?k.dim(` ${dt(i)}`):"";this._rawWrite(`${Ae} ${k.red(o)}`),this._rawWrite(`${it} ${k.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,o){this._rawWrite(k.dim(` ${e} \u2192 ${o}`)),this._rawWrite("")}graphComplete(){}},x=new me;var se=".zibby/output",ve="sessions",U=".session-info.json",xe=".zibby-stop",po="result.json",fo="raw_stream_output.txt",ho="events.json",ht={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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},go=Object.freeze([ht.CODEBASE_MEMORY]),ke=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",t=>Number(t)+1);H.helpers.json||H.registerHelper("json",t=>JSON.stringify(t,null,2));H.helpers.eq||H.registerHelper("eq",(t,e)=>t===e);var j=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)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,o){let n=()=>o&&typeof o.getAll=="function"?o.getAll():e,i=l=>o&&typeof o.get=="function"?o.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 r;typeof this.prompt=="function"?r=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),r=this._compiledPrompt(n())):r=this.prompt;let s=i("_skillHints");s&&(r=`${s}
|
|
33
33
|
|
|
34
|
-
${r}`);let a=n(),c=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let l=Me(u,U);if(bt(l)){let f=JSON.parse(Tt(l,"utf-8"));f.currentNode=this.name,Be(l,JSON.stringify(f,null,2),"utf-8")}let p=Me(u,"..",U);if(bt(p))try{let f=JSON.parse(Tt(p,"utf-8"));f.currentNode=this.name,Be(p,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let d=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let p=n().config||{},f=p.agents||{},S=this.config.agent??f[this.name]??null,w={state:n()};S&&(w.preferredAgent=S);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:p,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let h=await E(r,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let y=Me(u,this.name,"raw_stream_output.txt");mo(So(y),{recursive:!0}),Be(y,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(y){I.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let y=m;if(typeof this.onComplete=="function")try{y=await this.onComplete(n(),m)}catch(O){I.warn(`[workflow] onComplete hook failed: ${O.message}`)}return{success:!0,output:y,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(y){throw new Error(`onComplete failed: ${y.message}`,{cause:y})}if(this.parser){let y=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(y,null,2)}`),x.step("Output parsed"),{success:!0,output:y,raw:g}}return{success:!0,output:g,raw:g}}catch(p){d=p,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:d.message,raw:null}}},Q=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){let n=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(n)},raw:null}}};F();F();import{mkdirSync as _o,existsSync as Y,statSync as Ct,readdirSync as Pt,rmSync as Eo}from"node:fs";import{spawn as Ot}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Io}from"node:url";import{AsyncLocalStorage as yo}from"node:async_hooks";var Le=new yo;function ce(){let t=Le.getStore();return t||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(t,e){let o=Le.getStore()||ce(),n=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??o.executionId??null,depth:(o.depth||0)+(t.executionId!==o.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:o.conversationId??null,dispatchMode:t.dispatchMode??null});return Le.run(n,e)}var De=new Map,je=new Map,vt=new Map;function xt(t,e,o={}){if(!t||typeof t!="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(t,e),je.set(t,"ready"),vt.set(t,{...o,cachedAt:Date.now()})}function kt(t,e){je.set(t,"failed"),vt.set(t,{error:e?.message||String(e),failedAt:Date.now()}),De.delete(t)}function Nt(t){return je.get(t)==="ready"?De.get(t):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $o(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,o){super(`in-process sub-graph fallback: ${e}${o?` (${o})`:""}`),this.fallback=!0,this.reason=e,this.detail=o||null,this.name="SubgraphFallback"}};function To(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),o=t||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!o||!n||!i)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:o,projectId:n,authToken:i}}async function bo({apiBase:t,authToken:e,body:o}){let n;try{n=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)})}catch(r){throw new N("network",`begin fetch failed: ${r.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let r=new Error(`Sub-graph child '${o.childWorkflowType}' not found in project`);throw r.code="SUBGRAPH_NOT_FOUND",r.status=404,r}if(n.status===429){let r=i?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${r.used??"?"}/${r.limit??"?"} on ${r.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=r,s}if(n.status===400&&i?.validationErrors){let r=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw r.code="SUBGRAPH_INVALID_INPUT",r.status=400,r.validationErrors=i.validationErrors,r.missing=i.missing,r}throw new N("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:t,authToken:e,payload:o}){try{let n=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${o.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Ao(t,e){let o=G(e,".ready"),n=G(e,"graph.mjs");if(Y(o)&&Y(n))return;_o(e,{recursive:!0});let i=G(e,".lock"),r=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),c=s(i,"wx");a(c),r=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!r){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(o)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,u)=>{let d=Ot("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),l=Ot("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(l.stdin);let p,f,S=()=>{if(p!==void 0&&f!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(f!==0)return u(new Error(`tar exited ${f}`));c()}};d.on("close",w=>{p=w,S()}),l.on("close",w=>{f=w,S()}),d.on("error",u),l.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(o,"");try{a(i)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new N("bundle-extract-failed",s.message)}}async function vo(t){let e=G(t,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${t}`);let o;try{o=await import(Io(e).href)}catch(i){throw new N("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=o.default||Object.values(o).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function Rt(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let o=ce(),n;try{n=To()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${t}' parent=${o.executionId||"<root>"}`);let i=await bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:o.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:r,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:c,workflowVersion:u,workflowUuid:d,bundleReady:l}=i,p=$o();if(s&&s!==p)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",error:{message:`runtimeTag mismatch: parent=${p} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${p} vs ${s}`);if(!l||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,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 f=Nt(t);if(!f){let m=G(Se,`${d}@${u||"0"}`);try{await Ao(a,m);try{ko()}catch{}}catch(y){throw y.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{f=await vo(m),xt(t,f,{workflowUuid:d,version:u,runtimeTag:s,cacheDir:m})}catch(y){throw kt(t,y),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let S=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await At({executionId:r,parentExecutionId:o.executionId,conversationId:e.conversationId!==void 0?e.conversationId:o.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-S}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",finalState:g,durationMs:Date.now()-S}});let m=new Error(`Sub-graph '${t}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=r,m}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"completed",finalState:g,durationMs:Date.now()-S}}),{finalState:g,executionId:r}}function xo(t){let e=0,o=[t];for(;o.length;){let n=o.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let r;try{r=Pt(n)}catch{continue}for(let s of r)o.push(G(n,s))}else e+=i.size}return e}function ko({cap:t=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(Se))return{evicted:0,freedBytes:0};let e=Pt(Se),o=[],n=0;for(let a of e){let c=G(Se,a),u;try{u=Ct(c)}catch{continue}let d=u.isDirectory()?xo(c):u.size;n+=d,o.push({name:a,full:c,size:d,mtimeMs:u.mtimeMs})}if(n<=t)return{evicted:0,freedBytes:0,totalBytes:n};o.sort((a,c)=>a.mtimeMs-c.mtimeMs);let i=Math.floor(t*.7),r=0,s=0;for(let a of o){if(n-r<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),r+=a.size,s+=1}catch(c){I.debug(`[sub-graph cache] evict skip ${a.name}: ${c.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(r/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:r,totalBytes:n-r}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var No=2e3,Oo=600*1e3,Co=new Set(["completed","failed","canceled","timeout"]);function Po(){let t=process.env.PROGRESS_API_URL;if(!t)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 t.replace(/\/executions\/?$/,"")}function Ro(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function Bo(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function Mo(){return process.env.EXECUTION_ID||null}function Bt(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((o,n)=>o==null?o:o[n],t):t}async function Fe(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let o=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((o.depth||0)>=n)throw new Error(`dispatchSubgraph('${t}'): sub-graph depth ${o.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 '${t}'`);let{finalState:m}=await Rt(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),y=Bt(m,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),y}catch(m){if(m instanceof N||m?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Po(),r=Ro(),s=Bo(),a=Mo(),c=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(t)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)});if(!d.ok){let m=null,y="";try{m=await d.json(),y=m?.error||m?.message||JSON.stringify(m)}catch{y=await d.text().catch(()=>"")}if(d.status===429){let A=m?.quotaInfo||{},R=new Error(`Sub-graph '${t}' 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=t,R.quotaInfo=A,R}if(d.status===400){let A=new Error(`Sub-graph '${t}' rejected input: ${y}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=t,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let O=new Error(`Sub-graph '${t}' trigger rejected (${d.status}): ${y}`);throw O.code="SUBGRAPH_TRIGGER_FAILED",O.status=d.status,O.subgraph=t,O}let l=await d.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:t};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:Oo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:No,w=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(A=>setTimeout(A,S)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let y=await m.json(),O=y?.data||y?.execution||y;if(E=O?.status||E,Co.has(E)){if(E!=="completed"){let _=new Error(`Sub-graph '${t}' (${p}) ended in status '${E}'`);throw _.subgraphJobId=p,_.subgraphStatus=E,_}let A=O?.finalState||O?.state||{},R=Bt(A,e.output);return I.info(`[sub-graph] '${t}' (${p}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${t}' (${p}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=p,g.subgraphStatus=E,g}import{existsSync as Mt,readFileSync as Lo}from"node:fs";import{join as Ge,dirname as Lt}from"node:path";var le=class{static async loadContext(e,o,n={}){let i={},r=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Lt(Ge(o,e));for(let c of r){let u=await this.findAndMergeContextFiles(c,a,o);if(u){let d=c.replace(/\.[^.]+$/,"").toLowerCase();i[d]=u}}}let s=n.discovery||{};for(let[a,c]of Object.entries(s))try{let u=Ge(o,c);Mt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${c}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,o,n){let i=[],r=o;for(;r.startsWith(n);){let s=Ge(r,e);if(Mt(s))try{i.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=Lt(r);if(a===r)break;r=a}return i.length===0?null:i.every(s=>typeof s=="string")?i.join(`
|
|
34
|
+
${r}`);let a=n(),c=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let l=Me(u,U);if(bt(l)){let f=JSON.parse(Tt(l,"utf-8"));f.currentNode=this.name,Be(l,JSON.stringify(f,null,2),"utf-8")}let p=Me(u,"..",U);if(bt(p))try{let f=JSON.parse(Tt(p,"utf-8"));f.currentNode=this.name,Be(p,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let d=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let p=n().config||{},f=p.agents||{},S=this.config.agent??f[this.name]??null,w={state:n()};S&&(w.preferredAgent=S);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:p,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let h=await E(r,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let y=Me(u,this.name,"raw_stream_output.txt");mo(So(y),{recursive:!0}),Be(y,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(y){I.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let y=m;if(typeof this.onComplete=="function")try{y=await this.onComplete(n(),m)}catch(O){I.warn(`[workflow] onComplete hook failed: ${O.message}`)}return{success:!0,output:y,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(y){throw new Error(`onComplete failed: ${y.message}`,{cause:y})}if(this.parser){let y=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(y,null,2)}`),x.step("Output parsed"),{success:!0,output:y,raw:g}}return{success:!0,output:g,raw:g}}catch(p){d=p,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:d.message,raw:null}}},Q=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){let n=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(n)},raw:null}}};F();F();import{mkdirSync as _o,existsSync as Y,statSync as Ct,readdirSync as Pt,rmSync as Eo}from"node:fs";import{spawn as Ot}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Io}from"node:url";import{AsyncLocalStorage as yo}from"node:async_hooks";var De=new yo;function ce(){let t=De.getStore();return t||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(t,e){let o=De.getStore()||ce(),n=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??o.executionId??null,depth:(o.depth||0)+(t.executionId!==o.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:o.conversationId??null,dispatchMode:t.dispatchMode??null});return De.run(n,e)}var Le=new Map,je=new Map,vt=new Map;function xt(t,e,o={}){if(!t||typeof t!="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(t,e),je.set(t,"ready"),vt.set(t,{...o,cachedAt:Date.now()})}function kt(t,e){je.set(t,"failed"),vt.set(t,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(t)}function Nt(t){return je.get(t)==="ready"?Le.get(t):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $o(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,o){super(`in-process sub-graph fallback: ${e}${o?` (${o})`:""}`),this.fallback=!0,this.reason=e,this.detail=o||null,this.name="SubgraphFallback"}};function To(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),o=t||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!o||!n||!i)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:o,projectId:n,authToken:i}}async function bo({apiBase:t,authToken:e,body:o}){let n;try{n=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)})}catch(r){throw new N("network",`begin fetch failed: ${r.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let r=new Error(`Sub-graph child '${o.childWorkflowType}' not found in project`);throw r.code="SUBGRAPH_NOT_FOUND",r.status=404,r}if(n.status===429){let r=i?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${r.used??"?"}/${r.limit??"?"} on ${r.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=r,s}if(n.status===400&&i?.validationErrors){let r=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw r.code="SUBGRAPH_INVALID_INPUT",r.status=400,r.validationErrors=i.validationErrors,r.missing=i.missing,r}throw new N("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:t,authToken:e,payload:o}){try{let n=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${o.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Ao(t,e){let o=G(e,".ready"),n=G(e,"graph.mjs");if(Y(o)&&Y(n))return;_o(e,{recursive:!0});let i=G(e,".lock"),r=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),c=s(i,"wx");a(c),r=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!r){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(o)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,u)=>{let d=Ot("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),l=Ot("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(l.stdin);let p,f,S=()=>{if(p!==void 0&&f!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(f!==0)return u(new Error(`tar exited ${f}`));c()}};d.on("close",w=>{p=w,S()}),l.on("close",w=>{f=w,S()}),d.on("error",u),l.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(o,"");try{a(i)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new N("bundle-extract-failed",s.message)}}async function vo(t){let e=G(t,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${t}`);let o;try{o=await import(Io(e).href)}catch(i){throw new N("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=o.default||Object.values(o).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function Rt(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let o=ce(),n;try{n=To()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${t}' parent=${o.executionId||"<root>"}`);let i=await bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:o.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:r,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:c,workflowVersion:u,workflowUuid:d,bundleReady:l}=i,p=$o();if(s&&s!==p)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",error:{message:`runtimeTag mismatch: parent=${p} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${p} vs ${s}`);if(!l||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,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 f=Nt(t);if(!f){let m=G(Se,`${d}@${u||"0"}`);try{await Ao(a,m);try{ko()}catch{}}catch(y){throw y.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{f=await vo(m),xt(t,f,{workflowUuid:d,version:u,runtimeTag:s,cacheDir:m})}catch(y){throw kt(t,y),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let S=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await At({executionId:r,parentExecutionId:o.executionId,conversationId:e.conversationId!==void 0?e.conversationId:o.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-S}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",finalState:g,durationMs:Date.now()-S}});let m=new Error(`Sub-graph '${t}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=r,m}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"completed",finalState:g,durationMs:Date.now()-S}}),{finalState:g,executionId:r}}function xo(t){let e=0,o=[t];for(;o.length;){let n=o.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let r;try{r=Pt(n)}catch{continue}for(let s of r)o.push(G(n,s))}else e+=i.size}return e}function ko({cap:t=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(Se))return{evicted:0,freedBytes:0};let e=Pt(Se),o=[],n=0;for(let a of e){let c=G(Se,a),u;try{u=Ct(c)}catch{continue}let d=u.isDirectory()?xo(c):u.size;n+=d,o.push({name:a,full:c,size:d,mtimeMs:u.mtimeMs})}if(n<=t)return{evicted:0,freedBytes:0,totalBytes:n};o.sort((a,c)=>a.mtimeMs-c.mtimeMs);let i=Math.floor(t*.7),r=0,s=0;for(let a of o){if(n-r<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),r+=a.size,s+=1}catch(c){I.debug(`[sub-graph cache] evict skip ${a.name}: ${c.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(r/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:r,totalBytes:n-r}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var No=2e3,Oo=600*1e3,Co=new Set(["completed","failed","canceled","timeout"]);function Po(){let t=process.env.PROGRESS_API_URL;if(!t)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 t.replace(/\/executions\/?$/,"")}function Ro(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function Bo(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function Mo(){return process.env.EXECUTION_ID||null}function Bt(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((o,n)=>o==null?o:o[n],t):t}async function Fe(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let o=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((o.depth||0)>=n)throw new Error(`dispatchSubgraph('${t}'): sub-graph depth ${o.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 '${t}'`);let{finalState:m}=await Rt(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),y=Bt(m,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),y}catch(m){if(m instanceof N||m?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Po(),r=Ro(),s=Bo(),a=Mo(),c=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(t)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)});if(!d.ok){let m=null,y="";try{m=await d.json(),y=m?.error||m?.message||JSON.stringify(m)}catch{y=await d.text().catch(()=>"")}if(d.status===429){let A=m?.quotaInfo||{},R=new Error(`Sub-graph '${t}' 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=t,R.quotaInfo=A,R}if(d.status===400){let A=new Error(`Sub-graph '${t}' rejected input: ${y}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=t,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let O=new Error(`Sub-graph '${t}' trigger rejected (${d.status}): ${y}`);throw O.code="SUBGRAPH_TRIGGER_FAILED",O.status=d.status,O.subgraph=t,O}let l=await d.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:t};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:Oo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:No,w=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(A=>setTimeout(A,S)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let y=await m.json(),O=y?.data||y?.execution||y;if(E=O?.status||E,Co.has(E)){if(E!=="completed"){let _=new Error(`Sub-graph '${t}' (${p}) ended in status '${E}'`);throw _.subgraphJobId=p,_.subgraphStatus=E,_}let A=O?.finalState||O?.state||{},R=Bt(A,e.output);return I.info(`[sub-graph] '${t}' (${p}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${t}' (${p}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=p,g.subgraphStatus=E,g}import{existsSync as Mt,readFileSync as Do}from"node:fs";import{join as Ge,dirname as Dt}from"node:path";var le=class{static async loadContext(e,o,n={}){let i={},r=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Dt(Ge(o,e));for(let c of r){let u=await this.findAndMergeContextFiles(c,a,o);if(u){let d=c.replace(/\.[^.]+$/,"").toLowerCase();i[d]=u}}}let s=n.discovery||{};for(let[a,c]of Object.entries(s))try{let u=Ge(o,c);Mt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${c}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,o,n){let i=[],r=o;for(;r.startsWith(n);){let s=Ge(r,e);if(Mt(s))try{i.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=Dt(r);if(a===r)break;r=a}return i.length===0?null:i.every(s=>typeof s=="string")?i.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):i.every(s=>typeof s=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let o=
|
|
38
|
+
`):i.every(s=>typeof s=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let o=Do(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(o);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),i=await import(n(e).href);return i.default||i}return o}};import{mkdirSync as Ft,existsSync as Ue,writeFileSync as Lt,unlinkSync as Lo}from"node:fs";import{join as z,resolve as Gt}from"node:path";import{config as jo}from"dotenv";import{zodToJsonSchema as jt}from"zod-to-json-schema";import{z as ye}from"zod";import Fo from"handlebars";function Go({traceFrom:t,sessionId:e,sessionPath:o,idSource:n,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${t} pid=${process.pid} ppid=${s} sessionId=${e} source=${n} mkdir=${i?"yes":"no"} path=${o}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let d=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${t}):
|
|
41
|
-
${d}`)}}function Ut(){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 Wt(){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 Gt(String(e).trim())}catch{return String(e).trim()}}function Ht(){Ut()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Jt({sessionPath:t,sessionId:e}){t&&typeof t=="string"&&(process.env.ZIBBY_SESSION_PATH=t),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Yt(t={}){let e=ke.map(r=>process.env[r]).find(Boolean),o=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${o}`,i=t.paths?.sessionPrefix;return i?`${i}_${n}`:n}function zt({cwd:t=process.cwd(),config:e={},initialState:o={},traceFrom:n="resolveWorkflowSession"}={}){let i=o.sessionPath,r=o.sessionTimestamp,s="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Gt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Yt(e),s="generated")}r=r??Date.now();let d=e.paths?.output||se;i=z(t,d,ve,a)}let c=!Ue(i);return c&&Ft(i,{recursive:!0}),(c||s!=="initialState.sessionPath")&&Go({traceFrom:n,sessionId:a,sessionPath:i,idSource:s,mkdirFresh:c}),Jt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:r}}var ue=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,o,n={}){if(!(o instanceof j)&&o&&typeof o=="object"&&typeof o.workflow=="string"){let r=o,s={name:e,_isCustomCode:!0,retries:r.retries,onComplete:r.onComplete,execute:async c=>{let u=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,d;return typeof r.input=="function"?d=r.input(u):r.input&&typeof r.input=="object"?d=r.input:d={},Fe(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(u):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:u?._signal,parentAgent:c?.agent})}},a=new j(s);return a.name=e,this.nodes.set(e,a),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=o instanceof j?o:new j(o);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof o?.prompt=="string"&&o.prompt.trim()&&this.nodePrompts.set(e,o.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addConditionalNode(e,o){return this.nodes.set(e,new Q({...o,name:e})),this}addEdge(e,o){return this.edges.set(e,o),this}setNodeType(e,o){return this.nodeTypeMap.set(e,o),this}addConditionalEdges(e,o,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:o,labels:n}),typeof o=="function"&&this.conditionalCodeMap.set(e,o.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,o,n,i,r){let s=n;for(let a=e.length-1;a>=0;a--){let c=e[a],u=s;s=()=>c(o,u,i,r)}return s()}serialize(){let e=[],o={};for(let[d,l]of this.nodes){let p=this.nodeTypeMap.get(d)||(l instanceof Q?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};l._isCustomCode&&typeof l.execute=="function"&&(f.customCode=l.execute.toString());let S=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;S&&(f.description=S);let w=this.nodePrompts.get(d);if(w)f.prompt=w;else if(typeof l.prompt=="function")try{let g=l.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(f.executeCode=l.customExecute.toString()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let g=null;if(typeof ye?.toJSONSchema=="function")try{g=ye.toJSONSchema(l.outputSchema)}catch{}if(!g)try{g=jt(l.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:l.outputSchema}}else f.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(o[d]=f)}let n=[];for(let[d,l]of this.edges)if(typeof l=="string")n.push({source:d,target:l});else if(l.conditional){let p=this.conditionalCodeMap.get(d)||l.routes.toString(),f=this._inferConditionalTargets(l.routes,l.labels),S=l.labels||{};for(let w of f){let $={source:d,target:w,data:{conditionalCode:p}};S[w]&&($.label=S[w]),n.push($)}}let i=d=>{if(!d)return null;if(typeof ye?.toJSONSchema=="function")try{return ye.toJSONSchema(d)}catch{}try{return jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let r=0;for(let d of n)if(d.target==="END"){r+=1;let l=`END__${r}`;d.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){r+=1;let l=`END__${r}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:l})}let s=this._runtimeSchema(),a=i(s||this.stateSchema),c=i(this.inputSchema),u=i(this.contextSchema);return{nodes:e,edges:n,nodeConfigs:o,stateSchema:a,inputSchema:c,contextSchema:u}}_inferConditionalTargets(e,o){let n=e.toString(),i=new Set,r=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=r.exec(n))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&i.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(o&&typeof o=="object")for(let u of Object.keys(o))a.add(u);let c=new Set;for(let u of i)a.has(u)&&c.add(u);if(c.size===0){let u=/return\s+['"]([^'"]+)['"]/g,d;for(;(d=u.exec(n))!==null;)c.add(d[1])}return[...c]}_flattenJsonSchemaToVariables(e,o=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,o)}_flattenSchema(e,o=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},r=e.required||[];for(let[s,a]of Object.entries(i)){let c=o?`${o}.${s}`:s;n.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!r.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${c}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,o=>o.toUpperCase()).trim()}_summarizeNodeOutput(e,o){if(!o||typeof o!="object")return[];let n=[];o.success!==void 0&&n.push(`Result: ${o.success?"passed":"failed"}`);for(let[i,r]of Object.entries(o))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof r=="string"&&r.length<=80)n.push(`${i}: ${r}`);else if(Array.isArray(r)){let s=r.length,a=r.filter(u=>u?.passed===!0).length,c=r.some(u=>u?.passed!==void 0);n.push(c?`${i}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${i}: ${s} items`)}if(n.length>=4)break}return n}async run(e,o={},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 r=n.strategyAbortTimeoutMs??o.config?.strategyAbortTimeoutMs??5e3,s=o.cwd||process.cwd();jo({path:z(s,".env")});let a=o.config||{};if(!a||Object.keys(a).length===0)try{let T=z(s,".zibby.config.js");Ue(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=o.agentType;if(!c){let T=a?.agent;T?.provider?c=T.provider:T?.gemini?c="gemini":T?.claude?c="claude":T?.cursor?c="cursor":T?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let u=o.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},d=this._runtimeSchema();if(d){let T=d.safeParse(o);if(!T.success){let C=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`);throw console.error("\u274C Initial state validation failed:"),C.forEach(P=>console.error(` - ${P}`)),new Error(`State validation failed: ${C.join(", ")}`)}x.step("State validated against schema")}let l=Wt(),p=o.sessionPath||l;p||Ht();let{sessionPath:f,sessionTimestamp:S,sessionId:w}=zt({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:p,sessionTimestamp:o.sessionTimestamp}});x.step(`Session ${w}`);let $=await le.loadContext(o.specPath||"",s,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let E=o.outputPath;!E&&o.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(o.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${o.specPath})`));let h=new te({...o,config:a,agentType:c,outputPath:E,sessionPath:f,sessionTimestamp:S,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(ie(),_t)),y=a.skills&&typeof a.skills=="object"?a.skills:{},O=Object.values(y).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let C of O)if(C.id===T)return C;return m(T)},R=new Set;for(let[,T]of this.nodes)for(let C of T.config?.skills||[])R.add(C);for(let T of R){let C=A(T);if(typeof C?.middleware=="function")try{let P=await C.middleware();typeof P=="function"&&g.set(T,P)}catch{}}let _=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,qt=0;try{for(;_&&_!=="END";){if(++qt>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let C=z(f,xe);if(Ue(C)){try{Do(C)}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:h.getAll(),executionLog:pe,stoppedExternally:!0};let P=this.nodes.get(_);if(!P)throw new Error(`Node '${_}' not found in graph`);let Ve=JSON.stringify({sessionPath:f,sessionTimestamp:S,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),Xt=z(f,U);
|
|
41
|
+
${d}`)}}function Ut(){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 Wt(){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 Gt(String(e).trim())}catch{return String(e).trim()}}function Ht(){Ut()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Jt({sessionPath:t,sessionId:e}){t&&typeof t=="string"&&(process.env.ZIBBY_SESSION_PATH=t),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Yt(t={}){let e=ke.map(r=>process.env[r]).find(Boolean),o=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${o}`,i=t.paths?.sessionPrefix;return i?`${i}_${n}`:n}function zt({cwd:t=process.cwd(),config:e={},initialState:o={},traceFrom:n="resolveWorkflowSession"}={}){let i=o.sessionPath,r=o.sessionTimestamp,s="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Gt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Yt(e),s="generated")}r=r??Date.now();let d=e.paths?.output||se;i=z(t,d,ve,a)}let c=!Ue(i);return c&&Ft(i,{recursive:!0}),(c||s!=="initialState.sessionPath")&&Go({traceFrom:n,sessionId:a,sessionPath:i,idSource:s,mkdirFresh:c}),Jt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:r}}var ue=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,o,n={}){if(!(o instanceof j)&&o&&typeof o=="object"&&typeof o.workflow=="string"){let r=o,s={name:e,_isCustomCode:!0,retries:r.retries,onComplete:r.onComplete,execute:async c=>{let u=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,d;return typeof r.input=="function"?d=r.input(u):r.input&&typeof r.input=="object"?d=r.input:d={},Fe(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(u):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:u?._signal,parentAgent:c?.agent})}},a=new j(s);return a.name=e,this.nodes.set(e,a),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=o instanceof j?o:new j(o);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof o?.prompt=="string"&&o.prompt.trim()&&this.nodePrompts.set(e,o.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addConditionalNode(e,o){return this.nodes.set(e,new Q({...o,name:e})),this}addEdge(e,o){return this.edges.set(e,o),this}setNodeType(e,o){return this.nodeTypeMap.set(e,o),this}addConditionalEdges(e,o,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:o,labels:n}),typeof o=="function"&&this.conditionalCodeMap.set(e,o.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,o,n,i,r){let s=n;for(let a=e.length-1;a>=0;a--){let c=e[a],u=s;s=()=>c(o,u,i,r)}return s()}serialize(){let e=[],o={};for(let[d,l]of this.nodes){let p=this.nodeTypeMap.get(d)||(l instanceof Q?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};l._isCustomCode&&typeof l.execute=="function"&&(f.customCode=l.execute.toString());let S=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;S&&(f.description=S);let w=this.nodePrompts.get(d);if(w)f.prompt=w;else if(typeof l.prompt=="function")try{let g=l.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(f.executeCode=l.customExecute.toString()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let g=null;if(typeof ye?.toJSONSchema=="function")try{g=ye.toJSONSchema(l.outputSchema)}catch{}if(!g)try{g=jt(l.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:l.outputSchema}}else f.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(o[d]=f)}let n=[];for(let[d,l]of this.edges)if(typeof l=="string")n.push({source:d,target:l});else if(l.conditional){let p=this.conditionalCodeMap.get(d)||l.routes.toString(),f=this._inferConditionalTargets(l.routes,l.labels),S=l.labels||{};for(let w of f){let $={source:d,target:w,data:{conditionalCode:p}};S[w]&&($.label=S[w]),n.push($)}}let i=d=>{if(!d)return null;if(typeof ye?.toJSONSchema=="function")try{return ye.toJSONSchema(d)}catch{}try{return jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let r=0;for(let d of n)if(d.target==="END"){r+=1;let l=`END__${r}`;d.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){r+=1;let l=`END__${r}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:l})}let s=this._runtimeSchema(),a=i(s||this.stateSchema),c=i(this.inputSchema),u=i(this.contextSchema);return{nodes:e,edges:n,nodeConfigs:o,stateSchema:a,inputSchema:c,contextSchema:u}}_inferConditionalTargets(e,o){let n=e.toString(),i=new Set,r=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=r.exec(n))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&i.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(o&&typeof o=="object")for(let u of Object.keys(o))a.add(u);let c=new Set;for(let u of i)a.has(u)&&c.add(u);if(c.size===0){let u=/return\s+['"]([^'"]+)['"]/g,d;for(;(d=u.exec(n))!==null;)c.add(d[1])}return[...c]}_flattenJsonSchemaToVariables(e,o=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,o)}_flattenSchema(e,o=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},r=e.required||[];for(let[s,a]of Object.entries(i)){let c=o?`${o}.${s}`:s;n.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!r.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${c}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,o=>o.toUpperCase()).trim()}_summarizeNodeOutput(e,o){if(!o||typeof o!="object")return[];let n=[];o.success!==void 0&&n.push(`Result: ${o.success?"passed":"failed"}`);for(let[i,r]of Object.entries(o))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof r=="string"&&r.length<=80)n.push(`${i}: ${r}`);else if(Array.isArray(r)){let s=r.length,a=r.filter(u=>u?.passed===!0).length,c=r.some(u=>u?.passed!==void 0);n.push(c?`${i}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${i}: ${s} items`)}if(n.length>=4)break}return n}async run(e,o={},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 r=n.strategyAbortTimeoutMs??o.config?.strategyAbortTimeoutMs??5e3,s=o.cwd||process.cwd();jo({path:z(s,".env")});let a=o.config||{};if(!a||Object.keys(a).length===0)try{let T=z(s,".zibby.config.js");Ue(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=o.agentType;if(!c){let T=a?.agent;T?.provider?c=T.provider:T?.gemini?c="gemini":T?.claude?c="claude":T?.cursor?c="cursor":T?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let u=o.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},d=this._runtimeSchema();if(d){let T=d.safeParse(o);if(!T.success){let C=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`);throw console.error("\u274C Initial state validation failed:"),C.forEach(P=>console.error(` - ${P}`)),new Error(`State validation failed: ${C.join(", ")}`)}x.step("State validated against schema")}let l=Wt(),p=o.sessionPath||l;p||Ht();let{sessionPath:f,sessionTimestamp:S,sessionId:w}=zt({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:p,sessionTimestamp:o.sessionTimestamp}});x.step(`Session ${w}`);let $=await le.loadContext(o.specPath||"",s,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let E=o.outputPath;!E&&o.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(o.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${o.specPath})`));let h=new te({...o,config:a,agentType:c,outputPath:E,sessionPath:f,sessionTimestamp:S,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(ie(),_t)),y=a.skills&&typeof a.skills=="object"?a.skills:{},O=Object.values(y).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let C of O)if(C.id===T)return C;return m(T)},R=new Set;for(let[,T]of this.nodes)for(let C of T.config?.skills||[])R.add(C);for(let T of R){let C=A(T);if(typeof C?.middleware=="function")try{let P=await C.middleware();typeof P=="function"&&g.set(T,P)}catch{}}let _=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,qt=0;try{for(;_&&_!=="END";){if(++qt>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let C=z(f,xe);if(Ue(C)){try{Lo(C)}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:h.getAll(),executionLog:pe,stoppedExternally:!0};let P=this.nodes.get(_);if(!P)throw new Error(`Node '${_}' not found in graph`);let Ve=JSON.stringify({sessionPath:f,sessionTimestamp:S,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),Xt=z(f,U);Lt(Xt,Ve,"utf-8");let qe=h.get("config")?.paths?.output||se,Qt=z(s,qe,U);Ft(z(s,qe),{recursive:!0});try{Lt(Qt,Ve,"utf-8")}catch{}let Xe=o.onPipelineProgress;if(typeof Xe=="function")try{Xe({cwd:s,sessionPath:f,sessionId:w,outputBase:h.get("config")?.paths?.output||se,currentNode:_})}catch{}let eo=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",eo);let to=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",to[_]||{}),x.nodeStart(_);let Qe=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let v=await Promise.resolve().then(()=>(X(),ae));this._invokeAgent=v.invokeAgent}let oo=this._invokeAgent,Ie={},no=P.config?.skills||[];for(let v of no){let B=A(v);if(typeof B?.invokeAgentOptions=="function")try{let b=B.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});b&&typeof b=="object"&&(Ie={...Ie,...b})}catch(b){console.warn(`[graph] skill '${v}' invokeAgentOptions threw: ${b.message}`)}}let et=async(v,B,b={})=>{let M=oo(v,B,{...Ie,...b,signal:i.signal});return M.catch(()=>{}),i.signal.aborted?M:Promise.race([M,new Promise((Z,K)=>{let L=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${r}ms`);ee.name="AbortError",K(ee)},r)};i.signal.addEventListener("abort",L,{once:!0})})])},ro=async(v={},B={})=>{let b=B.prompt||"";if(fe){let M=this._compiledPrompts.get(_);M||(M=Fo.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,M));try{b=M(v)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${_}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!b)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return et(b,{state:h.getAll(),images:B.images||[]},{model:B.model||h.get("model"),workspace:h.get("workspace"),schema:B.schema,...B,signal:i.signal})},tt=h.getAll(),so=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let v of so)Object.prototype.hasOwnProperty.call(tt,v)&&console.warn(`[workflow] node "${_}": state key "${v}" is shadowed by the engine context prop; read it via context.state.get('${v}')`);let ot={...tt,state:h,invokeAgent:ro,_coreInvokeAgent:et,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let v=(P.config?.skills||[]).map(L=>g.get(L)).filter(Boolean),B=[...this.middleware,...v],b;B.length>0?b=await this._composeMiddleware(B,_,async()=>P.execute(ot,h),h.getAll(),h):b=await P.execute(ot,h);let M=Date.now()-Qe;if(pe.push({node:_,success:b.success,duration:M,timestamp:new Date().toISOString()}),!b.success){if(i.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};h.append("errors",{node:_,error:b.error});let L=P.config?.retries||0,ee=`${_}_retries`,he=h.getAll()[ee]||0;if(he<L){x.stepInfo(`Retrying (attempt ${he+1}/${L})`),h.update({[ee]:he+1,[`${_}_raw`]:b.raw});continue}throw x.nodeFailed(_,b.error,{duration:M}),new Error(`Node '${_}' failed after ${he} attempts: ${b.error}`)}h.update({[_]:b.output});let Z=this._summarizeNodeOutput(_,b.output);x.nodeComplete(_,{duration:M,details:Z});let K=this.edges.get(_);if(!K)_="END";else if(K.conditional){let L=K.routes(h.getAll());x.route(_,L),_=L}else _=K}catch(v){throw x.isInsideNode&&x.nodeFailed(_,v.message,{duration:Date.now()-Qe}),h.set("failed",!0),h.set("failedAt",_),v}}x.graphComplete();let T={success:!0,state:h.getAll(),executionLog:pe};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 We=Symbol.for("@zibby/agent-workflow.nodes");globalThis[We]||(globalThis[We]=new Map);var de=globalThis[We];function Zt(t,e){de.set(t,e)}function He(t){return de.get(t)}function we(t){return de.has(t)}function Uo(){return Array.from(de.keys())}function Je(t){let e=de.get(t);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}Zt("ai_agent",{name:"ai_agent",factory:!0,create:(t,e={})=>({name:t,_isCustomCode:!0,execute:async o=>{let n=o?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",r=Wo(i,o),s=await n(r,{cwd:o.workspace||process.cwd(),model:o.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:t},raw:typeof s=="string"?s:s.raw}}})});function Wo(t,e){let o=/@([\w.]+)/g,n=new Set,i;for(;(i=o.exec(t))!==null;)n.add(i[1]);if(n.size===0)return t;let r=[],s=new Set;for(let a of n){let c=a.split(".")[0];if(s.has(c))continue;let u=a.split(".").reduce((p,f)=>p?.[f],e);if(u===void 0)continue;let d=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,p=>p.toUpperCase());r.push(`## ${l}
|
|
43
43
|
${d}`),a.includes(".")||s.add(c)}return r.length===0?t:`${t}
|
|
44
44
|
|
|
45
45
|
---
|
|
@@ -47,7 +47,7 @@ ${d}`),a.includes(".")||s.add(c)}return r.length===0?t:`${t}
|
|
|
47
47
|
|
|
48
48
|
${r.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}ie();F();var _e={};function ze(t,e){if(Array.isArray(e))return Ye(e);let o=_e[t];return!o||o.length===0?null:Ye(o)}function Ye(t){if(!Array.isArray(t)||t.length===0)return null;let e=[],o={},n=[];for(let i of t){let r=q(i);if(!r){I.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}n.push(i);for(let s of r.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!o[r.serverName])if(typeof r.resolve=="function"){let s=r.resolve();s&&(o[r.serverName]={...s,toolPrefix:i})}else{let s={};for(let a of r.envKeys||[]){let c=process.env[a];c&&(s[a]=c)}o[r.serverName]={command:r.command,args:[...r.args||[]],env:s,toolPrefix:i}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:o}}F();function Ho(t,e={}){let{nodes:o,edges:n,nodeConfigs:i={}}=t;if(!Array.isArray(o)||o.length===0)throw new
|
|
50
|
+
`)}`}ie();F();var _e={};function ze(t,e){if(Array.isArray(e))return Ye(e);let o=_e[t];return!o||o.length===0?null:Ye(o)}function Ye(t){if(!Array.isArray(t)||t.length===0)return null;let e=[],o={},n=[];for(let i of t){let r=q(i);if(!r){I.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}n.push(i);for(let s of r.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!o[r.serverName])if(typeof r.resolve=="function"){let s=r.resolve();s&&(o[r.serverName]={...s,toolPrefix:i})}else{let s={};for(let a of r.envKeys||[]){let c=process.env[a];c&&(s[a]=c)}o[r.serverName]={command:r.command,args:[...r.args||[]],env:s,toolPrefix:i}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:o}}F();function Ho(t,e={}){let{nodes:o,edges:n,nodeConfigs:i={}}=t;if(!Array.isArray(o)||o.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(n))throw new D("Graph edges must be an array");let r=new ue(e);e.stateSchema&&r.setStateSchema(e.stateSchema);let s=new Set,a=new Map,c={};for(let p of o){let f=Ee(p);a.set(p.id,{...p,resolvedType:f}),f==="decision"&&s.add(p.id)}for(let[p,f]of a){if(s.has(p))continue;let S=f.resolvedType,w=i[p]||{},$=ze(S,w.tools);$&&(c[p]=$);let E={};w.prompt&&(E.prompt=w.prompt);let h=we(S);if(I.debug(`[workflow] compiler: node "${p}" type="${S}" registered=${h}`),w.customCode&&!h)r.addNode(p,Kt(p,w.customCode,w),E),r.setNodeType(p,S);else if(h){let g=He(S);g.factory?r.addNode(p,g.create(p,{...w,resolvedTools:$}),E):r.addNode(p,g,E),r.setNodeType(p,S)}else if(w.executeCode)r.addNode(p,Kt(p,w.executeCode,w),E),r.setNodeType(p,S);else throw new D(`Unknown node type "${S}" for node "${p}". Did you forget to register it?`)}r.resolvedToolsMap=c;let u=new Set;for(let p of n)s.has(p.target)||u.add(p.target);let d=o.find(p=>!s.has(p.id)&&!u.has(p.id));if(!d)throw new D("Could not determine entry point: no node without incoming edges found");r.setEntryPoint(d.id);let l=zo(n,"source");for(let p of n)if(!s.has(p.source))if(s.has(p.target)){let f=p.target,S=l.get(f)||[];if(S.length===0)throw new D(`Decision node "${f}" has no outgoing edges`);let w=Zo(f,S,s);r.addConditionalEdges(p.source,w)}else r.addEdge(p.source,p.target);return r}function Jo(t){let e=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(t.nodes)||t.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(t.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let o=t.nodeConfigs||{};for(let a of t.nodes){let c=Ee(a);if(c==="decision"||we(c))continue;let u=o[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let n=new Set(t.nodes.map(a=>a.id));for(let a of t.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(t.nodes.filter(a=>Ee(a)==="decision").map(a=>a.id)),r=new Set;for(let a of t.edges)i.has(a.target)||r.add(a.target);let s=t.nodes.filter(a=>!i.has(a.id)&&!r.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of i){let c=t.edges.filter(d=>d.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(d=>d.data?.conditionalCode||d.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Yo(t){return!t||!Array.isArray(t.nodes)?[]:t.nodes.filter(e=>Ee(e)!=="decision").map(e=>e.id)}function Ee(t){let e=t.data?.nodeType||t.data?.type||t.type;return e==="workflowNode"||e==="custom"||e==="default"?t.id:e}function zo(t,e){let o=new Map;for(let n of t){let i=n[e];o.has(i)||o.set(i,[]),o.get(i).push(n)}return o}function Zo(t,e,o){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new D(`Decision node "${t}" has no conditionalCode on its outgoing edges`);let i=n.data?.conditionalCode||n.conditionalCode,r=new Set(e.map(a=>a.target).filter(a=>!o.has(a))),s;try{let c=new Function(`return (${i})`)();s=u=>{let d=c(u);return r.has(d)||I.warn(`[workflow] conditional route from "${t}" returned "${d}" which is not in valid targets: ${[...r].join(", ")}`),d}}catch(a){throw new D(`Failed to compile conditionalCode for "${t}": ${a.message}`)}return s}function Kt(t,e,o={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new D(`Failed to compile customCode for node "${t}": ${s.message}`)}let i=n(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),ae));return a(...s)},typeof $e<"u"?$e:void 0,console),r=null;return o.outputSchema&&(r=o.outputSchema.jsonSchema||o.outputSchema),{name:t,_isCustomCode:!0,outputSchema:r,execute:async s=>{try{let a=await i(s);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 D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ie();var Ze=/^[a-z][a-z0-9_]{0,40}$/;function Ko(t){if(t==null)return[];if(!Array.isArray(t))return["stores must be an array of { name, description } objects"];let e=[],o=new Map;return t.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:r}=n;if(typeof r!="string"||r.length===0){e.push(`stores[${i}] is missing a string "name"`);return}Ze.test(r)||e.push(`stores[${i}] name "${r}" is invalid \u2014 must match ${Ze} (lowercase letter first, then up to 40 of [a-z0-9_])`),o.has(r)?e.push(`stores[${i}] duplicate store name "${r}" (also at index ${o.get(r)}) \u2014 store names must be unique within a workflow`):o.set(r,i)}),e}Oe();X();function Vo(t,e={}){let{nodes:o,edges:n,nodeConfigs:i={}}=t,r=new Set,s=[],a=new Map;for(let $ of o){let E=$.data?.nodeType||$.type;a.set($.id,E),E==="decision"?r.add($.id):s.push({id:$.id,nodeType:E,label:$.data?.label||$.id})}let c=s.some($=>{let E=i[$.id]||{};return!E.customCode&&!E.executeCode}),{toolsPerNode:u,toolIdsByVar:d}=rn(s,i),{simpleEdges:l,conditionalEdges:p}=sn(n,r),f=an(s,n,r),S=[],w=e.workflowType||"workflow";return S.push(Xo(e)),S.push(Qo(w,{usesRegisteredNodes:c})),S.push(en(d)),S.push(tn(w)),S.push(on(s,i)),S.push(nn(s,f,l,p,u,w)),S.filter(Boolean).join(`
|
|
51
51
|
`)}function qo(t){let e={};for(let[o,n]of Object.entries(t)){let{tools:i,...r}=n;Object.keys(r).length>0&&(e[o]=r)}return e}function Xo(t){let e=t.workflowType||"workflow";return["// Generated workflow",`// ${t.projectId?`Project: ${t.projectId} | `:""}Type: ${e} | Version: ${t.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
52
|
`)}function Qo(t,{usesRegisteredNodes:e=!0}={}){let o=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&o.push("// import './register-nodes.js'; // register custom node types here"),o.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),o.join(`
|
|
53
53
|
`)}function en(t){if(t.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[o,n]of t)e.push(`const ${o} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
|
|
@@ -56,4 +56,4 @@ ${r.join(`
|
|
|
56
56
|
`)}function nn(t,e,o,n,i,r){let s=["// \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"];s.push("export function buildGraph(options = {}) {"),s.push(" const graph = new WorkflowGraph(options);",""),s.push(" // Nodes");for(let c of t){let u=Vt(c.id);s.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${u}_execute });`),s.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}s.push("",` graph.setEntryPoint('${e}');`,""),(o.length>0||n.length>0)&&s.push(" // Edges");for(let c of o)s.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of n){let u=c.code.split(`
|
|
57
57
|
`).map((d,l)=>l===0?d:` ${d}`).join(`
|
|
58
58
|
`);s.push(` graph.addConditionalEdges('${c.source}', ${u});`)}let a=[];for(let c of t){let u=i.get(c.id);u&&a.push(` '${c.id}': ${u},`)}return a.length>0&&s.push(""," graph.resolvedToolsMap = {",...a," };"),s.push(""," return graph;","}",""),s.push("export { nodeConfigs };",""),s.join(`
|
|
59
|
-
`)}function rn(t,e){let o=new Map,n=new Map;for(let i of t){let r=e[i.id]?.tools,s;if(Array.isArray(r)&&r.length>0)s=[...r].sort();else{let a=_e[i.nodeType];a?.length>0&&(s=[...a].sort())}if(s){let a=`${s.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,a),n.has(a)||n.set(a,s)}}return{toolsPerNode:o,toolIdsByVar:n}}function sn(t,e){let o=[],n=[],i=new Map,r=new Set;for(let s of t)i.has(s.source)||i.set(s.source,[]),i.get(s.source).push(s);for(let s of t)if(!e.has(s.source))if(e.has(s.target)){if(r.has(s.target))continue;r.add(s.target);let c=(i.get(s.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);c&&n.push({source:s.source,code:c.data?.conditionalCode||c.conditionalCode})}else o.push({source:s.source,target:s.target});return{simpleEdges:o,conditionalEdges:n}}function an(t,e,o){let n=new Set;for(let r of e)o.has(r.target)||n.add(r.target);let i=t.find(r=>!n.has(r.id));return i?i.id:t[0]?.id}function Vt(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}F();export{Ne as AgentStrategy,ke as CI_ENV_VARS,
|
|
59
|
+
`)}function rn(t,e){let o=new Map,n=new Map;for(let i of t){let r=e[i.id]?.tools,s;if(Array.isArray(r)&&r.length>0)s=[...r].sort();else{let a=_e[i.nodeType];a?.length>0&&(s=[...a].sort())}if(s){let a=`${s.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,a),n.has(a)||n.set(a,s)}}return{toolsPerNode:o,toolIdsByVar:n}}function sn(t,e){let o=[],n=[],i=new Map,r=new Set;for(let s of t)i.has(s.source)||i.set(s.source,[]),i.get(s.source).push(s);for(let s of t)if(!e.has(s.source))if(e.has(s.target)){if(r.has(s.target))continue;r.add(s.target);let c=(i.get(s.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);c&&n.push({source:s.source,code:c.data?.conditionalCode||c.conditionalCode})}else o.push({source:s.source,target:s.target});return{simpleEdges:o,conditionalEdges:n}}function an(t,e,o){let n=new Set;for(let r of e)o.has(r.target)||n.add(r.target);let i=t.find(r=>!n.has(r.id));return i?i.id:t[0]?.id}function Vt(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}F();export{Ne as AgentStrategy,ke as CI_ENV_VARS,D as CompilationError,Q as ConditionalNode,le as ContextLoader,se as DEFAULT_OUTPUT_BASE,ho as EVENTS_FILE,_e as NODE_DEFAULT_TOOLS,go as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,j as Node,oe as OutputParser,fo as RAW_OUTPUT_FILE,po as RESULT_FILE,ve as SESSIONS_DIR,U as SESSION_INFO_FILE,ht as SKILLS,xe as STOP_REQUEST_FILE,Ze as STORE_NAME_REGEX,co as SchemaTypes,me as Timeline,ft as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ue as WorkflowGraph,te as WorkflowState,Ht as clearInheritedSessionEnvForFreshRun,wt as clearSkills,Ho as compileGraph,Fe as dispatchSubgraph,Yo as extractSteps,qo as generateNodeConfigsJson,Vo as generateWorkflowCode,Yt as generateWorkflowSessionId,Re as getAgentStrategy,St as getAllSkills,He as getNodeImpl,Je as getNodeTemplate,Ye as getResolvedToolDefinitions,q as getSkill,we as hasNode,mt as hasSkill,$t as invokeAgent,Uo as listNodeTypes,yt as listSkillIds,It as listStrategies,Wt as readPinnedSessionPathFromEnv,Zt as registerNode,gt as registerSkill,Et as registerStrategy,ze as resolveNodeTools,zt as resolveWorkflowSession,lo as setLogger,Ut as shouldTrustInheritedSessionEnv,Jt as syncProcessEnvToSession,x as timeline,Jo as validateGraphConfig,Ko as validateStoreDefs};
|
package/dist/node.js
CHANGED
|
@@ -29,6 +29,6 @@ ${Y}`,t.col=V))}return r(c,o,a)}}var C=class{constructor(){this._currentNode=nul
|
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(U,t):process.stdout.write.bind(process.stdout)(`${$} ${U} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=p.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(J,e):process.stdout.write.bind(process.stdout)(`${$} ${J} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(x,p.red(t)):process.stdout.write.bind(process.stdout)(`${$} ${x} ${p.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${dt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:a}=e;if(a)for(let c of a)this._rawWrite(`${W} ${c}`);let i=o?p.dim(` ${Z(o)}`):"";this._rawWrite(`${K} ${p.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:a}=o,i=a?p.dim(` ${Z(a)}`):"";this._rawWrite(`${x} ${p.red(e)}`),this._rawWrite(`${K} ${p.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(p.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},q=new C;var v=".session-info.json";var ht={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Nt=Object.freeze([ht.CODEBASE_MEMORY]);I.helpers.inc||I.registerHelper("inc",r=>Number(r)+1);I.helpers.json||I.registerHelper("json",r=>JSON.stringify(r,null,2));I.helpers.eq||I.registerHelper("eq",(r,t)=>r===t);var F=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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 k(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,a=s=>e&&typeof e.get=="function"?e.get(s):t?.[s];if(typeof this.customExecute=="function"){u.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let s=await this.customExecute(t);return typeof s=="object"&&s!==null&&s.success===!1?{success:!1,error:s.error||"Node execution failed",raw:s.raw||null}:this.isZodSchema?(u.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){return u.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&u.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),{success:!1,error:s.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=I.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let c=a("_skillHints");c&&(i=`${c}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${dt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:a}=e;if(a)for(let c of a)this._rawWrite(`${W} ${c}`);let i=o?p.dim(` ${Z(o)}`):"";this._rawWrite(`${K} ${p.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:a}=o,i=a?p.dim(` ${Z(a)}`):"";this._rawWrite(`${x} ${p.red(e)}`),this._rawWrite(`${K} ${p.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(p.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},q=new C;var v=".session-info.json";var ht={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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Nt=Object.freeze([ht.CODEBASE_MEMORY]);I.helpers.inc||I.registerHelper("inc",r=>Number(r)+1);I.helpers.json||I.registerHelper("json",r=>JSON.stringify(r,null,2));I.helpers.eq||I.registerHelper("eq",(r,t)=>r===t);var F=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)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 k(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,a=s=>e&&typeof e.get=="function"?e.get(s):t?.[s];if(typeof this.customExecute=="function"){u.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let s=await this.customExecute(t);return typeof s=="object"&&s!==null&&s.success===!1?{success:!1,error:s.error||"Node execution failed",raw:s.raw||null}:this.isZodSchema?(u.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){return u.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&u.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),{success:!1,error:s.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=I.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let c=a("_skillHints");c&&(i=`${c}
|
|
33
33
|
|
|
34
34
|
${i}`);let _=o(),d=_.cwd||process.cwd(),S=_.sessionPath;try{if(S){let s=D(S,v);if(st(s)){let h=JSON.parse(it(s,"utf-8"));h.currentNode=this.name,M(s,JSON.stringify(h,null,2),"utf-8")}let m=D(S,"..",v);if(st(m))try{let h=JSON.parse(it(m,"utf-8"));h.currentNode=this.name,M(m,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(s){u.debug(`[workflow] could not update session info: ${s.message}`)}let N=null;for(let s=0;s<=this.retries;s++)try{u.debug(`[workflow] node '${this.name}' attempt ${s}`);let m=o().config||{},h=m.agents||{},O=this.config.agent??h[this.name]??null,w={state:o()};O&&(w.preferredAgent=O);let b={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:S,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},E=t?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(ot(),rt))).invokeAgent);let f=await E(i,w,b),n,g;if(typeof f=="string"?(n=f,g=null):f.structured?(n=f.raw||JSON.stringify(f.structured,null,2),g=f.structured):(n=f.raw||JSON.stringify(f,null,2),g=f.extracted||null),S)try{let l=D(S,this.name,"raw_stream_output.txt");St(wt(l),{recursive:!0}),M(l,typeof n=="string"?n:JSON.stringify(n),"utf-8")}catch(l){u.debug(`[workflow] could not save raw output: ${l.message}`)}if(this.isZodSchema&&g){u.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let l=g;if(typeof this.onComplete=="function")try{l=await this.onComplete(o(),g)}catch(T){u.warn(`[workflow] onComplete hook failed: ${T.message}`)}return{success:!0,output:l,raw:n}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:n}),raw:n}}catch(l){throw new Error(`onComplete failed: ${l.message}`,{cause:l})}if(this.parser){let l=this.parser.parse(n);return u.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(l,null,2)}`),q.step("Output parsed"),{success:!0,output:l,raw:n}}return{success:!0,output:n,raw:n}}catch(m){N=m,s<this.retries&&u.info(`[workflow] node '${this.name}' failed, retrying (${s+1}/${this.retries})\u2026`)}return{success:!1,error:N.message,raw:null}}},nt=class extends F{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};export{nt as ConditionalNode,F as Node};
|