@zibby/agent-workflow 0.4.28 → 0.4.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.d.ts +0 -1
- package/dist/graph.js +19 -19
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +38 -38
- package/dist/node.d.ts +0 -10
- package/dist/node.js +12 -12
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ae=Object.defineProperty;var rt=(r,t)=>()=>(r&&(t=r(r=0)),t);var Mt=(r,t)=>{for(var e in t)Ae(r,e,{get:t[e],enumerable:!0})};var Dt,ve,nt,w,q=rt(()=>{Dt=()=>{},ve={debug:Dt,info:Dt,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},nt={impl:ve},w={debug:(...r)=>nt.impl.debug?.(...r),info:(...r)=>nt.impl.info?.(...r),warn:(...r)=>nt.impl.warn?.(...r),error:(...r)=>nt.impl.error?.(...r)}});var zt=rt(()=>{});var Kt={};Mt(Kt,{clearSkills:()=>Me,getAllSkills:()=>Be,getSkill:()=>mt,hasSkill:()=>Re,listSkillIds:()=>Ce,registerSkill:()=>Ne});function Ne(r){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");z.set(r.id,Object.freeze({...r}))}function mt(r){return z.get(r)||null}function Re(r){return z.has(r)}function Be(){return new Map(z)}function Ce(){return Array.from(z.keys())}function Me(){z.clear()}var gt,z,St=rt(()=>{gt=Symbol.for("@zibby/agent-workflow.skills");globalThis[gt]||(globalThis[gt]=new Map);z=globalThis[gt]});var _t={};Mt(_t,{getAgentStrategy:()=>qt,invokeAgent:()=>je,listStrategies:()=>Le,registerStrategy:()=>De});function De(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=U.findIndex(e=>e.getName()===r.getName());t>=0?U[t]=r:U.push(r)}function Le(){return U.map(r=>r.getName())}function qt(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let i=U.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}w.debug(`[workflow] agent selection: requested=${o}`);let s=U.find(i=>i.getName()===o);if(!s){let i=U.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return w.debug(`[workflow] using agent: ${s.getName()}`),s}async function je(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},s={...t,state:o},i=qt(s),n=o.config||e.config||{},c=n.models||{},l=e.nodeName&&c[e.nodeName]||null,u=c.default||null,p=n.agent?.[i.name]?.model||null,a=l||u||p||e.model||null,m={...e,model:a,workspace:o.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],plugins:e.plugins||t.plugins||[],config:n},h=r,$=m.skills||[];if($.length>0&&!e.skipPromptFragments){let I=$.map(f=>{let g=mt(f)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);I.length>0&&(h+=`
|
|
2
2
|
|
|
3
3
|
${I.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let T=o._currentNodeConfig?.stores;if(Array.isArray(T)&&T.length>0&&typeof T[0]=="object"){let I=T.length<=8,f=T.map(g=>{let d=g?.id??g?.storeId??"",y=(g?.name??"").toString().trim()||d,E=g?.type?` \xB7 ${g.type}`:"",_=(g?.description||"").toString().replace(/\s+/g," ").trim(),B=`- ${y} \xB7 ${_||"(no description)"}${E} (id: ${d})`;if(I&&g?.schema&&typeof g.schema=="object"){let S=g.schema.properties&&typeof g.schema.properties=="object"?Object.keys(g.schema.properties):Object.keys(g.schema);S.length&&(B+=`
|
|
6
|
+
fields: ${S.join(", ")}`)}return B});h+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${f.join(`
|
|
10
|
-
`)}`}let
|
|
10
|
+
`)}`}let v=o._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(h+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`),
|
|
16
|
+
${v}
|
|
17
|
+
`),w.debug(`[workflow] prompt length: ${h.length} chars`),i.invoke(h,m)}var yt,U,wt=rt(()=>{zt();q();St();yt=Symbol.for("@zibby/agent-workflow.strategies");globalThis[yt]||(globalThis[yt]=[]);U=globalThis[yt]});var ke=new Set(["__proto__","constructor","prototype"]);function pt(r){if(ke.has(r))throw new Error(`Invalid state key: "${r}"`)}var ot=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){pt(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let o of e)pt(o);this._history.push({...this._state});for(let o of e)this._state[o]=t[o]}append(t,e){pt(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import W from"handlebars";var st=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of o)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&s.type){let i=typeof t[o];i!==s.type&&e.push(`Field '${o}' expected ${s.type}, got ${i}`)}if(s.validate&&o in t){let i=s.validate(t[o]);i&&e.push(`Field '${o}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};
|
|
20
|
-
`?(
|
|
21
|
-
${
|
|
19
|
+
`)}`);return t}};q();import{writeFileSync as It,readFileSync as Vt,existsSync as Xt,mkdirSync as Ue}from"node:fs";import{join as Et,dirname as We}from"node:path";import O from"chalk";var Oe="__WORKFLOW_GRAPH_LOG__",V=O.gray("\u2502"),xe=O.gray("\u250C"),Lt=O.gray("\u2514"),dt=O.green("\u25C6"),jt=O.hex("#c084fc")("\u25C6"),Ut=O.hex("#2dd4bf")("\u25C6"),ft=O.red("\u25C6"),Wt=`${V} `,Gt=2;function Ft(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ht(r,t){return(e,o,s)=>{if(typeof e!="string")return r(e,o,s);let i=process.stdout.columns||120,n="";for(let c=0;c<e.length;c++){let l=e[c];t.lineStart&&(n+=Wt,t.col=Gt,t.lineStart=!1),l===`
|
|
20
|
+
`?(n+=l,t.lineStart=!0,t.col=0,t.inEsc=!1):l==="\x1B"?(t.inEsc=!0,n+=l):t.inEsc?(n+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(t.inEsc=!1)):(t.col++,n+=l,t.col>=i&&(n+=`
|
|
21
|
+
${Wt}`,t.col=Gt))}return r(n,o,s)}}var ht=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Ht(this._origStdoutWrite,t),process.stderr.write=Ht(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
24
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
24
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Oe}${JSON.stringify(t)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(t){let e=
|
|
31
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(dt,t):process.stdout.write.bind(process.stdout)(`${V} ${dt} ${t}
|
|
29
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(jt,t):process.stdout.write.bind(process.stdout)(`${V} ${jt} ${t}
|
|
30
|
+
`)}stepMemory(t){let e=O.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Ut,e):process.stdout.write.bind(process.stdout)(`${V} ${Ut} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ft,O.red(t)):process.stdout.write.bind(process.stdout)(`${V} ${ft} ${O.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${xe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let n of s)this._rawWrite(`${dt} ${n}`);let i=o?O.dim(` ${Ft(o)}`):"";this._rawWrite(`${Lt} ${O.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,i=s?O.dim(` ${Ft(s)}`):"";this._rawWrite(`${ft} ${O.red(e)}`),this._rawWrite(`${Lt} ${O.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(O.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},x=new ht;var it=".zibby/output",Jt="sessions",Z=".session-info.json",Yt=".zibby-stop";var Pe={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},$r=Object.freeze([Pe.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&&!t._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new st(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return w.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=a=>e&&typeof e.get=="function"?e.get(a):t?.[a];if(typeof this.customExecute=="function"){w.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let a=await this.customExecute(t);return typeof a=="object"&&a!==null&&a.success===!1?{success:!1,error:a.error||"Node execution failed",raw:a.raw||null}:this.isZodSchema?(w.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(a),raw:null}):{success:!0,output:a,raw:null}}catch(a){return w.error(`[workflow] node '${this.name}' failed: ${a.message}`),a.name==="ZodError"&&w.error(`Schema errors: ${JSON.stringify(a.issues||a.errors,null,2)}`),{success:!1,error:a.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let n=s("_skillHints");n&&(i=`${n}
|
|
33
33
|
|
|
34
|
-
${n}`);let c=o(),l=c.cwd||process.cwd(),p=c.sessionPath;try{if(p){let a=bt(p,Z);if(Qt(a)){let h=JSON.parse(Xt(a,"utf-8"));h.currentNode=this.name,Et(a,JSON.stringify(h,null,2),"utf-8")}let S=bt(p,"..",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(a){_.debug(`[workflow] could not update session info: ${a.message}`)}let d=null;for(let a=0;a<=this.retries;a++)try{_.debug(`[workflow] node '${this.name}' attempt ${a}`);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||[],plugins:this.config.plugins||[],sessionPath:p,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let f=await I(n,E,A),g,u;if(typeof f=="string"?(g=f,u=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),u=f.structured):(g=f.raw||JSON.stringify(f,null,2),u=f.extracted||null),p)try{let m=bt(p,this.name,"raw_stream_output.txt");We(Ge(m),{recursive:!0}),Et(m,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&u){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(u,null,2)}`);let m=u;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),u)}catch(P){_.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:m,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:g}),raw:g}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(g);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),v.step("Output parsed"),{success:!0,output:m,raw:g}}return{success:!0,output:g,raw:g}}catch(S){d=S,a<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${a+1}/${this.retries})\u2026`)}return{success:!1,error:d.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:c}=await import("node:fs"),l=i(s,"wx");c(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(c=>setTimeout(c,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,p)=>{let d=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),a=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(a.stdin);let S,h,b=()=>{if(S!==void 0&&h!==void 0){if(S!==0)return p(new Error(`curl exited ${S}`));if(h!==0)return p(new Error(`tar exited ${h}`));l()}};d.on("close",E=>{S=E,b()}),a.on("close",E=>{h=E,b()}),d.on("error",p),a.on("error",p)});let{writeFileSync:i,unlinkSync:c}=await import("node:fs");i(e,"");try{c(s)}catch{}}catch(i){try{let{unlinkSync:c}=await import("node:fs");c(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(u){throw u}_.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:c,sourcesPresignedUrl:l,workflowVersion:p,workflowUuid:d,bundleReady:a}=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(!a||!c)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 u=j(ct,`${d}@${p||"0"}`);try{await qe(c,u);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(u),re(r,h,{workflowUuid:d,version:p,runtimeTag:i,cacheDir:u})}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||{}},f,g;try{f=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})),g=f&&typeof f=="object"&&"state"in f?f.state:f}catch(u){throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:u.message,code:u.code||"CHILD_THREW",stack:u.stack},durationMs:Date.now()-b}}),u}if(f&&typeof f=="object"&&f.stoppedExternally){await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-b}});let u=new Error(`Sub-graph '${r}' canceled by parent abort`);throw u.code="SUBGRAPH_CANCELED",u.subgraphJobId=n,u}return await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-b}}),{finalState:g,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 c of t){let l=j(ct,c),p;try{p=ie(l)}catch{continue}let d=p.isDirectory()?Qe(l):p.size;o+=d,e.push({name:c,full:l,size:d,mtimeMs:p.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((c,l)=>c.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let c of e){if(o-n<=s)break;if(!F(j(c.full,".lock")))try{Ye(c.full,{recursive:!0,force:!0}),n+=c.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${c.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:u}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(u,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(u){if(u instanceof x||u?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let s=sr(),n=nr(),i=ir(),c=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:t.input||{},...c?{parentExecutionId:c}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${c||"<none>"}`);let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(p)});if(!d.ok){let u=null,m="";try{u=await d.json(),m=u?.error||u?.message||JSON.stringify(u)}catch{m=await d.text().catch(()=>"")}if(d.status===429){let T=u?.quotaInfo||{},C=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 C.code="SUBGRAPH_QUOTA_EXCEEDED",C.status=429,C.subgraph=r,C.quotaInfo=T,C}if(d.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=u?.validationErrors||null,T.missing=u?.missing||null,T}let P=new Error(`Sub-graph '${r}' trigger rejected (${d.status}): ${m}`);throw P.code="SUBGRAPH_TRIGGER_FAILED",P.status=d.status,P.subgraph=r,P}let a=await d.json(),S=a?.data?.jobId||a?.jobId;if(!S)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(a).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",f=0;for(;Date.now()<A;){await new Promise(T=>setTimeout(T,b)),f+=1;let u=await fetch(E,{headers:{Authorization:`Bearer ${i}`}});if(!u.ok){if(u.status>=500){_.warn(`[sub-graph] status poll for ${S} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${S}: ${u.status}`)}let m=await u.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||{},C=le(T,t.output);return _.info(`[sub-graph] '${r}' (${S}) completed after ${f} polls`),C}}let g=new Error(`Sub-graph '${r}' (${S}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw g.subgraphJobId=S,g.subgraphStatus=I,g}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as Ot,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 c=de(Ot(e,t));for(let l of n){let p=await this.findAndMergeContextFiles(l,c,e);if(p){let d=l.replace(/\.[^.]+$/,"").toLowerCase();s[d]=p}}}let i=o.discovery||{};for(let[c,l]of Object.entries(i))try{let p=Ot(e,l);pe(p)&&(s[c]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${c}' from '${l}': ${p.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=Ot(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 c=de(n);if(c===n)break;n=c}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
34
|
+
${i}`);let c=o(),l=c.cwd||process.cwd(),u=c.sessionPath;try{if(u){let a=Et(u,Z);if(Xt(a)){let h=JSON.parse(Vt(a,"utf-8"));h.currentNode=this.name,It(a,JSON.stringify(h,null,2),"utf-8")}let m=Et(u,"..",Z);if(Xt(m))try{let h=JSON.parse(Vt(m,"utf-8"));h.currentNode=this.name,It(m,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(a){w.debug(`[workflow] could not update session info: ${a.message}`)}let p=null;for(let a=0;a<=this.retries;a++)try{w.debug(`[workflow] node '${this.name}' attempt ${a}`);let m=o().config||{},h=m.agents||{},$=this.config.agent??h[this.name]??null,T={state:o()};$&&(T.preferredAgent=$);let v={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(wt(),_t))).invokeAgent);let f=await I(i,T,v),g,d;if(typeof f=="string"?(g=f,d=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),d=f.structured):(g=f.raw||JSON.stringify(f,null,2),d=f.extracted||null),u)try{let y=Et(u,this.name,"raw_stream_output.txt");Ue(We(y),{recursive:!0}),It(y,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(y){w.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&d){w.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(d,null,2)}`);let y=d;if(typeof this.onComplete=="function")try{y=await this.onComplete(o(),d)}catch(E){w.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:y,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{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 w.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(m){p=m,a<this.retries&&w.info(`[workflow] node '${this.name}' failed, retrying (${a+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}};q();q();import{mkdirSync as He,existsSync as F,statSync as ne,readdirSync as ie,rmSync as Je}from"node:fs";import{spawn as se}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ye}from"node:url";import{AsyncLocalStorage as Ge}from"node:async_hooks";var bt=new Ge;function X(){let r=bt.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 Qt(r,t){let e=bt.getStore()||X(),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 bt.run(o,t)}var $t=new Map,Tt=new Map,te=new Map;function ee(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");$t.set(r,t),Tt.set(r,"ready"),te.set(r,{...e,cachedAt:Date.now()})}function re(r,t){Tt.set(r,"failed"),te.set(r,{error:t?.message||String(t),failedAt:Date.now()}),$t.delete(r)}function oe(r){return Tt.get(r)==="ready"?$t.get(r):null}var at=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}};function ze(){let 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 P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Ke({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(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=s?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=i,n}if(o.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${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||w.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){w.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;He(t,{recursive:!0});let s=j(t,".lock"),i=!1;try{let{openSync:n,closeSync:c}=await import("node:fs"),l=n(s,"wx");c(l),i=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!i){let n=Date.now()+3e4;for(;Date.now()<n;){if(F(e)&&F(o))return;await new Promise(c=>setTimeout(c,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=se("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),a=se("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(a.stdin);let m,h,$=()=>{if(m!==void 0&&h!==void 0){if(m!==0)return u(new Error(`curl exited ${m}`));if(h!==0)return u(new Error(`tar exited ${h}`));l()}};p.on("close",T=>{m=T,$()}),a.on("close",T=>{h=T,$()}),p.on("error",u),a.on("error",u)});let{writeFileSync:n,unlinkSync:c}=await import("node:fs");n(e,"");try{c(s)}catch{}}catch(n){try{let{unlinkSync:c}=await import("node:fs");c(s)}catch{}throw new P("bundle-extract-failed",n.message)}}async function Ve(r){let t=j(r,"graph.mjs");if(!F(t))throw new P("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ye(t).href)}catch(s){throw new P("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 P("entry-class-missing","no buildGraph() class export found");return o}async function ae(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=X(),o;try{o=ze()}catch(E){throw E}w.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await Ke({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:n,bundlePresignedUrl:c,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:a,nodeConfigs:m}=s,h=Ze();if(n&&n!==h)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${h} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new P("runtime-mismatch",`${h} vs ${n}`);if(!a||!c)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new P("no-bundle","workflow bundle not built yet");let $=oe(r);if(!$){let E=j(at,`${p}@${u||"0"}`);try{await qe(c,E);try{Qe()}catch{}}catch(_){throw _.fallback&&await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason}}}),_}try{$=await Ve(E),ee(r,$,{workflowUuid:p,version:u,runtimeTag:n,cacheDir:E})}catch(_){throw re(r,_),await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:_.message,code:_.reason||"IMPORT_FAILED"}}}),_.fallback?_:new P("import-failed",_.message)}}let T=Date.now(),I=await(typeof $=="function"&&$.prototype?.buildGraph?new $:$).buildGraph(),f=m&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,g={...t.input||{},...f?{nodeConfigs:m}:{}},d,y;try{d=await Qt({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>I.run(t.parentAgent,g,{signal:t.signal})),y=d&&typeof d=="object"&&"state"in d?d.state:d}catch(E){throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.code||"CHILD_THREW",stack:E.stack},durationMs:Date.now()-T}}),E}if(d&&typeof d=="object"&&d.stoppedExternally){await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-T}});let E=new Error(`Sub-graph '${r}' canceled by parent abort`);throw E.code="SUBGRAPH_CANCELED",E.subgraphJobId=i,E}return await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-T}}),{finalState:y,executionId:i}}function Xe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ne(o)}catch{continue}if(s.isDirectory()){let i;try{i=ie(o)}catch{continue}for(let n of i)e.push(j(o,n))}else t+=s.size}return t}function Qe({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(at))return{evicted:0,freedBytes:0};let t=ie(at),e=[],o=0;for(let c of t){let l=j(at,c),u;try{u=ne(l)}catch{continue}let p=u.isDirectory()?Xe(l):u.size;o+=p,e.push({name:c,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((c,l)=>c.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),i=0,n=0;for(let c of e){if(o-i<=s)break;if(!F(j(c.full,".lock")))try{Je(c.full,{recursive:!0,force:!0}),i+=c.size,n+=1}catch(l){w.debug(`[sub-graph cache] evict skip ${c.name}: ${l.message}`)}}return n>0&&w.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:i,totalBytes:o-i}}catch(t){return w.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var tr=2e3,er=600*1e3,rr=new Set(["completed","failed","canceled","timeout"]);function or(){let 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 sr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function nr(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ir(){return process.env.EXECUTION_ID||null}function ce(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 le(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=X(),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{w.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:d}=await ae(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),y=ce(d,t.output);return w.info(`[sub-graph] '${r}' completed in-process`),y}catch(d){if(d instanceof P||d?.fallback)w.info(`[sub-graph] in-process fallback for '${r}': ${d.reason||"unknown"} \u2014 using HTTP`);else throw d}let s=or(),i=sr(),n=nr(),c=ir(),l=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...c?{parentExecutionId:c}:{},...t.conversationId?{conversationId:t.conversationId}:{}};w.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${c||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(u)});if(!p.ok){let d=null,y="";try{d=await p.json(),y=d?.error||d?.message||JSON.stringify(d)}catch{y=await p.text().catch(()=>"")}if(p.status===429){let _=d?.quotaInfo||{},B=new Error(`Sub-graph '${r}' blocked by execution quota (${_.used??"?"}/${_.limit??"?"} on plan ${_.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=_,B}if(p.status===400){let _=new Error(`Sub-graph '${r}' rejected input: ${y}`);throw _.code="SUBGRAPH_INVALID_INPUT",_.status=400,_.subgraph=r,_.validationErrors=d?.validationErrors||null,_.missing=d?.missing||null,_}let E=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${y}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=p.status,E.subgraph=r,E}let a=await p.json(),m=a?.data?.jobId||a?.jobId;if(!m)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(a).slice(0,200)}`);if(t.async)return w.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${m} (not waiting)`),{jobId:m,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:er,$=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:tr,T=`${s}/executions/${encodeURIComponent(m)}`,v=Date.now()+h,I="accepted",f=0;for(;Date.now()<v;){await new Promise(_=>setTimeout(_,$)),f+=1;let d=await fetch(T,{headers:{Authorization:`Bearer ${n}`}});if(!d.ok){if(d.status>=500){w.warn(`[sub-graph] status poll for ${m} returned ${d.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${m}: ${d.status}`)}let y=await d.json(),E=y?.data||y?.execution||y;if(I=E?.status||I,rr.has(I)){if(I!=="completed"){let S=new Error(`Sub-graph '${r}' (${m}) ended in status '${I}'`);throw S.subgraphJobId=m,S.subgraphStatus=I,S}let _=E?.finalState||E?.state||{},B=ce(_,t.output);return w.info(`[sub-graph] '${r}' (${m}) completed after ${f} polls`),B}}let g=new Error(`Sub-graph '${r}' (${m}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw g.subgraphJobId=m,g.subgraphStatus=I,g}import{existsSync as ue,readFileSync as ar}from"node:fs";import{join as At,dirname as pe}from"node:path";var ct=class{static async loadContext(t,e,o={}){let s={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let c=pe(At(e,t));for(let l of i){let u=await this.findAndMergeContextFiles(l,c,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let n=o.discovery||{};for(let[c,l]of Object.entries(n))try{let u=At(e,l);ue(u)&&(s[c]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${c}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],i=e;for(;i.startsWith(o);){let n=At(i,t);if(ue(n))try{s.unshift(await this.loadFile(n))}catch(l){console.warn(`[workflow] could not load ${t} from ${n}: ${l.message}`)}let c=pe(i);if(c===i)break;i=c}return s.length===0?null:s.every(n=>typeof n=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):s.every(
|
|
38
|
+
`):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=ar(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(t).href);return s.default||s}return e}};import{mkdirSync as ge,existsSync as kt,writeFileSync as de,unlinkSync as cr}from"node:fs";import{join as H,resolve as me}from"node:path";import{config as lr}from"dotenv";import{zodToJsonSchema as fe}from"zod-to-json-schema";import{z as lt}from"zod";import ur from"handlebars";function pr({traceFrom:r,sessionId:t,sessionPath:e,idSource:o,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",c=`[zibby:session] from=${r} pid=${process.pid} ppid=${n} sessionId=${t} source=${o} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(c),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let p=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
41
|
-
${d}`)}}function fr(){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 hr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Se(String(t).trim())}catch{return String(t).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Sr(r={}){let t=zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function yr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=Se(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,i="ZIBBY_SESSION_PATH")}catch{}let c;if(s)c=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)c=p,i="ZIBBY_SESSION_ID";else{let a=t.sessionId!=null?String(t.sessionId).trim():"";a&&a!=="last"?(c=a,i="config.sessionId"):(c=Sr(t),i="generated")}n=n??Date.now();let d=t.paths?.output||at;s=H(r,d,Yt,c)}let l=!kt(s);return l&&me(s,{recursive:!0}),(l||i!=="initialState.sessionPath")&&dr({traceFrom:o,sessionId:c,sessionPath:s,idSource:i,mkdirFresh:l}),mr({sessionPath:s,sessionId:c}),{sessionPath:s,sessionId:c,sessionTimestamp:n}}var ge=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let p=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,d;return typeof n.input=="function"?d=n.input(p):n.input&&typeof n.input=="object"?d=n.input:d={},ue(n.workflow,{input:d,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(p):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:p?._signal,parentAgent:l?.agent})}},c=new L(i);return c.name=t,this.nodes.set(t,c),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof L?e:new L(e);return s.name=t,this.nodes.set(t,s),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new X({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,n){let i=o;for(let c=t.length-1;c>=0;c--){let l=t[c],p=i;i=()=>l(e,p,s,n)}return i()}serialize(){let t=[],e={};for(let[d,a]of this.nodes){let S=this.nodeTypeMap.get(d)||(a instanceof X?"decision":d);t.push({id:d,type:S,data:{nodeType:S,label:d}});let h={};a._isCustomCode&&typeof a.execute=="function"&&(h.customCode=a.execute.toString());let b=typeof a?.config?.description=="string"&&a.config.description.trim()?a.config.description:typeof a?.description=="string"&&a.description.trim()?a.description:null;b&&(h.description=b);let E=this.nodePrompts.get(d);if(E)h.prompt=E;else if(typeof a.prompt=="function")try{let u=a.prompt({});typeof u=="string"&&u.trim()&&(h.prompt=u,h.promptIsCode=!0)}catch{}if(typeof a.customExecute=="function"&&(h.executeCode=a.customExecute.toString()),typeof a?.config?.dispatchesWorkflow=="string"&&a.config.dispatchesWorkflow.trim()&&(h.dispatchesWorkflow=a.config.dispatchesWorkflow.trim()),a.outputSchema)if(typeof a.outputSchema._def<"u"){let u=null;if(typeof ut?.toJSONSchema=="function")try{u=ut.toJSONSchema(a.outputSchema)}catch{}if(!u)try{u=he(a.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=u?{jsonSchema:u,variables:this._flattenJsonSchemaToVariables(u)}:{schema:a.outputSchema}}else h.outputSchema={schema:a.outputSchema};let A=(this.resolvedToolsMap||{})[d];A?.toolIds&&(h.tools=A.toolIds);let I=Array.isArray(a?.config?.skills)?a.config.skills:Array.isArray(a?.skills)?a.skills:null;I&&I.length>0&&(h.skills=[...I]);let f=Array.isArray(a?.config?.plugins)?a.config.plugins:Array.isArray(a?.plugins)?a.plugins:null;f&&f.length>0&&(h.plugins=f.map(u=>u&&typeof u=="object"?{...u}:u));let g=Array.isArray(a?.config?.stores)?a.config.stores:Array.isArray(a?.stores)?a.stores:null;g&&g.length>0&&(h.stores=g.map(u=>u&&typeof u=="object"?{...u}:u)),Object.keys(h).length>0&&(e[d]=h)}let o=[];for(let[d,a]of this.edges)if(typeof a=="string")o.push({source:d,target:a});else if(a.conditional){let S=this.conditionalCodeMap.get(d)||a.routes.toString(),h=this._inferConditionalTargets(a.routes,a.labels),b=a.labels||{};for(let E of h){let A={source:d,target:E,data:{conditionalCode:S}};b[E]&&(A.label=b[E]),o.push(A)}}let s=d=>{if(!d)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(d)}catch{}try{return he(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let n=0;for(let d of o)if(d.target==="END"){n+=1;let a=`END__${n}`;d.target=a,t.push({id:a,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){n+=1;let a=`END__${n}`;t.push({id:a,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:d,target:a})}let i=this._runtimeSchema(),c=s(i||this.stateSchema),l=s(this.inputSchema),p=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:c,inputSchema:l,contextSchema:p}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(o))!==null;){let p=i[2]!==void 0?i[2]:i[3];p!==void 0&&p!==""&&s.add(p)}let c=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())c.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))c.add(p);let l=new Set;for(let p of s)c.has(p)&&l.add(p);if(l.size===0){let p=/return\s+['"]([^'"]+)['"]/g,d;for(;(d=p.exec(o))!==null;)l.add(d[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},n=t.required||[];for(let[i,c]of Object.entries(s)){let l=e?`${e}.${i}`:i;o.push({path:l,type:c.type||"unknown",label:c.description||this._formatLabel(i),optional:!n.includes(i)}),c.type==="object"&&c.properties&&o.push(...this._flattenSchema(c,l)),c.type==="array"&&c.items?.type==="object"&&c.items.properties&&o.push(...this._flattenSchema(c.items,`${l}[]`))}return o}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,c=n.filter(p=>p?.passed===!0).length,l=n.some(p=>p?.passed!==void 0);o.push(l?`${s}: ${c}/${i} passed${i-c?`, ${i-c} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();ur({path:H(i,".env")});let c=e.config||{};if(!c||Object.keys(c).length===0)try{let w=H(i,".zibby.config.js");kt(w)&&(c=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!c.agent?.strictMode&&(c.agent={...c.agent,strictMode:!0});let l=e.agentType;if(!l){let w=c?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||c?.context||{},d=this._runtimeSchema();if(d){let w=d.safeParse(e);if(!w.success){let N=w.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}v.step("State validated against schema")}let a=hr(),S=e.sessionPath||a;S||gr();let{sessionPath:h,sessionTimestamp:b,sessionId:E}=yr({cwd:i,config:c,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:S,sessionTimestamp:e.sessionTimestamp}});v.step(`Session ${E}`);let A=await lt.loadContext(e.specPath||"",i,p);Object.keys(A).length>0&&v.step(`Context loaded: ${Object.keys(A).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new st({...e,config:c,agentType:l,outputPath:I,sessionPath:h,sessionTimestamp:b,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:u}=await Promise.resolve().then(()=>(yt(),Vt)),m=c.skills&&typeof c.skills=="object"?c.skills:{},P=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),T=w=>{for(let N of P)if(N.id===w)return N;return u(w)},C=new Set;for(let[,w]of this.nodes)for(let N of w.config?.skills||[])C.add(N);for(let w of C){let N=T(w);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&g.set(w,R)}catch{}}let y=this.entryPoint,tt=[],vt=c?.recursionLimit??100,ye=0;try{for(;y&&y!=="END";){if(++ye>vt)throw new Error(`Workflow exceeded recursion limit (${vt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(h,Zt);if(kt(N)){try{lr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
${p}`)}}function dr(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function fr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return me(String(t).trim())}catch{return String(t).trim()}}function hr(){dr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function gr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function mr(r={}){let t=Zt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function Sr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,i=e.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=me(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,n="ZIBBY_SESSION_PATH")}catch{}let c;if(s)c=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)c=u,n="ZIBBY_SESSION_ID";else{let a=t.sessionId!=null?String(t.sessionId).trim():"";a&&a!=="last"?(c=a,n="config.sessionId"):(c=mr(t),n="generated")}i=i??Date.now();let p=t.paths?.output||it;s=H(r,p,Jt,c)}let l=!kt(s);return l&&ge(s,{recursive:!0}),(l||n!=="initialState.sessionPath")&&pr({traceFrom:o,sessionId:c,sessionPath:s,idSource:n,mkdirFresh:l}),gr({sessionPath:s,sessionId:c}),{sessionPath:s,sessionId:c,sessionTimestamp:i}}var he=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,c={name:t,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async u=>{let p=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,a;return typeof n.input=="function"?a=n.input(p):n.input&&typeof n.input=="object"?a=n.input:a={},le(n.workflow,{input:a,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(p):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:p?._signal,parentAgent:u?.agent})}},l=new L(c);return l.name=t,this.nodes.set(t,l),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=!(e instanceof L)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof L?e:new L(s?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,i){let n=o;for(let c=t.length-1;c>=0;c--){let l=t[c],u=n;n=()=>l(e,u,s,i)}return n()}serialize(){let t=[],e={};for(let[p,a]of this.nodes){let m=this.nodeTypeMap.get(p)||(a?.config?._isRouter===!0?"decision":p);t.push({id:p,type:m,data:{nodeType:m,label:p}});let h={};a._isCustomCode&&typeof a.execute=="function"&&(h.customCode=a.execute.toString());let $=typeof a?.config?.description=="string"&&a.config.description.trim()?a.config.description:typeof a?.description=="string"&&a.description.trim()?a.description:null;$&&(h.description=$);let T=this.nodePrompts.get(p);if(T)h.prompt=T;else if(typeof a.prompt=="function")try{let d=a.prompt({});typeof d=="string"&&d.trim()&&(h.prompt=d,h.promptIsCode=!0)}catch{}if(typeof a.customExecute=="function"&&(h.executeCode=a.customExecute.toString()),typeof a?.config?.dispatchesWorkflow=="string"&&a.config.dispatchesWorkflow.trim()&&(h.dispatchesWorkflow=a.config.dispatchesWorkflow.trim()),a.outputSchema)if(typeof a.outputSchema._def<"u"){let d=null;if(typeof lt?.toJSONSchema=="function")try{d=lt.toJSONSchema(a.outputSchema)}catch{}if(!d)try{d=fe(a.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:a.outputSchema}}else h.outputSchema={schema:a.outputSchema};let v=(this.resolvedToolsMap||{})[p];v?.toolIds&&(h.tools=v.toolIds);let I=Array.isArray(a?.config?.skills)?a.config.skills:Array.isArray(a?.skills)?a.skills:null;I&&I.length>0&&(h.skills=[...I]);let f=Array.isArray(a?.config?.plugins)?a.config.plugins:Array.isArray(a?.plugins)?a.plugins:null;f&&f.length>0&&(h.plugins=f.map(d=>d&&typeof d=="object"?{...d}:d));let g=Array.isArray(a?.config?.stores)?a.config.stores:Array.isArray(a?.stores)?a.stores:null;g&&g.length>0&&(h.stores=g.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(h).length>0&&(e[p]=h)}let o=[];for(let[p,a]of this.edges)if(typeof a=="string")o.push({source:p,target:a});else if(a.conditional){let m=this.conditionalCodeMap.get(p)||a.routes.toString(),h=this._inferConditionalTargets(a.routes,a.labels),$=a.labels||{},T=this.nodes.get(p),v=T?.config?._isRouter===!0||this.nodeTypeMap.get(p)==="decision"||!T,I=p;if(!v){let f=`${p}__branch`;t.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),o.push({source:p,target:f}),I=f}for(let f of h){let g={source:I,target:f,data:{conditionalCode:m}};$[f]&&(g.label=$[f]),o.push(g)}}let s=p=>{if(!p)return null;if(typeof lt?.toJSONSchema=="function")try{return lt.toJSONSchema(p)}catch{}try{return fe(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let p of o)if(p.target==="END"){i+=1;let a=`END__${i}`;p.target=a,t.push({id:a,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){i+=1;let a=`END__${i}`;t.push({id:a,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:p,target:a})}let n=this._runtimeSchema(),c=s(n||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:c,inputSchema:l,contextSchema:u}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=i.exec(o))!==null;){let u=n[2]!==void 0?n[2]:n[3];u!==void 0&&u!==""&&s.add(u)}let c=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())c.add(u);if(e&&typeof e=="object")for(let u of Object.keys(e))c.add(u);let l=new Set;for(let u of s)c.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=u.exec(o))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},i=t.required||[];for(let[n,c]of Object.entries(s)){let l=e?`${e}.${n}`:n;o.push({path:l,type:c.type||"unknown",label:c.description||this._formatLabel(n),optional:!i.includes(n)}),c.type==="object"&&c.properties&&o.push(...this._flattenSchema(c,l)),c.type==="array"&&c.items?.type==="object"&&c.items.properties&&o.push(...this._flattenSchema(c.items,`${l}[]`))}return o}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,i]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)o.push(`${s}: ${i}`);else if(Array.isArray(i)){let n=i.length,c=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${c}/${n} passed${n-c?`, ${n-c} failed`:""}`:`${s}: ${n} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();lr({path:H(n,".env")});let c=e.config||{};if(!c||Object.keys(c).length===0)try{let b=H(n,".zibby.config.js");kt(b)&&(c=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!c.agent?.strictMode&&(c.agent={...c.agent,strictMode:!0});let l=e.agentType;if(!l){let b=c?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=e.contextConfig||t?.config?.contextConfig||t?.config?.context||c?.context||{},p=this._runtimeSchema();if(p){let b=p.safeParse(e);if(!b.success){let N=b.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}x.step("State validated against schema")}let a=fr(),m=e.sessionPath||a;m||hr();let{sessionPath:h,sessionTimestamp:$,sessionId:T}=Sr({cwd:n,config:c,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:m,sessionTimestamp:e.sessionTimestamp}});x.step(`Session ${T}`);let v=await ct.loadContext(e.specPath||"",n,u);Object.keys(v).length>0&&x.step(`Context loaded: ${Object.keys(v).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new ot({...e,config:c,agentType:l,outputPath:I,sessionPath:h,sessionTimestamp:$,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:d}=await Promise.resolve().then(()=>(St(),Kt)),y=c.skills&&typeof c.skills=="object"?c.skills:{},E=Object.values(y).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),_=b=>{for(let N of E)if(N.id===b)return N;return d(b)},B=new Set;for(let[,b]of this.nodes)for(let N of b.config?.skills||[])B.add(N);for(let b of B){let N=_(b);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&g.set(b,R)}catch{}}let S=this.entryPoint,Q=[],vt=c?.recursionLimit??100,Se=0;try{for(;S&&S!=="END";){if(++Se>vt)throw new Error(`Workflow exceeded recursion limit (${vt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(h,Yt);if(kt(N)){try{cr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:Q,stoppedExternally:!0};let R=this.nodes.get(S);if(!R)throw new Error(`Node '${S}' not found in graph`);let Ot=JSON.stringify({sessionPath:h,sessionTimestamp:$,currentNode:S,createdAt:new Date().toISOString(),config:f.get("config")}),ye=H(h,Z);de(ye,Ot,"utf-8");let xt=f.get("config")?.paths?.output||it,_e=H(n,xt,Z);ge(H(n,xt),{recursive:!0});try{de(_e,Ot,"utf-8")}catch{}let Pt=e.onPipelineProgress;if(typeof Pt=="function")try{Pt({cwd:n,sessionPath:h,sessionId:T,outputBase:f.get("config")?.paths?.output||it,currentNode:S})}catch{}let we=(this.resolvedToolsMap||{})[S]||null;f.set("_currentNodeTools",we);let Ie=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Ie[S]||{}),x.nodeStart(S);let Nt=Date.now(),tt=this.nodePrompts.get(S);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(wt(),_t));this._invokeAgent=k.invokeAgent}let Ee=this._invokeAgent,ut={},be=R.config?.skills||[];for(let k of be){let C=_(k);if(typeof C?.invokeAgentOptions=="function")try{let A=C.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:S});A&&typeof A=="object"&&(ut={...ut,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let Rt=async(k,C,A={})=>{let M=Ee(k,C,{...ut,...A,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((J,Y)=>{let D=()=>{setTimeout(()=>{let K=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);K.name="AbortError",Y(K)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},$e=async(k={},C={})=>{let A=C.prompt||"";if(tt){let M=this._compiledPrompts.get(S);M||(M=ur.compile(tt,{noEscape:!0}),this._compiledPrompts.set(S,M));try{A=M(k)}catch(J){throw console.error(`\u274C Template rendering failed for node '${S}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!A)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return Rt(A,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:s.signal})},Bt=f.getAll(),Te=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Te)Object.prototype.hasOwnProperty.call(Bt,k)&&console.warn(`[workflow] node "${S}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ct={...Bt,state:f,invokeAgent:$e,_coreInvokeAgent:Rt,agent:t,nodeId:S,promptTemplate:tt,getPromptTemplate:()=>tt};try{let k=(R.config?.skills||[]).map(D=>g.get(D)).filter(Boolean),C=[...this.middleware,...k],A;C.length>0?A=await this._composeMiddleware(C,S,async()=>R.execute(Ct,f),f.getAll(),f):A=await R.execute(Ct,f);let M=Date.now()-Nt;if(Q.push({node:S,success:A.success,duration:M,timestamp:new Date().toISOString()}),!A.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:Q,stoppedExternally:!0};f.append("errors",{node:S,error:A.error});let D=R.config?.retries||0,K=`${S}_retries`,et=f.getAll()[K]||0;if(et<D){x.stepInfo(`Retrying (attempt ${et+1}/${D})`),f.update({[K]:et+1,[`${S}_raw`]:A.raw});continue}throw x.nodeFailed(S,A.error,{duration:M}),new Error(`Node '${S}' failed after ${et} attempts: ${A.error}`)}f.update({[S]:A.output});let J=this._summarizeNodeOutput(S,A.output);x.nodeComplete(S,{duration:M,details:J});let Y=this.edges.get(S);if(!Y)S="END";else if(Y.conditional){let D=Y.routes(f.getAll());x.route(S,D),S=D}else S=Y}catch(k){throw x.isInsideNode&&x.nodeFailed(S,k.message,{duration:Date.now()-Nt}),f.set("failed",!0),f.set("failedAt",S),k}}x.graphComplete();let b={success:!0,state:f.getAll(),executionLog:Q};return t&&typeof t.onComplete=="function"&&await t.onComplete(b),b}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};export{he as WorkflowGraph,hr as clearInheritedSessionEnvForFreshRun,mr as generateWorkflowSessionId,fr as readPinnedSessionPathFromEnv,Sr as resolveWorkflowSession,dr as shouldTrustInheritedSessionEnv,gr as syncProcessEnvToSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as
|
|
1
|
+
import{mkdirSync as X,existsSync as I,statSync as N,readdirSync as C,rmSync as Y}from"node:fs";import{spawn as j}from"node:child_process";import{join as y}from"node:path";import{pathToFileURL as V}from"node:url";var R=()=>{},F={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k={impl:F};var E={debug:(...e)=>k.impl.debug?.(...e),info:(...e)=>k.impl.info?.(...e),warn:(...e)=>k.impl.warn?.(...e),error:(...e)=>k.impl.error?.(...e)};import{AsyncLocalStorage as J}from"node:async_hooks";var B=new J;function v(){let e=B.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function O(e,n){let r=B.getStore()||v(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null});return B.run(t,n)}var $=new Map,A=new Map,P=new Map;function D(e,n,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof n!="function")throw new Error("subgraph-registry.register: factory must be a function");$.set(e,n),A.set(e,"ready"),P.set(e,{...r,cachedAt:Date.now()})}function M(e,n){A.set(e,"failed"),P.set(e,{error:n?.message||String(n),failedAt:Date.now()}),$.delete(e)}function U(e){return A.get(e)==="ready"?$.get(e):null}var T=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function W(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var u=class extends Error{constructor(n,r){super(`in-process sub-graph fallback: ${n}${r?` (${r})`:""}`),this.fallback=!0,this.reason=n,this.detail=r||null,this.name="SubgraphFallback"}};function Z(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),n=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||n,t=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!r||!t||!s)throw new u("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:t,authToken:s}}async function K({apiBase:e,authToken:n,body:r}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)})}catch(o){throw new u("network",`begin fetch failed: ${o.message}`)}let s=null;try{s=await t.json()}catch{}if(!t.ok){if(t.status===404){let o=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(t.status===429){let o=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${o.used??"?"}/${o.limit??"?"} on ${o.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=o,a}if(t.status===400&&s?.validationErrors){let o=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=s.validationErrors,o.missing=s.missing,o}throw new u("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function x({apiBase:e,authToken:n,payload:r}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});t.ok||E.warn(`[in-process subgraph] finalize returned ${t.status} for ${r.childExecutionId}`)}catch(t){E.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function Q(e,n){let r=y(n,".ready"),t=y(n,"graph.mjs");if(I(r)&&I(t))return;X(n,{recursive:!0});let s=y(n,".lock"),o=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),d=a(s,"wx");i(d),o=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!o){let a=Date.now()+3e4;for(;Date.now()<a;){if(I(r)&&I(t))return;await new Promise(i=>setTimeout(i,100))}throw new u("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,l)=>{let g=j("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=j("tar",["-xzf","-","-C",n],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(S.stdin);let f,m,h=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return l(new Error(`curl exited ${f}`));if(m!==0)return l(new Error(`tar exited ${m}`));d()}};g.on("close",b=>{f=b,h()}),S.on("close",b=>{m=b,h()}),g.on("error",l),S.on("error",l)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(r,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new u("bundle-extract-failed",a.message)}}async function ee(e){let n=y(e,"graph.mjs");if(!I(n))throw new u("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(V(n).href)}catch(s){throw new u("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let t=r.default||Object.values(r).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!t)throw new u("entry-class-missing","no buildGraph() class export found");return t}async function pe(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=v(),t;try{t=Z()}catch(c){throw c}E.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await K({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:n.input||{},...n.conversationId?{conversationId:n.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:l,workflowUuid:g,bundleReady:S,nodeConfigs:f}=s,m=W();if(a&&a!==m)throw await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new u("runtime-mismatch",`${m} vs ${a}`);if(!S||!i)throw await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new u("no-bundle","workflow bundle not built yet");let h=U(e);if(!h){let c=y(T,`${g}@${l||"0"}`);try{await Q(i,c);try{te()}catch{}}catch(p){throw p.fallback&&await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:p.message,code:p.reason}}}),p}try{h=await ee(c),D(e,h,{workflowUuid:g,version:l,runtimeTag:a,cacheDir:c})}catch(p){throw M(e,p),await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:p.message,code:p.reason||"IMPORT_FAILED"}}}),p.fallback?p:new u("import-failed",p.message)}}let b=Date.now(),H=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),L=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,G={...n.input||{},...L?{nodeConfigs:f}:{}},w,_;try{w=await O({executionId:o,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>H.run(n.parentAgent,G,{signal:n.signal})),_=w&&typeof w=="object"&&"state"in w?w.state:w}catch(c){throw await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-b}}),c}if(w&&typeof w=="object"&&w.stoppedExternally){await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:_,durationMs:Date.now()-b}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await x({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:_,durationMs:Date.now()-b}}),{finalState:_,executionId:o}}function fe(){try{if(!I(T))return{bytes:0,entries:0};let e=C(T),n=0;for(let r of e)try{n+=z(y(T,r))}catch{}return{bytes:n,entries:e.length}}catch{return{bytes:0,entries:0}}}function z(e){let n=0,r=[e];for(;r.length;){let t=r.pop(),s;try{s=N(t)}catch{continue}if(s.isDirectory()){let o;try{o=C(t)}catch{continue}for(let a of o)r.push(y(t,a))}else n+=s.size}return n}function te({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!I(T))return{evicted:0,freedBytes:0};let n=C(T),r=[],t=0;for(let i of n){let d=y(T,i),l;try{l=N(d)}catch{continue}let g=l.isDirectory()?z(d):l.size;t+=g,r.push({name:i,full:d,size:g,mtimeMs:l.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};r.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let i of r){if(t-o<=s)break;if(!I(y(i.full,".lock")))try{Y(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){E.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&E.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:t-o}}catch(n){return E.debug(`[sub-graph cache] evict failed: ${n.message}`),{evicted:0,freedBytes:0}}}export{u as SubgraphFallback,te as evictCacheIfOver,fe as getCacheStats,pe as runInProcessSubgraph};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
export { dispatchSubgraph } from "./sub-graph-executor.js";
|
|
2
|
+
export { Node } from "./node.js";
|
|
2
3
|
export { WorkflowState } from "./state.js";
|
|
3
4
|
export { ContextLoader } from "./context-loader.js";
|
|
4
5
|
export { AgentStrategy } from "./agents/base.js";
|
|
5
6
|
export { setLogger } from "./logger.js";
|
|
6
7
|
export { WorkflowGraph, WorkflowGraph as Graph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
|
|
7
|
-
export { Node, ConditionalNode } from "./node.js";
|
|
8
8
|
export { OutputParser, SchemaTypes } from "./output-parser.js";
|
|
9
9
|
export { compileGraph, validateGraphConfig, extractSteps, CompilationError } from "./graph-compiler.js";
|
|
10
10
|
export { registerNode, getNodeImpl, hasNode, listNodeTypes, getNodeTemplate } from "./node-registry.js";
|