@zibby/agent-workflow 0.4.1 → 0.4.3
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/exec-context.d.ts +53 -0
- package/dist/exec-context.js +1 -0
- package/dist/graph-compiler.js +17 -17
- package/dist/graph.js +19 -19
- package/dist/in-process-subgraph.d.ts +59 -0
- package/dist/in-process-subgraph.js +1 -0
- package/dist/index.js +37 -37
- package/dist/sub-graph-executor.js +1 -1
- package/dist/subgraph-registry.d.ts +48 -0
- package/dist/subgraph-registry.js +1 -0
- package/package.json +1 -1
package/dist/graph.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _e=Object.defineProperty;var Q=(r,t)=>()=>(r&&(t=r(r=0)),t);var Rt=(r,t)=>{for(var e in t)_e(r,e,{get:t[e],enumerable:!0})};var Ct,Ie,rt,y,Y=Q(()=>{Ct=()=>{},Ie={debug:Ct,info:Ct,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},rt={impl:Ie},y={debug:(...r)=>rt.impl.debug?.(...r),info:(...r)=>rt.impl.info?.(...r),warn:(...r)=>rt.impl.warn?.(...r),error:(...r)=>rt.impl.error?.(...r)}});var Jt=Q(()=>{});var Yt={};Rt(Yt,{clearSkills:()=>ke,getAllSkills:()=>ve,getSkill:()=>dt,hasSkill:()=>Te,listSkillIds:()=>Ae,registerSkill:()=>$e});function $e(r){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");H.set(r.id,Object.freeze({...r}))}function dt(r){return H.get(r)||null}function Te(r){return H.has(r)}function ve(){return new Map(H)}function Ae(){return Array.from(H.keys())}function ke(){H.clear()}var pt,H,ht=Q(()=>{pt=Symbol.for("@zibby/agent-workflow.skills");globalThis[pt]||(globalThis[pt]=new Map);H=globalThis[pt]});var gt={};Rt(gt,{getAgentStrategy:()=>Zt,invokeAgent:()=>Pe,listStrategies:()=>Oe,registerStrategy:()=>xe});function xe(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=D.findIndex(e=>e.getName()===r.getName());t>=0?D[t]=r:D.push(r)}function Oe(){return D.map(r=>r.getName())}function Zt(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let n=D.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}y.debug(`[workflow] agent selection: requested=${o}`);let s=D.find(n=>n.getName()===o);if(!s){let n=D.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${n}`)}if(!s.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return y.debug(`[workflow] using agent: ${s.getName()}`),s}async function Pe(r,t={},e={}){let o=Zt(t),s=t.state?.config||e.config||{},n=s.models||{},i=e.nodeName&&n[e.nodeName]||null,a=n.default||null,c=s.agent?.[o.name]?.model||null,l=i||a||c||e.model||null,p={...e,model:l,workspace:t.state?.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:s},h=r,f=p.skills||[];if(f.length>0&&!e.skipPromptFragments){let I=f.map(g=>{let $=dt(g)?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);I.length>0&&(h+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${I.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let m=t.state?._currentNodeConfig?.extraPromptInstructions?.trim();return m&&(h+=`
|
|
6
6
|
|
|
7
7
|
\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
|
|
8
8
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
9
9
|
\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
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`),
|
|
11
|
+
${m}
|
|
12
|
+
`),y.debug(`[workflow] prompt length: ${h.length} chars`),o.invoke(h,p)}var ft,D,mt=Q(()=>{Jt();Y();ht();ft=Symbol.for("@zibby/agent-workflow.strategies");globalThis[ft]||(globalThis[ft]=[]);D=globalThis[ft]});var ye=new Set(["__proto__","constructor","prototype"]);function at(r){if(ye.has(r))throw new Error(`Invalid state key: "${r}"`)}var tt=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){at(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let o of e)at(o);this._history.push({...this._state});for(let o of e)this._state[o]=t[o]}append(t,e){at(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())}};var et=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(n){if(!(n instanceof SyntaxError))throw n}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 n=typeof t[o];n!==s.type&&e.push(`Field '${o}' expected ${s.type}, got ${n}`)}if(s.validate&&o in t){let n=s.validate(t[o]);n&&e.push(`Field '${o}': ${n}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
13
13
|
${e.join(`
|
|
14
|
-
`)}`);return t}};
|
|
15
|
-
`?(
|
|
16
|
-
${
|
|
14
|
+
`)}`);return t}};Y();import{writeFileSync as St,readFileSync as zt,existsSync as Kt,mkdirSync as Ne}from"node:fs";import{join as wt,dirname as Re}from"node:path";import T from"chalk";var Ee="__WORKFLOW_GRAPH_LOG__",Z=T.gray("\u2502"),be=T.gray("\u250C"),Bt=T.gray("\u2514"),ct=T.green("\u25C6"),Mt=T.hex("#c084fc")("\u25C6"),Dt=T.hex("#2dd4bf")("\u25C6"),lt=T.red("\u25C6"),Lt=`${Z} `,jt=2;function Ut(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Wt(r,t){return(e,o,s)=>{if(typeof e!="string")return r(e,o,s);let n=process.stdout.columns||120,i="";for(let a=0;a<e.length;a++){let c=e[a];t.lineStart&&(i+=Lt,t.col=jt,t.lineStart=!1),c===`
|
|
15
|
+
`?(i+=c,t.lineStart=!0,t.col=0,t.inEsc=!1):c==="\x1B"?(t.inEsc=!0,i+=c):t.inEsc?(i+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(t.inEsc=!1)):(t.col++,i+=c,t.col>=n&&(i+=`
|
|
16
|
+
${Lt}`,t.col=jt))}return r(i,o,s)}}var ut=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=Wt(this._origStdoutWrite,t),process.stderr.write=Wt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
17
17
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
18
18
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
19
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
19
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${Ee}${JSON.stringify(t)}
|
|
20
20
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
21
21
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
22
22
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
23
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(
|
|
24
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(
|
|
25
|
-
`)}stepMemory(t){let e=
|
|
26
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(
|
|
27
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
23
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(ct,t):process.stdout.write.bind(process.stdout)(`${Z} ${ct} ${t}
|
|
24
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Mt,t):process.stdout.write.bind(process.stdout)(`${Z} ${Mt} ${t}
|
|
25
|
+
`)}stepMemory(t){let e=T.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Dt,e):process.stdout.write.bind(process.stdout)(`${Z} ${Dt} ${e}
|
|
26
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(lt,T.red(t)):process.stdout.write.bind(process.stdout)(`${Z} ${lt} ${T.red(t)}
|
|
27
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${be} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ct} ${i}`);let n=o?T.dim(` ${Ut(o)}`):"";this._rawWrite(`${Bt} ${T.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?T.dim(` ${Ut(s)}`):"";this._rawWrite(`${lt} ${T.red(e)}`),this._rawWrite(`${Bt} ${T.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(T.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},v=new ut;var st=".zibby/output",Ft="sessions",G=".session-info.json",Gt=".zibby-stop";var Ht=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var M=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 et(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=h=>e&&typeof e.get=="function"?e.get(h):t?.[h];if(typeof this.customExecute=="function"){y.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let h=await this.customExecute(t);return typeof h=="object"&&h!==null&&h.success===!1?{success:!1,error:h.error||"Node execution failed",raw:h.raw||null}:this.isZodSchema?(y.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(h),raw:null}):{success:!0,output:h,raw:null}}catch(h){return y.error(`[workflow] node '${this.name}' failed: ${h.message}`),h.name==="ZodError"&&y.error(`Schema errors: ${JSON.stringify(h.issues||h.errors,null,2)}`),{success:!1,error:h.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(o()):this.prompt,i=s("_skillHints");i&&(n=`${i}
|
|
28
28
|
|
|
29
|
-
${n}`);let i=o(),c=i.cwd||process.cwd(),l=i.sessionPath;try{if(l){let d=ft(l,F);if(Ft(d)){let _=JSON.parse(Dt(d,"utf-8"));_.currentNode=this.name,ht(d,JSON.stringify(_,null,2),"utf-8")}let g=ft(l,"..",F);if(Ft(g))try{let _=JSON.parse(Dt(g,"utf-8"));_.currentNode=this.name,ht(g,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(d){I.debug(`[workflow] could not update session info: ${d.message}`)}let p=null;for(let d=0;d<=this.retries;d++)try{I.debug(`[workflow] node '${this.name}' attempt ${d}`);let g=o().config||{},_=g.agents||{},$=this.config.agent??_[this.name]??null,w={state:o()};$&&(w.preferredAgent=$);let N={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:g,nodeName:this.name,timeout:this.config?.timeout||3e5},P=t?._coreInvokeAgent;P||(P=(await Promise.resolve().then(()=>(dt(),pt))).invokeAgent);let u=await P(n,w,N),S,E;if(typeof u=="string"?(S=u,E=null):u.structured?(S=u.raw||JSON.stringify(u.structured,null,2),E=u.structured):(S=u.raw||JSON.stringify(u,null,2),E=u.extracted||null),l)try{let h=ft(l,this.name,"raw_stream_output.txt");ge(Se(h),{recursive:!0}),ht(h,typeof S=="string"?S:JSON.stringify(S),"utf-8")}catch(h){I.debug(`[workflow] could not save raw output: ${h.message}`)}if(this.isZodSchema&&E){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(E,null,2)}`);let h=E;if(typeof this.onComplete=="function")try{h=await this.onComplete(o(),E)}catch(R){I.warn(`[workflow] onComplete hook failed: ${R.message}`)}return{success:!0,output:h,raw:S}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:S}),raw:S}}catch(h){throw new Error(`onComplete failed: ${h.message}`,{cause:h})}if(this.parser){let h=this.parser.parse(S);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(h,null,2)}`),v.step("Output parsed"),{success:!0,output:h,raw:S}}return{success:!0,output:S,raw:S}}catch(g){p=g,d<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},tt=class extends M{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}}};X();var _e=2e3,we=600*1e3,ye=new Set(["completed","failed","canceled","timeout"]);function Ie(){let s=process.env.PROGRESS_API_URL;if(!s)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return s.replace(/\/executions\/?$/,"")}function Ee(){let s=process.env.PROJECT_ID;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return s}function $e(){let s=process.env.PROJECT_API_TOKEN;if(!s)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return s}function be(){return process.env.EXECUTION_ID||null}function ve(s,t){return t==null?s:typeof t=="function"?t(s):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],s):s}async function Ut(s,t={}){if(!s||typeof s!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Ie(),o=Ee(),r=$e(),n=be(),a=`${e}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(s)}/trigger`,i={input:t.input||{},...n?{parentExecutionId:n}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${s}' (${t.async?"async":"sync"}) from parent ${n||"<none>"}`);let c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(i)});if(!c.ok){let u=null,S="";try{u=await c.json(),S=u?.error||u?.message||JSON.stringify(u)}catch{S=await c.text().catch(()=>"")}if(c.status===429){let h=u?.quotaInfo||{},R=new Error(`Sub-graph '${s}' blocked by execution quota (${h.used??"?"}/${h.limit??"?"} on plan ${h.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=s,R.quotaInfo=h,R}if(c.status===400){let h=new Error(`Sub-graph '${s}' rejected input: ${S}`);throw h.code="SUBGRAPH_INVALID_INPUT",h.status=400,h.subgraph=s,h.validationErrors=u?.validationErrors||null,h.missing=u?.missing||null,h}let E=new Error(`Sub-graph '${s}' trigger rejected (${c.status}): ${S}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=c.status,E.subgraph=s,E}let l=await c.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${s}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${s}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:s};let d=Number.isFinite(t.timeoutMs)?t.timeoutMs:we,g=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:_e,_=`${e}/executions/${encodeURIComponent(p)}`,$=Date.now()+d,w="accepted",N=0;for(;Date.now()<$;){await new Promise(h=>setTimeout(h,g)),N+=1;let u=await fetch(_,{headers:{Authorization:`Bearer ${r}`}});if(!u.ok){if(u.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${u.status}`)}let S=await u.json(),E=S?.data||S?.execution||S;if(w=E?.status||w,ye.has(w)){if(w!=="completed"){let W=new Error(`Sub-graph '${s}' (${p}) ended in status '${w}'`);throw W.subgraphJobId=p,W.subgraphStatus=w,W}let h=E?.finalState||E?.state||{},R=ve(h,t.output);return I.info(`[sub-graph] '${s}' (${p}) completed after ${N} polls`),R}}let P=new Error(`Sub-graph '${s}' (${p}) timed out after ${Math.round(d/1e3)}s (last status: ${w})`);throw P.subgraphJobId=p,P.subgraphStatus=w,P}import{existsSync as Jt,readFileSync as Te}from"node:fs";import{join as mt,dirname as Yt}from"node:path";var et=class{static async loadContext(t,e,o={}){let r={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let i=Yt(mt(e,t));for(let c of n){let l=await this.findAndMergeContextFiles(c,i,e);if(l){let p=c.replace(/\.[^.]+$/,"").toLowerCase();r[p]=l}}}let a=o.discovery||{};for(let[i,c]of Object.entries(a))try{let l=mt(e,c);Jt(l)&&(r[i]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${i}' from '${c}': ${l.message}`)}return r}static async findAndMergeContextFiles(t,e,o){let r=[],n=e;for(;n.startsWith(o);){let a=mt(n,t);if(Jt(a))try{r.unshift(await this.loadFile(a))}catch(c){console.warn(`[workflow] could not load ${t} from ${a}: ${c.message}`)}let i=Yt(n);if(i===n)break;n=i}return r.length===0?null:r.every(a=>typeof a=="string")?r.join(`
|
|
29
|
+
${n}`);let a=o(),c=a.cwd||process.cwd(),l=a.sessionPath;try{if(l){let h=wt(l,G);if(Kt(h)){let m=JSON.parse(zt(h,"utf-8"));m.currentNode=this.name,St(h,JSON.stringify(m,null,2),"utf-8")}let f=wt(l,"..",G);if(Kt(f))try{let m=JSON.parse(zt(f,"utf-8"));m.currentNode=this.name,St(f,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(h){y.debug(`[workflow] could not update session info: ${h.message}`)}let p=null;for(let h=0;h<=this.retries;h++)try{y.debug(`[workflow] node '${this.name}' attempt ${h}`);let f=o().config||{},m=f.agents||{},I=this.config.agent??m[this.name]??null,g={state:o()};I&&(g.preferredAgent=I);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:f,nodeName:this.name,timeout:this.config?.timeout||3e5},N=t?._coreInvokeAgent;N||(N=(await Promise.resolve().then(()=>(mt(),gt))).invokeAgent);let u=await N(n,g,$),w,E;if(typeof u=="string"?(w=u,E=null):u.structured?(w=u.raw||JSON.stringify(u.structured,null,2),E=u.structured):(w=u.raw||JSON.stringify(u,null,2),E=u.extracted||null),l)try{let d=wt(l,this.name,"raw_stream_output.txt");Ne(Re(d),{recursive:!0}),St(d,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(d){y.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&E){y.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(E,null,2)}`);let d=E;if(typeof this.onComplete=="function")try{d=await this.onComplete(o(),E)}catch(C){y.warn(`[workflow] onComplete hook failed: ${C.message}`)}return{success:!0,output:d,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:w}),raw:w}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(w);return y.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),v.step("Output parsed"),{success:!0,output:d,raw:w}}return{success:!0,output:w,raw:w}}catch(f){p=f,h<this.retries&&y.info(`[workflow] node '${this.name}' failed, retrying (${h+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},ot=class extends M{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}}};Y();Y();import{mkdirSync as Me,existsSync as z,statSync as Nr}from"node:fs";import{spawn as ee}from"node:child_process";import{join as K}from"node:path";import{pathToFileURL as De}from"node:url";import{AsyncLocalStorage as Ce}from"node:async_hooks";var _t=new Ce;function yt(){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 qt(r,t){let e=_t.getStore()||yt(),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 It=new Map,Et=new Map,Vt=new Map;function Xt(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");It.set(r,t),Et.set(r,"ready"),Vt.set(r,{...e,cachedAt:Date.now()})}function Qt(r,t){Et.set(r,"failed"),Vt.set(r,{error:t?.message||String(t),failedAt:Date.now()}),It.delete(r)}function te(r){return Et.get(r)==="ready"?It.get(r):null}var Le=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function je(){return Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10)}function Ue(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var A=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 We(){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 A("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Fe({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 A("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 A("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function L({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||y.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){y.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function Ge(r,t){let e=K(t,".ready"),o=K(t,"graph.mjs");if(z(e)&&z(o))return;Me(t,{recursive:!0});let s=K(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),c=i(s,"wx");a(c),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(z(e)&&z(o))return;await new Promise(a=>setTimeout(a,100))}throw new A("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,l)=>{let p=ee("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),h=ee("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(h.stdin);let f,m,I=()=>{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}`));c()}};p.on("close",g=>{f=g,I()}),h.on("close",g=>{m=g,I()}),p.on("error",l),h.on("error",l)});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 A("bundle-extract-failed",i.message)}}async function He(r){let t=K(r,"graph.mjs");if(!z(t))throw new A("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(De(t).href)}catch(s){throw new A("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 A("entry-class-missing","no buildGraph() class export found");return o}async function re(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=yt(),o=je();if((e.depth||0)>=o)throw new A("depth-exceeded",`depth ${e.depth} \u2265 MAX_DEPTH ${o}`);let s;try{s=We()}catch(d){throw d}y.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let n=await Fe({apiBase:s.apiBase,authToken:s.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:a,bundlePresignedUrl:c,sourcesPresignedUrl:l,workflowVersion:p,workflowUuid:h,bundleReady:f}=n,m=Ue();if(a&&a!==m)throw await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new A("runtime-mismatch",`${m} vs ${a}`);if(!f||!c)throw await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new A("no-bundle","workflow bundle not built yet");let I=K(Le,`${h}@${p||"0"}`);try{await Ge(c,I)}catch(d){throw d.fallback&&await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.reason}}}),d}let g=te(r);if(!g)try{g=await He(I),Xt(r,g,{workflowUuid:h,version:p,runtimeTag:a,cacheDir:I})}catch(d){throw Qt(r,d),await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.reason||"IMPORT_FAILED"}}}),d.fallback?d:new A("import-failed",d.message)}let $=Date.now(),u=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph(),w={...t.input||{}},E;try{E=await qt({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>u.run(t.parentAgent,w,{signal:t.signal}))}catch(d){throw await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-$}}),d}if(E?.stoppedExternally){await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"canceled",finalState:E,durationMs:Date.now()-$}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await L({apiBase:s.apiBase,authToken:s.authToken,payload:{childExecutionId:i,status:"completed",finalState:E,durationMs:Date.now()-$}}),{finalState:E,executionId:i}}var Je=2e3,Ye=600*1e3,Ze=new Set(["completed","failed","canceled","timeout"]);function ze(){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 Ke(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function qe(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function Ve(){return process.env.EXECUTION_ID||null}function se(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 oe(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{y.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:u}=await re(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),w=se(u,t.output);return y.info(`[sub-graph] '${r}' completed in-process`),w}catch(u){if(u instanceof A||u?.fallback)y.info(`[sub-graph] in-process fallback for '${r}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let e=ze(),o=Ke(),s=qe(),n=Ve(),i=`${e}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(r)}/trigger`,a={input:t.input||{},...n?{parentExecutionId:n}:{},...t.conversationId?{conversationId:t.conversationId}:{}};y.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${n||"<none>"}`);let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(a)});if(!c.ok){let u=null,w="";try{u=await c.json(),w=u?.error||u?.message||JSON.stringify(u)}catch{w=await c.text().catch(()=>"")}if(c.status===429){let d=u?.quotaInfo||{},C=new Error(`Sub-graph '${r}' blocked by execution quota (${d.used??"?"}/${d.limit??"?"} on plan ${d.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=d,C}if(c.status===400){let d=new Error(`Sub-graph '${r}' rejected input: ${w}`);throw d.code="SUBGRAPH_INVALID_INPUT",d.status=400,d.subgraph=r,d.validationErrors=u?.validationErrors||null,d.missing=u?.missing||null,d}let E=new Error(`Sub-graph '${r}' trigger rejected (${c.status}): ${w}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=c.status,E.subgraph=r,E}let l=await c.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(t.async)return y.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:Ye,f=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:Je,m=`${e}/executions/${encodeURIComponent(p)}`,I=Date.now()+h,g="accepted",$=0;for(;Date.now()<I;){await new Promise(d=>setTimeout(d,f)),$+=1;let u=await fetch(m,{headers:{Authorization:`Bearer ${s}`}});if(!u.ok){if(u.status>=500){y.warn(`[sub-graph] status poll for ${p} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${u.status}`)}let w=await u.json(),E=w?.data||w?.execution||w;if(g=E?.status||g,Ze.has(g)){if(g!=="completed"){let U=new Error(`Sub-graph '${r}' (${p}) ended in status '${g}'`);throw U.subgraphJobId=p,U.subgraphStatus=g,U}let d=E?.finalState||E?.state||{},C=se(d,t.output);return y.info(`[sub-graph] '${r}' (${p}) completed after ${$} polls`),C}}let N=new Error(`Sub-graph '${r}' (${p}) timed out after ${Math.round(h/1e3)}s (last status: ${g})`);throw N.subgraphJobId=p,N.subgraphStatus=g,N}import{existsSync as ne,readFileSync as Xe}from"node:fs";import{join as bt,dirname as ie}from"node:path";var nt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=ie(bt(e,t));for(let c of n){let l=await this.findAndMergeContextFiles(c,a,e);if(l){let p=c.replace(/\.[^.]+$/,"").toLowerCase();s[p]=l}}}let i=o.discovery||{};for(let[a,c]of Object.entries(i))try{let l=bt(e,c);ne(l)&&(s[a]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${a}' from '${c}': ${l.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=bt(n,t);if(ne(i))try{s.unshift(await this.loadFile(i))}catch(c){console.warn(`[workflow] could not load ${t} from ${i}: ${c.message}`)}let a=ie(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
30
30
|
|
|
31
31
|
---
|
|
32
32
|
|
|
33
|
-
`):
|
|
33
|
+
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=Xe(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 ue,existsSync as $t,writeFileSync as ae,unlinkSync as Qe}from"node:fs";import{join as j,resolve as pe}from"node:path";import{config as tr}from"dotenv";import{zodToJsonSchema as ce}from"zod-to-json-schema";import er from"handlebars";function rr({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 i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${i} sessionId=${t} source=${o} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let p=(new Error("session trace").stack||"").split(`
|
|
34
34
|
`).slice(2,14).join(`
|
|
35
|
-
`);console.log(`[zibby:session] stack (${
|
|
36
|
-
${p}`)}}function
|
|
37
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),v.step("Workflow stopped externally"),{success:!0,state:u.getAll(),executionLog:
|
|
35
|
+
`);console.log(`[zibby:session] stack (${r}):
|
|
36
|
+
${p}`)}}function sr(){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 or(){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 pe(String(t).trim())}catch{return String(t).trim()}}function nr(){sr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function ir({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 ar(r={}){let t=Ht.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 cr({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 l=pe(String(process.env.ZIBBY_SESSION_PATH));l&&(s=l,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let l=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(l)a=l,i="ZIBBY_SESSION_ID";else{let h=t.sessionId!=null?String(t.sessionId).trim():"";h&&h!=="last"?(a=h,i="config.sessionId"):(a=ar(t),i="generated")}n=n??Date.now();let p=t.paths?.output||st;s=j(r,p,Ft,a)}let c=!$t(s);return c&&ue(s,{recursive:!0}),(c||i!=="initialState.sessionPath")&&rr({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:c}),ir({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var le=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{return this.inputSchema.merge(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(t,e,o={}){if(!(e instanceof M)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async c=>{let l=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,p;return typeof n.input=="function"?p=n.input(l):n.input&&typeof n.input=="object"?p=n.input:p={},oe(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(l):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:l?._signal,parentAgent:c?.agent})}},a=new M(i);return a.name=t,this.nodes.set(t,a),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof M?e:new M(e);return s.name=t,this.nodes.set(t,s),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new ot({...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 a=t.length-1;a>=0;a--){let c=t[a],l=i;i=()=>c(e,l,s,n)}return i()}serialize(){let t=[],e={};for(let[l,p]of this.nodes){let h=this.nodeTypeMap.get(l)||l;t.push({id:l,type:h,data:{nodeType:h,label:l}});let f={};p._isCustomCode&&typeof p.execute=="function"&&(f.customCode=p.execute.toString());let m=this.nodePrompts.get(l);if(m&&(f.prompt=m),typeof p.customExecute=="function"&&(f.executeCode=p.customExecute.toString()),p.outputSchema)try{if(typeof p.outputSchema._def<"u"){let $=ce(p.outputSchema,{target:"openApi3"});f.outputSchema={jsonSchema:$,variables:this._flattenJsonSchemaToVariables($)}}else f.outputSchema={schema:p.outputSchema}}catch($){console.warn(`[workflow] failed to convert schema for ${l}:`,$.message)}let I=(this.resolvedToolsMap||{})[l];I?.toolIds&&(f.tools=I.toolIds);let g=Array.isArray(p?.config?.skills)?p.config.skills:Array.isArray(p?.skills)?p.skills:null;g&&g.length>0&&(f.skills=[...g]),Object.keys(f).length>0&&(e[l]=f)}let o=[];for(let[l,p]of this.edges)if(typeof p=="string")o.push({source:l,target:p});else if(p.conditional){let h=this.conditionalCodeMap.get(l)||p.routes.toString(),f=this._inferConditionalTargets(p.routes),m=p.labels||{};for(let I of f){let g={source:l,target:I,data:{conditionalCode:h}};m[I]&&(g.label=m[I]),o.push(g)}}let s=l=>{if(!l)return null;try{return ce(l,{target:"openApi3"})}catch{return null}},n=this._runtimeSchema(),i=s(n||this.stateSchema),a=s(this.inputSchema),c=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:i,inputSchema:a,contextSchema:c}}_inferConditionalTargets(t){let e=t.toString(),o=new Set,s=/return\s+['"]([^'"]+)['"]/g,n;for(;(n=s.exec(e))!==null;)o.add(n[1]);return[...o]}_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,a]of Object.entries(s)){let c=e?`${e}.${i}`:i;o.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!n.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${c}[]`))}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,a=n.filter(l=>l?.passed===!0).length,c=n.some(l=>l?.passed!==void 0);o.push(c?`${s}: ${a}/${i} passed${i-a?`, ${i-a} 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();tr({path:j(i,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let _=j(i,".zibby.config.js");$t(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=e.agentType;if(!c){let _=a?.agent;_?.provider?c=_.provider:_?.gemini?c="gemini":_?.claude?c="claude":_?.cursor?c="cursor":_?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let l=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let _=p.safeParse(e);if(!_.success){let k=_.error.issues.map(x=>`${x.path.join(".")}: ${x.message}`);throw console.error("\u274C Initial state validation failed:"),k.forEach(x=>console.error(` - ${x}`)),new Error(`State validation failed: ${k.join(", ")}`)}v.step("State validated against schema")}let h=or(),f=e.sessionPath||h;f||nr();let{sessionPath:m,sessionTimestamp:I,sessionId:g}=cr({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:f,sessionTimestamp:e.sessionTimestamp}});v.step(`Session ${g}`);let $=await nt.loadContext(e.specPath||"",i,l);Object.keys($).length>0&&v.step(`Context loaded: ${Object.keys($).join(", ")}`);let N=e.outputPath;!N&&e.specPath&&(t?.calculateOutputPath?N=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let u=new tt({...e,config:a,agentType:c,outputPath:N,sessionPath:m,sessionTimestamp:I,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),w=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(ht(),Yt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},C=Object.values(d).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),U=_=>{for(let k of C)if(k.id===_)return k;return E(_)},Tt=new Set;for(let[,_]of this.nodes)for(let k of _.config?.skills||[])Tt.add(k);for(let _ of Tt){let k=U(_);if(typeof k?.middleware=="function")try{let x=await k.middleware();typeof x=="function"&&w.set(_,x)}catch{}}let S=this.entryPoint,q=[],vt=a?.recursionLimit??100,de=0;try{for(;S&&S!=="END";){if(++de>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 k=j(m,Gt);if($t(k)){try{Qe(k)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
37
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),v.step("Workflow stopped externally"),{success:!0,state:u.getAll(),executionLog:q,stoppedExternally:!0};let x=this.nodes.get(S);if(!x)throw new Error(`Node '${S}' not found in graph`);let At=JSON.stringify({sessionPath:m,sessionTimestamp:I,currentNode:S,createdAt:new Date().toISOString(),config:u.get("config")}),he=j(m,G);ae(he,At,"utf-8");let kt=u.get("config")?.paths?.output||st,fe=j(i,kt,G);ue(j(i,kt),{recursive:!0});try{ae(fe,At,"utf-8")}catch{}let xt=e.onPipelineProgress;if(typeof xt=="function")try{xt({cwd:i,sessionPath:m,sessionId:g,outputBase:u.get("config")?.paths?.output||st,currentNode:S})}catch{}let ge=(this.resolvedToolsMap||{})[S]||null;u.set("_currentNodeTools",ge);let me=u.get("nodeConfigs")||{};u.set("_currentNodeConfig",me[S]||{}),v.nodeStart(S);let Ot=Date.now(),V=this.nodePrompts.get(S);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(mt(),gt));this._invokeAgent=O.invokeAgent}let Se=this._invokeAgent,it={},we=x.config?.skills||[];for(let O of we){let P=U(O);if(typeof P?.invokeAgentOptions=="function")try{let b=P.invokeAgentOptions(u.getAll(),{agentType:u.get("agentType"),nodeName:S});b&&typeof b=="object"&&(it={...it,...b})}catch(b){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${b.message}`)}}let Pt=async(O,P,b={})=>{let R=Se(O,P,{...it,...b,signal:s.signal});return R.catch(()=>{}),s.signal.aborted?R:Promise.race([R,new Promise((W,F)=>{let B=()=>{setTimeout(()=>{let J=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${n}ms`);J.name="AbortError",F(J)},n)};s.signal.addEventListener("abort",B,{once:!0})})])},Nt={state:u,invokeAgent:async(O={},P={})=>{let b=P.prompt||"";if(V){let R=this._compiledPrompts.get(S);R||(R=er.compile(V,{noEscape:!0}),this._compiledPrompts.set(S,R));try{b=R(O)}catch(W){throw console.error(`\u274C Template rendering failed for node '${S}':`,W.message),new Error(`Template rendering failed: ${W.message}`,{cause:W})}}else if(!b)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return Pt(b,{state:u.getAll(),images:P.images||[]},{model:P.model||u.get("model"),workspace:u.get("workspace"),schema:P.schema,...P,signal:s.signal})},_coreInvokeAgent:Pt,agent:t,nodeId:S,promptTemplate:V,getPromptTemplate:()=>V,...u.getAll()};try{let O=(x.config?.skills||[]).map(B=>w.get(B)).filter(Boolean),P=[...this.middleware,...O],b;P.length>0?b=await this._composeMiddleware(P,S,async()=>x.execute(Nt,u),u.getAll(),u):b=await x.execute(Nt,u);let R=Date.now()-Ot;if(q.push({node:S,success:b.success,duration:R,timestamp:new Date().toISOString()}),!b.success){if(s.signal.aborted)return v.step("Workflow stopped externally"),{success:!0,state:u.getAll(),executionLog:q,stoppedExternally:!0};u.append("errors",{node:S,error:b.error});let B=x.config?.retries||0,J=`${S}_retries`,X=u.getAll()[J]||0;if(X<B){v.stepInfo(`Retrying (attempt ${X+1}/${B})`),u.update({[J]:X+1,[`${S}_raw`]:b.raw});continue}throw v.nodeFailed(S,b.error,{duration:R}),new Error(`Node '${S}' failed after ${X} attempts: ${b.error}`)}u.update({[S]:b.output});let W=this._summarizeNodeOutput(S,b.output);v.nodeComplete(S,{duration:R,details:W});let F=this.edges.get(S);if(!F)S="END";else if(F.conditional){let B=F.routes(u.getAll());v.route(S,B),S=B}else S=F}catch(O){throw v.isInsideNode&&v.nodeFailed(S,O.message,{duration:Date.now()-Ot}),u.set("failed",!0),u.set("failedAt",S),O}}v.graphComplete();let _={success:!0,state:u.getAll(),executionLog:q};return t&&typeof t.onComplete=="function"&&await t.onComplete(_),_}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};export{le as WorkflowGraph,nr as clearInheritedSessionEnvForFreshRun,ar as generateWorkflowSessionId,or as readPinnedSessionPathFromEnv,cr as resolveWorkflowSession,sr as shouldTrustInheritedSessionEnv,ir as syncProcessEnvToSession};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `workflowName` in-process inside the parent's Fargate task.
|
|
3
|
+
*
|
|
4
|
+
* The contract mirrors the cloud-HTTP `dispatchSubgraph` — same return
|
|
5
|
+
* shape, same options where they make sense — so callers can swap paths
|
|
6
|
+
* without changing user code.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} workflowName
|
|
9
|
+
* @param {object} options
|
|
10
|
+
* @param {object} [options.input]
|
|
11
|
+
* @param {string} [options.conversationId]
|
|
12
|
+
* @param {AbortSignal} [options.signal]
|
|
13
|
+
* Parent's internal AbortController signal. Plumbed straight into
|
|
14
|
+
* `child.run({ signal })` — UI cancels reach the child without polling.
|
|
15
|
+
* @param {object} [options.parentAgent]
|
|
16
|
+
* The agent shell from the parent's run. Passed verbatim into the
|
|
17
|
+
* child's `graph.run(agent, ...)` so the child sees the same agent
|
|
18
|
+
* strategy + onComplete hooks; child workflows can override per-node.
|
|
19
|
+
* @param {string | function} [options.output]
|
|
20
|
+
* Same shape as the HTTP path's `output:`. We don't resolve it here
|
|
21
|
+
* — the caller (`sub-graph-executor.js`) does that on the finalState
|
|
22
|
+
* we return, identical to the HTTP path.
|
|
23
|
+
*
|
|
24
|
+
* @returns {Promise<{ finalState: object, executionId: string }>}
|
|
25
|
+
*
|
|
26
|
+
* @throws {SubgraphFallback} when the in-process path is unavailable.
|
|
27
|
+
* Caller should drop to HTTP/trigger.
|
|
28
|
+
* @throws {Error} quota / not-found / validation errors that
|
|
29
|
+
* the HTTP path would also surface — pass
|
|
30
|
+
* these through, do NOT fall back, because
|
|
31
|
+
* HTTP would fail the same way.
|
|
32
|
+
*/
|
|
33
|
+
export function runInProcessSubgraph(workflowName: string, options?: {
|
|
34
|
+
input?: object;
|
|
35
|
+
conversationId?: string;
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
parentAgent?: object;
|
|
38
|
+
output?: string | Function;
|
|
39
|
+
}): Promise<{
|
|
40
|
+
finalState: object;
|
|
41
|
+
executionId: string;
|
|
42
|
+
}>;
|
|
43
|
+
/** Best-effort cache size probe — used by metrics and by the eventual
|
|
44
|
+
* LRU sweep. Returns total bytes under CACHE_ROOT or 0 if nothing yet. */
|
|
45
|
+
export function getCacheStats(): {
|
|
46
|
+
bytes: number;
|
|
47
|
+
entries: any;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Typed marker that callers should drop back to the HTTP/trigger path.
|
|
51
|
+
* Carries `.reason` for observability + a Boolean tag so a `catch` block
|
|
52
|
+
* can `if (e.fallback)` without instanceof-juggling across module loads.
|
|
53
|
+
*/
|
|
54
|
+
export class SubgraphFallback extends Error {
|
|
55
|
+
constructor(reason: any, detail: any);
|
|
56
|
+
fallback: boolean;
|
|
57
|
+
reason: any;
|
|
58
|
+
detail: any;
|
|
59
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var L=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{mkdirSync as z,existsSync as m,statSync as F}from"node:fs";import{spawn as U}from"node:child_process";import{join as y}from"node:path";import{pathToFileURL as q}from"node:url";var v=()=>{},N={debug:v,info:v,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},x={impl:N};var T={debug:(...e)=>x.impl.debug?.(...e),info:(...e)=>x.impl.info?.(...e),warn:(...e)=>x.impl.warn?.(...e),error:(...e)=>x.impl.error?.(...e)};import{AsyncLocalStorage as G}from"node:async_hooks";var k=new G;function $(){let e=k.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 R(e,n){let r=k.getStore()||$(),o=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 k.run(o,n)}var B=new Map,A=new Map,C=new Map;function P(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");B.set(e,n),A.set(e,"ready"),C.set(e,{...r,cachedAt:Date.now()})}function O(e,n){A.set(e,"failed"),C.set(e,{error:n?.message||String(n),failedAt:Date.now()}),B.delete(e)}function D(e){return A.get(e)==="ready"?B.get(e):null}var _=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function J(){return Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10)}function X(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var c=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 V(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),n=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||n,o=process.env.PROJECT_ID,t=process.env.PROJECT_API_TOKEN;if(!r||!o||!t)throw new c("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:o,authToken:t}}async function W({apiBase:e,authToken:n,body:r}){let o;try{o=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)})}catch(i){throw new c("network",`begin fetch failed: ${i.message}`)}let t=null;try{t=await o.json()}catch{}if(!o.ok){if(o.status===404){let i=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(o.status===429){let i=t?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=i,a}if(o.status===400&&t?.validationErrors){let i=new Error(`Sub-graph rejected input: ${t?.error||t?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=t.validationErrors,i.missing=t.missing,i}throw new c("begin-status",`begin returned ${o.status}`)}return t?.data||t}async function p({apiBase:e,authToken:n,payload:r}){try{let o=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});o.ok||T.warn(`[in-process subgraph] finalize returned ${o.status} for ${r.childExecutionId}`)}catch(o){T.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function Y(e,n){let r=y(n,".ready"),o=y(n,"graph.mjs");if(m(r)&&m(o))return;z(n,{recursive:!0});let t=y(n,".lock"),i=!1;try{let{openSync:a,closeSync:u}=await import("node:fs"),h=a(t,"wx");u(h),i=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!i){let a=Date.now()+3e4;for(;Date.now()<a;){if(m(r)&&m(o))return;await new Promise(u=>setTimeout(u,100))}throw new c("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((h,b)=>{let f=U("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),g=U("tar",["-xzf","-","-C",n],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(g.stdin);let w,l,I=()=>{if(w!==void 0&&l!==void 0){if(w!==0)return b(new Error(`curl exited ${w}`));if(l!==0)return b(new Error(`tar exited ${l}`));h()}};f.on("close",d=>{w=d,I()}),g.on("close",d=>{l=d,I()}),f.on("error",b),g.on("error",b)});let{writeFileSync:a,unlinkSync:u}=await import("node:fs");a(r,"");try{u(t)}catch{}}catch(a){try{let{unlinkSync:u}=await import("node:fs");u(t)}catch{}throw new c("bundle-extract-failed",a.message)}}async function Z(e){let n=y(e,"graph.mjs");if(!m(n))throw new c("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(q(n).href)}catch(t){throw new c("import-failed",`${t?.code||t?.name||"unknown"}: ${t.message}`)}let o=r.default||Object.values(r).find(t=>typeof t=="function"&&t.prototype?.buildGraph);if(!o)throw new c("entry-class-missing","no buildGraph() class export found");return o}async function ue(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=$(),o=J();if((r.depth||0)>=o)throw new c("depth-exceeded",`depth ${r.depth} \u2265 MAX_DEPTH ${o}`);let t;try{t=V()}catch(s){throw s}T.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let i=await W({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:n.input||{},...n.conversationId?{conversationId:n.conversationId}:{}}}),{childExecutionId:a,runtimeTag:u,bundlePresignedUrl:h,sourcesPresignedUrl:b,workflowVersion:f,workflowUuid:g,bundleReady:w}=i,l=X();if(u&&u!==l)throw await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"canceled",error:{message:`runtimeTag mismatch: parent=${l} child=${u}`,code:"RUNTIME_MISMATCH"}}}),new c("runtime-mismatch",`${l} vs ${u}`);if(!w||!h)throw await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new c("no-bundle","workflow bundle not built yet");let I=y(_,`${g}@${f||"0"}`);try{await Y(h,I)}catch(s){throw s.fallback&&await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"failed",error:{message:s.message,code:s.reason}}}),s}let d=D(e);if(!d)try{d=await Z(I),P(e,d,{workflowUuid:g,version:f,runtimeTag:u,cacheDir:I})}catch(s){throw O(e,s),await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"failed",error:{message:s.message,code:s.reason||"IMPORT_FAILED"}}}),s.fallback?s:new c("import-failed",s.message)}let S=Date.now(),M=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph(),H={...n.input||{}},E;try{E=await R({executionId:a,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>M.run(n.parentAgent,H,{signal:n.signal}))}catch(s){throw await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"failed",error:{message:s.message,code:s.code||"CHILD_THREW",stack:s.stack},durationMs:Date.now()-S}}),s}if(E?.stoppedExternally){await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"canceled",finalState:E,durationMs:Date.now()-S}});let s=new Error(`Sub-graph '${e}' canceled by parent abort`);throw s.code="SUBGRAPH_CANCELED",s.subgraphJobId=a,s}return await p({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:a,status:"completed",finalState:E,durationMs:Date.now()-S}}),{finalState:E,executionId:a}}function de(){try{if(!m(_))return{bytes:0,entries:0};let{readdirSync:e}=L("node:fs"),n=e(_),r=0;for(let o of n)try{r+=F(y(_,o)).size}catch{}return{bytes:r,entries:n.length}}catch{return{bytes:0,entries:0}}}export{c as SubgraphFallback,de as getCacheStats,ue as runInProcessSubgraph};
|