@zibby/agent-workflow 0.6.0 → 0.6.2
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/README.md +30 -0
- package/dist/code-generator.js +15 -15
- package/dist/exec-context.d.ts +12 -0
- package/dist/exec-context.js +1 -1
- package/dist/graph-compiler.js +21 -21
- package/dist/graph.d.ts +40 -0
- package/dist/graph.js +25 -25
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +30 -30
- package/dist/node-registry.js +10 -10
- package/dist/node.js +17 -17
- package/dist/strategy-registry.js +8 -8
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/graph.d.ts
CHANGED
|
@@ -98,10 +98,50 @@ export declare class WorkflowGraph {
|
|
|
98
98
|
*/
|
|
99
99
|
_runtimeSchema(): any;
|
|
100
100
|
addNode(name: any, nodeOrConfig: any, options?: any): this;
|
|
101
|
+
/**
|
|
102
|
+
* Connect `from` → `to`. Calling it AGAIN for the same `from` declares a
|
|
103
|
+
* FAN-OUT: the node's successors all run, each carrying on through its own
|
|
104
|
+
* children, instead of the second call silently replacing the first.
|
|
105
|
+
*
|
|
106
|
+
* That replacement is what this used to do (`Map.set`), and it lost work with
|
|
107
|
+
* no error anywhere: a fan-out drawn in the visual editor round-tripped
|
|
108
|
+
* through the code generator as two `addEdge` lines, compiled down to ONE
|
|
109
|
+
* edge, and ran one branch while the graph, the generated source and the UI
|
|
110
|
+
* all showed two. Appending makes the declaration and the execution agree.
|
|
111
|
+
*
|
|
112
|
+
* The single-successor case keeps the STRING shape (not a 1-element array),
|
|
113
|
+
* so every existing graph serializes and runs byte-identically.
|
|
114
|
+
*/
|
|
101
115
|
addEdge(from: any, to: any): this;
|
|
102
116
|
setNodeType(name: any, nodeType: any): this;
|
|
103
117
|
addConditionalEdges(from: any, routes: any, { labels }?: any): this;
|
|
104
118
|
setEntryPoint(nodeName: any): this;
|
|
119
|
+
/** Unconditional successors of `id` — [] for a leaf or a conditional node. */
|
|
120
|
+
_simpleTargets(id: any): any[];
|
|
121
|
+
/**
|
|
122
|
+
* Static analysis the fan-out scheduler runs on: which edges CLOSE A CYCLE,
|
|
123
|
+
* and how many branches converge on each node.
|
|
124
|
+
*
|
|
125
|
+
* Both are computed over UNCONDITIONAL edges only, deliberately. A
|
|
126
|
+
* conditional edge's targets can only be guessed by parsing the route
|
|
127
|
+
* function's source (`_inferConditionalTargets`) — fine for drawing a
|
|
128
|
+
* diagram, far too fragile to decide whether a node is allowed to run. So a
|
|
129
|
+
* conditional arrival always schedules its target immediately, exactly as it
|
|
130
|
+
* does today, and a JOIN is defined over the unconditional edges that a
|
|
131
|
+
* fan-out actually creates.
|
|
132
|
+
*
|
|
133
|
+
* Back-edges are excluded from the join count for the same reason a loop
|
|
134
|
+
* works today: a node that a later node routes BACK to must not sit waiting
|
|
135
|
+
* for that later node to arrive — it would deadlock the retry loops that
|
|
136
|
+
* already ship (`route back to fetch` after a failure).
|
|
137
|
+
*
|
|
138
|
+
* @returns {{ backEdges: Set<string>, joinDegree: Map<string, number> }}
|
|
139
|
+
* backEdges keyed `"<from>-><to>"`; joinDegree = inbound branches.
|
|
140
|
+
*/
|
|
141
|
+
_analyzeFlow(): {
|
|
142
|
+
backEdges: Set<string>;
|
|
143
|
+
joinDegree: Map<string, number>;
|
|
144
|
+
};
|
|
105
145
|
use(middlewareFn: any): this;
|
|
106
146
|
_composeMiddleware(middlewareList: any, nodeName: any, coreFn: any, stateValues: any, state: any): any;
|
|
107
147
|
serialize(): {
|
package/dist/graph.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
1
|
+
var jt=Object.defineProperty;var ae=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Fe=(r,e)=>{for(var t in e)jt(r,t,{get:e[t],enumerable:!0})};var Ge,Lt,ue,E,ee=ae(()=>{Ge=()=>{},Lt={debug:Ge,info:Ge,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},ue={impl:Lt},E={debug:(...r)=>ue.impl.debug?.(...r),info:(...r)=>ue.impl.info?.(...r),warn:(...r)=>ue.impl.warn?.(...r),error:(...r)=>ue.impl.error?.(...r)}});var et=ae(()=>{});var tt={};Fe(tt,{clearSkills:()=>Yt,getAllSkills:()=>Jt,getSkill:()=>$e,getSkillSource:()=>Ht,hasSkill:()=>Gt,listSkillIds:()=>zt,registerSkill:()=>Ft});function Ft(r,e={}){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,s=r.id;if(U.has(s)&&!n){let i=ne.get(s);if(!(i===t)){let a=i||"first-party",u=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${u} may not overwrite it. Ids are append-only and first-party ids cannot be shadowed. Pick a unique id (or pass { override: true } for a deliberate first-party replacement).`)}}U.set(s,Object.freeze({...r})),t===void 0?ne.delete(s):ne.set(s,t)}function $e(r){return U.get(r)||null}function Gt(r){return U.has(r)}function Ht(r){return ne.get(r)||null}function Jt(){return new Map(U)}function zt(){return Array.from(U.keys())}function Yt(){U.clear(),ne.clear()}var Ie,Ee,U,ne,ve=ae(()=>{Ie=Symbol.for("@zibby/agent-workflow.skills"),Ee=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ie]||(globalThis[Ie]=new Map);globalThis[Ee]||(globalThis[Ee]=new Map);U=globalThis[Ie],ne=globalThis[Ee]});var Te={};Fe(Te,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Zt,resolveInvocationModel:()=>nt});function Zt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=F.findIndex(t=>t.getName()===r.getName());e>=0?F[e]=r:F.push(r)}function qt(){return F.map(r=>r.getName())}function nt({config:r={},options:e={},strategyName:t,envModel:n}={}){let s=r.models||{},i=e.nodeName&&s[e.nodeName]||null,o=s.default||null,a=r.agent?.[t]?.model||null,u=(typeof n=="string"?n.trim():"")||null;return i||o||a||e.model||u||null}function rt(r={}){let{state:e={},preferredAgent:t=null}=r,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}E.debug(`[workflow] agent selection: requested=${n}`);let s=F.find(i=>i.getName()===n);if(!s){let i=F.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${i}`)}if(!s.canHandle(r))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${s.getName()}`),s}async function Vt(r,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:n},i=rt(s),o=n.config||t.config||{},a=nt({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL}),u={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:o},p=r,m=u.skills||[];if(m.length>0&&!t.skipPromptFragments){let S=t.connectedIntegrations;if(!S){let $=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof $=="string"&&$.trim()!==""){S={};for(let I of $.split(",").map(f=>f.trim()).filter(Boolean))S[I]=!0}}let w=$=>{let I=$&&$.requiresIntegration;return!I||!S?!0:(Array.isArray(I)?I:[I]).some(g=>S[g]===!0)},b=m.map($=>{let I=$e($);if(!w(I))return null;let f=I?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);b.length>0&&(p+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${b.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let c=n._currentNodeConfig?.stores;if(Array.isArray(c)&&c.length>0&&typeof c[0]=="object"){let S=c.length<=8,
|
|
6
|
-
fields: ${d.join(", ")}`)}return
|
|
5
|
+
`)}`)}let c=n._currentNodeConfig?.stores;if(Array.isArray(c)&&c.length>0&&typeof c[0]=="object"){let S=c.length<=8,w=c.map(b=>{let $=b?.id??b?.storeId??"",I=(b?.name??"").toString().trim()||$,f=b?.type?` \xB7 ${b.type}`:"",g=(b?.description||"").toString().replace(/\s+/g," ").trim(),y=`- ${I} \xB7 ${g||"(no description)"}${f} (id: ${$})`;if(S&&b?.schema&&typeof b.schema=="object"){let d=b.schema.properties&&typeof b.schema.properties=="object"?Object.keys(b.schema.properties):Object.keys(b.schema);d.length&&(y+=`
|
|
6
|
+
fields: ${d.join(", ")}`)}return y});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
9
|
+
${w.join(`
|
|
10
10
|
`)}`}let l=n._currentNodeConfig?.extraPromptInstructions?.trim();return l&&(p+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
@@ -14,29 +14,29 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${l}
|
|
17
|
-
`),
|
|
18
|
-
${
|
|
19
|
-
`)}`);return
|
|
20
|
-
`?(
|
|
21
|
-
${
|
|
17
|
+
`),E.debug(`[workflow] prompt length: ${p.length} chars`),i.invoke(p,u)}var Ae,F,ke=ae(()=>{et();ee();ve();Ae=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Ae]||(globalThis[Ae]=[]);F=globalThis[Ae]});var Dt=new Set(["__proto__","constructor","prototype"]);function Se(r){if(Dt.has(r))throw new Error(`Invalid state key: "${r}"`)}var ce=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){Se(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)Se(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){Se(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import G from"handlebars";var le=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of n)try{return this.validate(JSON.parse(s))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,s]of Object.entries(this.schema)){if(s.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&s.type){let i=typeof e[n];i!==s.type&&t.push(`Field '${n}' expected ${s.type}, got ${i}`)}if(s.validate&&n in e){let i=s.validate(e[n]);i&&t.push(`Field '${n}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
|
+
${t.join(`
|
|
19
|
+
`)}`);return e}};ee();import{writeFileSync as xe,readFileSync as st,existsSync as ot,mkdirSync as Kt}from"node:fs";import{join as Oe,dirname as Xt}from"node:path";import x from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",te=x.gray("\u2502"),Ut=x.gray("\u250C"),He=x.gray("\u2514"),we=x.green("\u25C6"),Je=x.hex("#c084fc")("\u25C6"),ze=x.hex("#2dd4bf")("\u25C6"),_e=x.red("\u25C6"),Ye=`${te} `,Ze=2;function qe(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Ve(r,e){return(t,n,s)=>{if(typeof t!="string")return r(t,n,s);let i=process.stdout.columns||120,o="";for(let a=0;a<t.length;a++){let u=t[a];e.lineStart&&(o+=Ye,e.col=Ze,e.lineStart=!1),u===`
|
|
20
|
+
`?(o+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,o+=u):e.inEsc?(o+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,o+=u,e.col>=i&&(o+=`
|
|
21
|
+
${Ye}`,e.col=Ze))}return r(o,n,s)}}var be=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
|
-
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(
|
|
24
|
-
`)}_emitGraphLogMarker(
|
|
25
|
-
`;this._origStdoutWrite?this._origStdoutWrite(
|
|
26
|
-
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${
|
|
27
|
-
`)):process.stdout.write.bind(process.stdout)(`${
|
|
28
|
-
`)}step(
|
|
29
|
-
`)}stepInfo(
|
|
30
|
-
`)}stepMemory(
|
|
31
|
-
`)}stepFail(
|
|
32
|
-
`)}nodeStart(
|
|
33
|
-
|
|
34
|
-
${i}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=$t(p,z);if(ee(c)){let S=JSON.parse(te(c,"utf-8"));S.currentNode=this.name,Et(c,JSON.stringify(S,null,2),"utf-8")}let l=$t(p,"..",z);if(ee(l))try{let S=JSON.parse(te(l,"utf-8"));S.currentNode=this.name,Et(l,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(c){I.debug(`[workflow] could not update session info: ${c.message}`)}let h=null;for(let c=0;c<=this.retries;c++)try{I.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},S=l.agents||{},y=this.config.agent??S[this.name]??null,w={state:n()};y&&(w.preferredAgent=y);let T={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},$=t?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(bt(),It))).invokeAgent);let f=await $(i,w,T),g,m;if(typeof f=="string"?(g=f,m=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),m=f.structured):(g=f.raw||JSON.stringify(f,null,2),m=f.extracted||null),p)try{let d=$t(p,this.name,"raw_stream_output.txt");Je(Ye(d),{recursive:!0}),Et(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){I.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let d=m;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),m)}catch(E){I.warn(`[workflow] onComplete hook failed: ${E.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),P.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){h=l,c<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};V();V();import{mkdirSync as qe,existsSync as H,statSync as ue,readdirSync as pe,rmSync as Ve}from"node:fs";import{spawn as ae}from"node:child_process";import{join as L}from"node:path";import{pathToFileURL as Ke}from"node:url";import{AsyncLocalStorage as Xe}from"node:async_hooks";import{AsyncLocalStorage as Ze}from"node:async_hooks";var vt=new Ze;function Q(){let r=vt.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 ne(r,t){let e=vt.getStore()||Q(),n=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 vt.run(n,t)}var Tt=new Map,kt=new Map,re=new Map;function oe(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),kt.set(r,"ready"),re.set(r,{...e,cachedAt:Date.now()})}function se(r,t){kt.set(r,"failed"),re.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function ie(r){return kt.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Qe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}},ce=new Xe,le=Promise.resolve();async function tn(r,t){let e=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([s,a])=>typeof s=="string"&&s&&typeof a=="string"):[];if(e.length===0)return t();let n=ce.getStore()===!0,o=null;if(!n){let s=le;le=new Promise(a=>{o=a}),await s}let i=new Map;try{for(let[s,a]of e)i.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=a;return I.debug(`[in-process subgraph] scoped ${e.length} child env var(s)${n?" (nested)":""}`),await ce.run(!0,t)}finally{for(let[s,a]of i)a===void 0?delete process.env[s]:process.env[s]=a;o&&o()}}function en(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!e||!n||!o)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:n,authToken:o}}async function nn({apiBase:r,authToken:t,body:e}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(i){throw new O("network",`begin fetch failed: ${i.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.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(n.status===429){let i=o?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(n.status===400&&o?.validationErrors){let i=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=o.validationErrors,i.missing=o.missing,i}throw new O("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function G({apiBase:r,authToken:t,payload:e}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${e.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function rn(r,t){let e=L(t,".ready"),n=L(t,"graph.mjs");if(H(e)&&H(n))return;qe(t,{recursive:!0});let o=L(t,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),u=s(o,"wx");a(u),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(H(e)&&H(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let h=ae("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ae("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(c.stdin);let l,S,y=()=>{if(l!==void 0&&S!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(S!==0)return p(new Error(`tar exited ${S}`));u()}};h.on("close",w=>{l=w,y()}),c.on("close",w=>{S=w,y()}),h.on("error",p),c.on("error",p)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(e,"");try{a(o)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(o)}catch{}throw new O("bundle-extract-failed",s.message)}}async function on(r){let t=L(r,"graph.mjs");if(!H(t))throw new O("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ke(t).href)}catch(o){throw new O("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=e.default||Object.values(e).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function de(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),n;try{n=en()}catch(d){throw d}I.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let o=await nn({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:i,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:h,bundleReady:c,nodeConfigs:l}=o,S=Qe();if(s&&s!==S)throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${S} vs ${s}`);if(!c||!a)throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let y=ie(r);if(!y){let d=L(ct,`${h}@${p||"0"}`);try{await rn(a,d);try{an()}catch{}}catch(E){throw E.fallback&&await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason}}}),E}try{y=await on(d),oe(r,y,{workflowUuid:h,version:p,runtimeTag:s,cacheDir:d})}catch(E){throw se(r,E),await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:E.message,code:E.reason||"IMPORT_FAILED"}}}),E.fallback?E:new O("import-failed",E.message)}}let w=Date.now(),T=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...t.input||{},...$?{nodeConfigs:l}:{}},g,m;try{g=await tn(T,async()=>{let E=await(typeof y=="function"&&y.prototype?.buildGraph?new y:y).buildGraph();return ne({executionId:i,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>E.run(t.parentAgent,f,{signal:t.signal}))}),m=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-w}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:m,durationMs:Date.now()-w}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await G({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:m,durationMs:Date.now()-w}}),{finalState:m,executionId:i}}function sn(r){let t=0,e=[r];for(;e.length;){let n=e.pop(),o;try{o=ue(n)}catch{continue}if(o.isDirectory()){let i;try{i=pe(n)}catch{continue}for(let s of i)e.push(L(n,s))}else t+=o.size}return t}function an({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!H(ct))return{evicted:0,freedBytes:0};let t=pe(ct),e=[],n=0;for(let a of t){let u=L(ct,a),p;try{p=ue(u)}catch{continue}let h=p.isDirectory()?sn(u):p.size;n+=h,e.push({name:a,full:u,size:h,mtimeMs:p.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};e.sort((a,u)=>a.mtimeMs-u.mtimeMs);let o=Math.floor(r*.7),i=0,s=0;for(let a of e){if(n-i<=o)break;if(!H(L(a.full,".lock")))try{Ve(a.full,{recursive:!0,force:!0}),i+=a.size,s+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:i,totalBytes:n-i}}catch(t){return I.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var cn=2e3,ln=600*1e3,un=new Set(["completed","failed","canceled","timeout"]);function pn(){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 dn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function fn(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function hn(){return process.env.EXECUTION_ID||null}function fe(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,n)=>e==null?e:e[n],r):r}async function he(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{I.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:m}=await de(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),d=fe(m,t.output);return I.info(`[sub-graph] '${r}' completed in-process`),d}catch(m){if(m instanceof O||m?.fallback)I.info(`[sub-graph] in-process fallback for '${r}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let o=pn(),i=dn(),s=fn(),a=hn(),u=`${o}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};I.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(p)});if(!h.ok){let m=null,d="";try{m=await h.json(),d=m?.error||m?.message||JSON.stringify(m)}catch{d=await h.text().catch(()=>"")}if(h.status===429){let k=m?.quotaInfo||{},M=new Error(`Sub-graph '${r}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=k,M}if(h.status===400){let k=new Error(`Sub-graph '${r}' rejected input: ${d}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=r,k.validationErrors=m?.validationErrors||null,k.missing=m?.missing||null,k}let E=new Error(`Sub-graph '${r}' trigger rejected (${h.status}): ${d}`);throw E.code="SUBGRAPH_TRIGGER_FAILED",E.status=h.status,E.subgraph=r,E}let c=await h.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return I.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let S=Number.isFinite(t.timeoutMs)?t.timeoutMs:ln,y=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:cn,w=`${o}/executions/${encodeURIComponent(l)}`,T=Date.now()+S,$="accepted",f=0;for(;Date.now()<T;){await new Promise(k=>setTimeout(k,y)),f+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${l} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${m.status}`)}let d=await m.json(),E=d?.data||d?.execution||d;if($=E?.status||$,un.has($)){if($!=="completed"){let _=new Error(`Sub-graph '${r}' (${l}) ended in status '${$}'`);throw _.subgraphJobId=l,_.subgraphStatus=$,_}let k=E?.finalState||E?.state||{},M=fe(k,t.output);return I.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(S/1e3)}s (last status: ${$})`);throw g.subgraphJobId=l,g.subgraphStatus=$,g}import{existsSync as ge,readFileSync as gn}from"node:fs";import{join as At,dirname as me}from"node:path";var lt=class{static async loadContext(t,e,n={}){let o={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=me(At(e,t));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,e);if(p){let h=u.replace(/\.[^.]+$/,"").toLowerCase();o[h]=p}}}let s=n.discovery||{};for(let[a,u]of Object.entries(s))try{let p=At(e,u);ge(p)&&(o[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return o}static async findAndMergeContextFiles(t,e,n){let o=[],i=e;for(;i.startsWith(n);){let s=At(i,t);if(ge(s))try{o.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${t} from ${s}: ${u.message}`)}let a=me(i);if(a===i)break;i=a}return o.length===0?null:o.every(s=>typeof s=="string")?o.join(`
|
|
23
|
+
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Wt}${JSON.stringify(e)}
|
|
25
|
+
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
|
+
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
|
+
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(we,e):process.stdout.write.bind(process.stdout)(`${te} ${we} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Je,e):process.stdout.write.bind(process.stdout)(`${te} ${Je} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ze,t):process.stdout.write.bind(process.stdout)(`${te} ${ze} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(_e,x.red(e)):process.stdout.write.bind(process.stdout)(`${te} ${_e} ${x.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:s}=t;if(s)for(let o of s)this._rawWrite(`${we} ${o}`);let i=n?x.dim(` ${qe(n)}`):"";this._rawWrite(`${He} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:s}=n,i=s?x.dim(` ${qe(s)}`):"";this._rawWrite(`${_e} ${x.red(t)}`),this._rawWrite(`${He} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new be;var pe=".zibby/output",Ke="sessions",Z=".session-info.json",Xe=".zibby-stop";var Dn=Object.freeze(["codebase-memory","code-scan","artifact"]),Qe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];G.helpers.inc||G.registerHelper("inc",r=>Number(r)+1);G.helpers.json||G.registerHelper("json",r=>JSON.stringify(r,null,2));G.helpers.eq||G.registerHelper("eq",(r,e)=>r===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return E.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=G.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(n())):i=this.prompt;let o=s("_skillHints");o&&(i=`${o}
|
|
33
|
+
|
|
34
|
+
${i}`);let a=n(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=Oe(p,Z);if(ot(c)){let S=JSON.parse(st(c,"utf-8"));S.currentNode=this.name,xe(c,JSON.stringify(S,null,2),"utf-8")}let l=Oe(p,"..",Z);if(ot(l))try{let S=JSON.parse(st(l,"utf-8"));S.currentNode=this.name,xe(l,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(c){E.debug(`[workflow] could not update session info: ${c.message}`)}let m=null;for(let c=0;c<=this.retries;c++)try{E.debug(`[workflow] node '${this.name}' attempt ${c}`);let l=n().config||{},S=l.agents||{},w=this.config.agent??S[this.name]??null,b={state:n()};w&&(b.preferredAgent=w);let $={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:p,config:l,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(ke(),Te))).invokeAgent);let f=await I(i,b,$),g,y;if(typeof f=="string"?(g=f,y=null):f.structured?(g=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(g=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),p)try{let d=Oe(p,this.name,"raw_stream_output.txt");Kt(Xt(d),{recursive:!0}),xe(d,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(d){E.debug(`[workflow] could not save raw output: ${d.message}`)}if(this.isZodSchema&&y){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let d=y;if(typeof this.onComplete=="function")try{d=await this.onComplete(n(),y)}catch(v){E.warn(`[workflow] onComplete hook failed: ${v.message}`)}return{success:!0,output:d,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(d){throw new Error(`onComplete failed: ${d.message}`,{cause:d})}if(this.parser){let d=this.parser.parse(g);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(d,null,2)}`),O.step("Output parsed"),{success:!0,output:d,raw:g}}return{success:!0,output:g,raw:g}}catch(l){m=l,c<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:m.message,raw:null}}};ee();ee();import{mkdirSync as tn,existsSync as J,statSync as gt,readdirSync as mt,rmSync as nn}from"node:fs";import{spawn as dt}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as rn}from"node:url";import{AsyncLocalStorage as sn}from"node:async_hooks";import{AsyncLocalStorage as Qt}from"node:async_hooks";var re=new Qt;function q(){let r=re.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,agent:null,signal:null})}function it(r,e){let t=re.getStore()||q(),n=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(r.executionId!==t.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:t.conversationId??null,dispatchMode:r.dispatchMode??null,agent:r.agent!==void 0?r.agent:t.agent??null,signal:r.signal!==void 0?r.signal:t.signal??null});return re.run(n,e)}function at(r,e,t){let n=re.getStore()||q(),s=Object.freeze({...n,agent:r??n.agent??null,signal:e??n.signal??null});return re.run(s,t)}var Pe=new Map,Ne=new Map,ct=new Map;function lt(r,e,t={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Pe.set(r,e),Ne.set(r,"ready"),ct.set(r,{...t,cachedAt:Date.now()})}function ut(r,e){Ne.set(r,"failed"),ct.set(r,{error:e?.message||String(e),failedAt:Date.now()}),Pe.delete(r)}function pt(r){return Ne.get(r)==="ready"?Pe.get(r):null}var de=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function on(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var P=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},ft=new sn,ht=Promise.resolve();async function an(r,e){let t=r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let n=ft.getStore()===!0,s=null;if(!n){let o=ht;ht=new Promise(a=>{s=a}),await o}let i=new Map;try{for(let[o,a]of t)i.set(o,Object.prototype.hasOwnProperty.call(process.env,o)?process.env[o]:void 0),process.env[o]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await ft.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function cn(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=r||e,n=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!n||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:s}}async function ln({apiBase:r,authToken:e,body:t}){let n;try{n=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(i){throw new P("network",`begin fetch failed: ${i.message}`)}let s=null;try{s=await n.json()}catch{}if(!n.ok){if(n.status===404){let i=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(n.status===429){let i=s?.quotaInfo||{},o=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw o.code="SUBGRAPH_QUOTA_EXCEEDED",o.status=429,o.quotaInfo=i,o}if(n.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 ${n.status}`)}return s?.data||s}async function H({apiBase:r,authToken:e,payload:t}){try{let n=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function un(r,e){let t=W(e,".ready"),n=W(e,"graph.mjs");if(J(t)&&J(n))return;tn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),u=o(s,"wx");a(u),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(J(t)&&J(n))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,p)=>{let m=dt("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});m.stdout.pipe(c.stdin);let l,S,w=()=>{if(l!==void 0&&S!==void 0){if(l!==0)return p(new Error(`curl exited ${l}`));if(S!==0)return p(new Error(`tar exited ${S}`));u()}};m.on("close",b=>{l=b,w()}),c.on("close",b=>{S=b,w()}),m.on("error",p),c.on("error",p)});let{writeFileSync:o,unlinkSync:a}=await import("node:fs");o(t,"");try{a(s)}catch{}}catch(o){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",o.message)}}async function pn(r){let e=W(r,"graph.mjs");if(!J(e))throw new P("entry-missing",`graph.mjs missing under ${r}`);let t;try{t=await import(rn(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let n=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!n)throw new P("entry-class-missing","no buildGraph() class export found");return n}async function yt(r,e={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=q(),n;try{n=cn()}catch(d){throw d}E.debug(`[in-process subgraph] begin '${r}' parent=${t.executionId||"<root>"}`);let s=await ln({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:r,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:u,workflowVersion:p,workflowUuid:m,bundleReady:c,nodeConfigs:l}=s,S=on();if(o&&o!==S)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${S} vs ${o}`);if(!c||!a)throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let w=pt(r);if(!w){let d=W(de,`${m}@${p||"0"}`);try{await un(a,d);try{fn()}catch{}}catch(v){throw v.fallback&&await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason}}}),v}try{w=await pn(d),lt(r,w,{workflowUuid:m,version:p,runtimeTag:o,cacheDir:d})}catch(v){throw ut(r,v),await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:v.message,code:v.reason||"IMPORT_FAILED"}}}),v.fallback?v:new P("import-failed",v.message)}}let b=Date.now(),$=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=l&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,f={...e.input||{},...I?{nodeConfigs:l}:{}},g,y;try{g=await an($,async()=>{let v=await(typeof w=="function"&&w.prototype?.buildGraph?new w:w).buildGraph();return it({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>v.run(e.parentAgent,f,{signal:e.signal}))}),y=g&&typeof g=="object"&&"state"in g?g.state:g}catch(d){throw await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"failed",error:{message:d.message,code:d.code||"CHILD_THREW",stack:d.stack},durationMs:Date.now()-b}}),d}if(g&&typeof g=="object"&&g.stoppedExternally){await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"canceled",finalState:y,durationMs:Date.now()-b}});let d=new Error(`Sub-graph '${r}' canceled by parent abort`);throw d.code="SUBGRAPH_CANCELED",d.subgraphJobId=i,d}return await H({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-b}}),{finalState:y,executionId:i}}function dn(r){let e=0,t=[r];for(;t.length;){let n=t.pop(),s;try{s=gt(n)}catch{continue}if(s.isDirectory()){let i;try{i=mt(n)}catch{continue}for(let o of i)t.push(W(n,o))}else e+=s.size}return e}function fn({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(de))return{evicted:0,freedBytes:0};let e=mt(de),t=[],n=0;for(let a of e){let u=W(de,a),p;try{p=gt(u)}catch{continue}let m=p.isDirectory()?dn(u):p.size;n+=m,t.push({name:a,full:u,size:m,mtimeMs:p.mtimeMs})}if(n<=r)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,u)=>a.mtimeMs-u.mtimeMs);let s=Math.floor(r*.7),i=0,o=0;for(let a of t){if(n-i<=s)break;if(!J(W(a.full,".lock")))try{nn(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(u){E.debug(`[sub-graph cache] evict skip ${a.name}: ${u.message}`)}}return o>0&&E.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:n-i}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var hn=2e3,gn=600*1e3,mn=new Set(["completed","failed","canceled","timeout"]);function yn(){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 Sn(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function wn(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function _n(){return process.env.EXECUTION_ID||null}function St(r,e){return e==null?r:typeof e=="function"?e(r):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],r):r}async function wt(r,e={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=q();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:y}=await yt(r,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),d=St(y,e.output);return E.info(`[sub-graph] '${r}' completed in-process`),d}catch(y){if(y instanceof P||y?.fallback)E.info(`[sub-graph] in-process fallback for '${r}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let s=yn(),i=Sn(),o=wn(),a=_n(),u=`${s}/projects/${encodeURIComponent(i)}/workflows/${encodeURIComponent(r)}/trigger`,p={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${r}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(p)});if(!m.ok){let y=null,d="";try{y=await m.json(),d=y?.error||y?.message||JSON.stringify(y)}catch{d=await m.text().catch(()=>"")}if(m.status===429){let T=y?.quotaInfo||{},M=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 M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=r,M.quotaInfo=T,M}if(m.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${d}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=y?.validationErrors||null,T.missing=y?.missing||null,T}let v=new Error(`Sub-graph '${r}' trigger rejected (${m.status}): ${d}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=m.status,v.subgraph=r,v}let c=await m.json(),l=c?.data?.jobId||c?.jobId;if(!l)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${l} (not waiting)`),{jobId:l,status:"accepted",workflow:r};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:gn,w=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:hn,b=`${s}/executions/${encodeURIComponent(l)}`,$=Date.now()+S,I="accepted",f=0;for(;Date.now()<$;){await new Promise(T=>setTimeout(T,w)),f+=1;let y=await fetch(b,{headers:{Authorization:`Bearer ${o}`}});if(!y.ok){if(y.status>=500){E.warn(`[sub-graph] status poll for ${l} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${l}: ${y.status}`)}let d=await y.json(),v=d?.data||d?.execution||d;if(I=v?.status||I,mn.has(I)){if(I!=="completed"){let V=new Error(`Sub-graph '${r}' (${l}) ended in status '${I}'`);throw V.subgraphJobId=l,V.subgraphStatus=I,V}let T=v?.finalState||v?.state||{},M=St(T,e.output);return E.info(`[sub-graph] '${r}' (${l}) completed after ${f} polls`),M}}let g=new Error(`Sub-graph '${r}' (${l}) timed out after ${Math.round(S/1e3)}s (last status: ${I})`);throw g.subgraphJobId=l,g.subgraphStatus=I,g}import{existsSync as _t,readFileSync as bn}from"node:fs";import{join as Re,dirname as bt}from"node:path";var fe=class{static async loadContext(e,t,n={}){let s={},i=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=bt(Re(t,e));for(let u of i){let p=await this.findAndMergeContextFiles(u,a,t);if(p){let m=u.replace(/\.[^.]+$/,"").toLowerCase();s[m]=p}}}let o=n.discovery||{};for(let[a,u]of Object.entries(o))try{let p=Re(t,u);_t(p)&&(s[a]=await this.loadFile(p))}catch(p){console.warn(`[workflow] could not load context '${a}' from '${u}': ${p.message}`)}return s}static async findAndMergeContextFiles(e,t,n){let s=[],i=t;for(;i.startsWith(n);){let o=Re(i,e);if(_t(o))try{s.unshift(await this.loadFile(o))}catch(u){console.warn(`[workflow] could not load ${e} from ${o}: ${u.message}`)}let a=bt(i);if(a===i)break;i=a}return s.length===0?null:s.every(o=>typeof o=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):
|
|
38
|
+
`):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=bn(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),s=await import(n(e).href);return s.default||s}return t}};import{mkdirSync as vt,existsSync as Be,writeFileSync as It,unlinkSync as In}from"node:fs";import{join as z,resolve as At}from"node:path";import{config as En}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import $n from"handlebars";function vn({traceFrom:r,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let o=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${o} sessionId=${e} source=${n} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let m=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
41
|
-
${h}`)}}function _n(){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 In(){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 Ie(String(t).trim())}catch{return String(t).trim()}}function bn(){_n()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function En({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 $n(r={}){let t=qt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),n=t||`${Date.now()}_${e}`,o=r.paths?.sessionPrefix;return o?`${o}_${n}`:n}function vn({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:n="resolveWorkflowSession"}={}){let o=e.sessionPath,i=e.sessionTimestamp,s="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{let p=Ie(String(process.env.ZIBBY_SESSION_PATH));p&&(o=p,s="ZIBBY_SESSION_PATH")}catch{}let a;if(o)a=String(o).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,s="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,s="config.sessionId"):(a=$n(t),s="generated")}i=i??Date.now();let h=t.paths?.output||at;o=J(r,h,Zt,a)}let u=!xt(o);return u&&_e(o,{recursive:!0}),(u||s!=="initialState.sessionPath")&&wn({traceFrom:n,sessionId:a,sessionPath:o,idSource:s,mkdirFresh:u}),En({sessionPath:o,sessionId:a}),{sessionPath:o,sessionId:a,sessionTimestamp:i}}var we=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,n={}){if(!(e instanceof D)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let s=e,a={name:t,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async p=>{let h=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof s.input=="function"?c=s.input(h):s.input&&typeof s.input=="object"?c=s.input:c={},he(s.workflow,{input:c,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(h):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:h?._signal,parentAgent:p?.agent})}},u=new D(a);return u.name=t,this.nodes.set(t,u),n.prompt&&this.nodePrompts.set(t,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(t,n),this}let o=!(e instanceof D)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof D?e:new D(o?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),n.prompt?this.nodePrompts.set(t,n.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(n).length>0&&this.nodeOptions.set(t,n),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:n}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:n}),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,n,o,i){let s=n;for(let a=t.length-1;a>=0;a--){let u=t[a],p=s;s=()=>u(e,p,o,i)}return s()}serialize(){let t=[],e={};for(let[c,l]of this.nodes){let S=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);t.push({id:c,type:S,data:{nodeType:S,label:c}});let y={};l._isCustomCode&&typeof l.execute=="function"&&(y.customCode=l.execute.toString());let w=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;w&&(y.description=w);let T=this.nodePrompts.get(c);if(T)y.prompt=T;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(y.prompt=d,y.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(y.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(y.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof ut?.toJSONSchema=="function")try{d=ut.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=Se(l.outputSchema,{target:"openApi3"})}catch{}y.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else y.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[c];$?.toolIds&&(y.tools=$.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(y.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(y.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let m=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;m&&m.length>0&&(y.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(y).length>0&&(e[c]=y)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(l.conditional){let S=this.conditionalCodeMap.get(c)||l.routes.toString(),y=this._inferConditionalTargets(l.routes,l.labels),w=l.labels||{},T=this.nodes.get(c),$=T?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!T,f=c;if(!$){let g=`${c}__branch`;t.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of y){let m={source:f,target:g,data:{conditionalCode:S}};w[g]&&(m.label=w[g]),n.push(m)}}let o=c=>{if(!c)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(c)}catch{}try{return Se(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let s=this._topoOrderNodes(t,n),a=this._runtimeSchema(),u=o(a||this.stateSchema),p=o(this.inputSchema),h=o(this.contextSchema);return{nodes:s,edges:n,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:h}}_topoOrderNodes(t,e){let n=new Map(t.map((c,l)=>[c.id,l])),o=new Map(t.map(c=>[c.id,c])),i=new Map(t.map(c=>[c.id,0])),s=new Map(t.map(c=>[c.id,[]]));for(let c of e)s.has(c.source)&&i.has(c.target)&&(s.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>i.get(c)===0),h=[];for(;h.length<t.length;){let c;if(p.length>0){if(p.sort((l,S)=>n.get(l)-n.get(S)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,S)=>n.get(l)-n.get(S))[0];a.add(c),u.delete(c),h.push(o.get(c));for(let l of s.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return h}_inferConditionalTargets(t,e){let n=t.toString(),o=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=i.exec(n))!==null;){let p=s[2]!==void 0?s[2]:s[3];p!==void 0&&p!==""&&o.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))a.add(p);let u=new Set;for(let p of o)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=p.exec(n))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let n=t;if(t.$ref&&t.definitions){let o=t.$ref.replace("#/definitions/","");n=t.definitions[o]||t}return this._flattenSchema(n,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let n=[],o=t.properties||{},i=t.required||[];for(let[s,a]of Object.entries(o)){let u=e?`${e}.${s}`:s;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}return n}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let n=[];e.success!==void 0&&n.push(`Result: ${e.success?"passed":"failed"}`);for(let[o,i]of Object.entries(e))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${o}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);n.push(u?`${o}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${o}: ${s} items`)}if(n.length>=4)break}return n}async run(t,e={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let o=new AbortController;n.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,s=e.cwd||process.cwd();yn({path:J(s,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let b=J(s,".zibby.config.js");xt(b)&&(a=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let b=a?.agent;b?.provider?u=b.provider:b?.gemini?u="gemini":b?.claude?u="claude":b?.cursor?u="cursor":b?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},h=this._runtimeSchema();if(h){let b=h.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(", ")}`)}P.step("State validated against schema")}let c=In(),l=e.sessionPath||c;l||bn();let{sessionPath:S,sessionTimestamp:y,sessionId:w}=vn({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});P.step(`Session ${w}`);let T=await lt.loadContext(e.specPath||"",s,p);Object.keys(T).length>0&&P.step(`Context loaded: ${Object.keys(T).join(", ")}`);let $=e.outputPath;!$&&e.specPath&&(t?.calculateOutputPath?$=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let f=new ot({...e,config:a,agentType:u,outputPath:$,sessionPath:S,sessionTimestamp:y,context:T,resolvedTools:this.resolvedToolsMap||{},_signal:o.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(wt(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},E=Object.values(d).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),k=b=>{for(let N of E)if(N.id===b)return N;return m(b)},M=new Set;for(let[,b]of this.nodes)for(let N of b.config?.skills||[])M.add(N);for(let b of M){let N=k(b);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&g.set(b,R)}catch{}}let _=this.entryPoint,tt=[],Pt=a?.recursionLimit??100,be=0;try{for(;_&&_!=="END";){if(++be>Pt)throw new Error(`Workflow exceeded recursion limit (${Pt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=J(S,zt);if(xt(N)){try{mn(N)}catch{}o.abort()}if(o.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
${m}`)}}function An(){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 Tn(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return At(String(e).trim())}catch{return String(e).trim()}}function kn(){An()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function xn({sessionPath:r,sessionId:e}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function On(r={}){let e=Qe.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,s=r.paths?.sessionPrefix;return s?`${s}_${n}`:n}function Pn({cwd:r=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=At(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,o="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(a=c,o="config.sessionId"):(a=On(e),o="generated")}i=i??Date.now();let m=e.paths?.output||pe;s=z(r,m,Ke,a)}let u=!Be(s);return u&&vt(s,{recursive:!0}),(u||o!=="initialState.sessionPath")&&vn({traceFrom:n,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:u}),xn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var $t=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let o=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:o.workflow,retries:o.retries,onComplete:o.onComplete,execute:async p=>{let m=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof o.input=="function"?c=o.input(m):o.input&&typeof o.input=="object"?c=o.input:c={},wt(o.workflow,{input:c,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(m):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:m?._signal,parentAgent:p?.agent})}},u=new L(a);return u.name=e,this.nodes.set(e,u),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let s=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof L?t:new L(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){let n=this.edges.get(e);return n===void 0?this.edges.set(e,t):typeof n=="string"?n!==t&&this.edges.set(e,[n,t]):Array.isArray(n)?n.includes(t)||n.push(t):(console.warn(`[workflow] addEdge('${e}', '${t}') overrides the conditional edges already declared on '${e}'. A node routes EITHER unconditionally (addEdge) OR conditionally (addConditionalEdges) \u2014 not both.`),this.edges.set(e,t)),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){let s=this.edges.get(e);return s!==void 0&&!s.conditional&&console.warn(`[workflow] addConditionalEdges('${e}', \u2026) overrides the unconditional edge(s) already declared on '${e}' (${Array.isArray(s)?s.join(", "):s}). A node routes EITHER unconditionally OR conditionally \u2014 not both.`),this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}_simpleTargets(e){let t=this.edges.get(e);return t===void 0?[]:typeof t=="string"?[t]:Array.isArray(t)?t:[]}_analyzeFlow(){let e=new Set,t=new Map,n=i=>{t.set(i,1);for(let o of this._simpleTargets(i)){if(!o||o==="END")continue;let a=t.get(o)||0;a===1?e.add(`${i}->${o}`):a===0&&n(o)}t.set(i,2)};this.entryPoint&&n(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let o of this._simpleTargets(i))!o||o==="END"||e.has(`${i}->${o}`)||s.set(o,(s.get(o)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,s,i){let o=n;for(let a=e.length-1;a>=0;a--){let u=e[a],p=o;o=()=>u(t,p,s,i)}return o()}serialize(){let e=[],t={};for(let[c,l]of this.nodes){let S=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);e.push({id:c,type:S,data:{nodeType:S,label:c}});let w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let b=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;b&&(w.description=b);let $=this.nodePrompts.get(c);if($)w.prompt=$;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(w.prompt=d,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof he?.toJSONSchema=="function")try{d=he.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=Et(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let I=(this.resolvedToolsMap||{})[c];I?.toolIds&&(w.tools=I.toolIds);let f=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;f&&f.length>0&&(w.skills=[...f]);let g=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;g&&g.length>0&&(w.plugins=g.map(d=>d&&typeof d=="object"?{...d}:d));let y=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;y&&y.length>0&&(w.stores=y.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(w).length>0&&(t[c]=w)}let n=[];for(let[c,l]of this.edges)if(typeof l=="string")n.push({source:c,target:l});else if(Array.isArray(l))for(let S of l)n.push({source:c,target:S});else if(l.conditional){let S=this.conditionalCodeMap.get(c)||l.routes.toString(),w=this._inferConditionalTargets(l.routes,l.labels),b=l.labels||{},$=this.nodes.get(c),I=$?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!$,f=c;if(!I){let g=`${c}__branch`;e.push({id:g,type:"decision",data:{nodeType:"decision",label:g}}),n.push({source:c,target:g}),f=g}for(let g of w){let y={source:f,target:g,data:{conditionalCode:S}};b[g]&&(y.label=b[g]),n.push(y)}}let s=c=>{if(!c)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(c)}catch{}try{return Et(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of n)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:c,target:l})}let o=this._topoOrderNodes(e,n),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),m=s(this.contextSchema);return{nodes:o,edges:n,nodeConfigs:t,stateSchema:u,inputSchema:p,contextSchema:m}}_topoOrderNodes(e,t){let n=new Map(e.map((c,l)=>[c.id,l])),s=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id,0])),o=new Map(e.map(c=>[c.id,[]]));for(let c of t)o.has(c.source)&&i.has(c.target)&&(o.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(n.keys()),p=[...u].filter(c=>i.get(c)===0),m=[];for(;m.length<e.length;){let c;if(p.length>0){if(p.sort((l,S)=>n.get(l)-n.get(S)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,S)=>n.get(l)-n.get(S))[0];a.add(c),u.delete(c),m.push(s.get(c));for(let l of o.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return m}_inferConditionalTargets(e,t){let n=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(n))!==null;){let p=o[2]!==void 0?o[2]:o[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(t&&typeof t=="object")for(let p of Object.keys(t))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,m;for(;(m=p.exec(n))!==null;)u.add(m[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");n=e.definitions[s]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let u=t?`${t}.${o}`:o;n.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${u}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,i]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)n.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);n.push(u?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t)&&(t=e.normalizeInput(t)??t);let s=new AbortController;n.signal&&(n.signal.aborted?s.abort():n.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();En({path:z(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=z(o,".zibby.config.js");Be(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=t.agentType;if(!u){let _=a?.agent;_?.provider?u=_.provider:_?.gemini?u="gemini":_?.claude?u="claude":_?.cursor?u="cursor":_?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},m=this._runtimeSchema();if(m){let _=m.safeParse(t);if(!_.success){let h=_.error.issues.map(B=>`${B.path.join(".")}: ${B.message}`);throw console.error("\u274C Initial state validation failed:"),h.forEach(B=>console.error(` - ${B}`)),new Error(`State validation failed: ${h.join(", ")}`)}O.step("State validated against schema")}let c=Tn(),l=t.sessionPath||c;l||kn();let{sessionPath:S,sessionTimestamp:w,sessionId:b}=Pn({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${b}`);let $=await fe.loadContext(t.specPath||"",o,p);Object.keys($).length>0&&O.step(`Context loaded: ${Object.keys($).join(", ")}`);let I=t.outputPath;!I&&t.specPath&&(e?.calculateOutputPath?I=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ce({...t,config:a,agentType:u,outputPath:I,sessionPath:S,sessionTimestamp:w,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ve(),tt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},v=Object.values(d).filter(_=>_&&typeof _=="object"&&typeof _.id=="string"),T=_=>{for(let h of v)if(h.id===_)return h;return y(_)},M=new Set;for(let[,_]of this.nodes)for(let h of _.config?.skills||[])M.add(h);for(let _ of M){let h=T(_);if(typeof h?.middleware=="function")try{let B=await h.middleware();typeof B=="function"&&g.set(_,B)}catch{}}let{backEdges:V,joinDegree:Tt}=this._analyzeFlow(),ge=new Map,K=[],me=(_,h,B)=>{if(!_||_==="END")return;let j=Tt.get(_)||0;if(B&&j>1&&!V.has(`${h}->${_}`)){let X=(ge.get(_)||0)+1;if(X<j){ge.set(_,X);return}ge.set(_,0)}K.includes(_)||K.push(_)};this.entryPoint&&K.push(this.entryPoint);let se=[],Ce=a?.recursionLimit??100,kt=0;try{for(;K.length>0;){let h=K.pop();if(!h||h==="END")continue;if(++kt>Ce)throw new Error(`Workflow exceeded recursion limit (${Ce}) \u2014 the cap counts NODE EXECUTIONS, so this is either a cyclic conditional route or a graph whose branches total more nodes than the cap. Set config.recursionLimit if you need a higher cap.`);let B=z(S,Xe);if(Be(B)){try{In(B)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};let j=this.nodes.get(h);if(!j)throw new Error(`Node '${h}' not found in graph`);let X=JSON.stringify({sessionPath:S,sessionTimestamp:w,currentNode:h,createdAt:new Date().toISOString(),config:f.get("config")}),xt=z(S,Z);It(xt,X,"utf-8");let Me=f.get("config")?.paths?.output||pe,Ot=z(o,Me,Z);vt(z(o,Me),{recursive:!0});try{It(Ot,X,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:o,sessionPath:S,sessionId:b,outputBase:f.get("config")?.paths?.output||pe,currentNode:h})}catch{}let Pt=(this.resolvedToolsMap||{})[h]||null;f.set("_currentNodeTools",Pt);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[h]||{}),O.nodeStart(h);let De=Date.now(),oe=this.nodePrompts.get(h);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(ke(),Te));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,ye={},Bt=j.config?.skills||[];for(let k of Bt){let N=T(k);if(typeof N?.invokeAgentOptions=="function")try{let A=N.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:h});A&&typeof A=="object"&&(ye={...ye,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let Le=async(k,N,A={})=>{let C=Rt(k,N,{...ye,...A,signal:s.signal});return C.catch(()=>{}),s.signal.aborted?C:Promise.race([C,new Promise((Y,D)=>{let R=()=>{setTimeout(()=>{let Q=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Q.name="AbortError",D(Q)},i)};s.signal.addEventListener("abort",R,{once:!0})})])},Ct=async(k={},N={})=>{let A=N.prompt||"";if(oe){let C=this._compiledPrompts.get(h);C||(C=$n.compile(oe,{noEscape:!0}),this._compiledPrompts.set(h,C));try{A=C(k)}catch(Y){throw console.error(`\u274C Template rendering failed for node '${h}':`,Y.message),new Error(`Template rendering failed: ${Y.message}`,{cause:Y})}}else if(!A)throw new Error(`No prompt template configured for node '${h}' and no prompt provided in options`);return Le(A,{state:f.getAll(),images:N.images||[]},{model:N.model||f.get("model"),workspace:f.get("workspace"),schema:N.schema,...N,signal:s.signal})},We=f.getAll(),Mt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Mt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${h}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ue={...We,state:f,invokeAgent:Ct,_coreInvokeAgent:Le,agent:e,nodeId:h,promptTemplate:oe,getPromptTemplate:()=>oe};try{let k=(j.config?.skills||[]).map(R=>g.get(R)).filter(Boolean),N=[...this.middleware,...k],A;A=await at(e,s.signal,async()=>N.length>0?this._composeMiddleware(N,h,async()=>j.execute(Ue,f),f.getAll(),f):j.execute(Ue,f));let C=Date.now()-De;if(se.push({node:h,success:A.success,duration:C,timestamp:new Date().toISOString()}),!A.success){if(s.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:se,stoppedExternally:!0};f.append("errors",{node:h,error:A.error});let R=j.config?.retries||0,Q=`${h}_retries`,ie=f.getAll()[Q]||0;if(ie<R){O.stepInfo(`Retrying (attempt ${ie+1}/${R})`),f.update({[Q]:ie+1,[`${h}_raw`]:A.raw});continue}throw O.nodeFailed(h,A.error,{duration:C}),new Error(`Node '${h}' failed after ${ie} attempts: ${A.error}`)}f.update({[h]:A.output});let Y=this._summarizeNodeOutput(h,A.output);O.nodeComplete(h,{duration:C,details:Y});let D=this.edges.get(h);if(D)if(D.conditional){let R=D.routes(f.getAll());O.route(h,R),me(R,h,!1)}else if(Array.isArray(D))for(let R=D.length-1;R>=0;R--)me(D[R],h,!0);else me(D,h,!0)}catch(k){throw O.isInsideNode&&O.nodeFailed(h,k.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",h),k}}O.graphComplete();let _={success:!0,state:f.getAll(),executionLog:se};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};export{$t as WorkflowGraph,kn as clearInheritedSessionEnvForFreshRun,On as generateWorkflowSessionId,Tn as readPinnedSessionPathFromEnv,Pn as resolveWorkflowSession,An as shouldTrustInheritedSessionEnv,xn as syncProcessEnvToSession};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as Y,existsSync as I,statSync as N,readdirSync as C,rmSync as W}from"node:fs";import{spawn as j}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as Z}from"node:url";import{AsyncLocalStorage as K}from"node:async_hooks";var R=()=>{},q={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k={impl:q};var b={debug:(...e)=>k.impl.debug?.(...e),info:(...e)=>k.impl.info?.(...e),warn:(...e)=>k.impl.warn?.(...e),error:(...e)=>k.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var _=new V;function B(){let e=_.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function O(e,n){let r=_.getStore()||B(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null});return _.run(t,n)}var A=new Map,$=new Map,P=new Map;function M(e,n,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof n!="function")throw new Error("subgraph-registry.register: factory must be a function");A.set(e,n),$.set(e,"ready"),P.set(e,{...r,cachedAt:Date.now()})}function D(e,n){$.set(e,"failed"),P.set(e,{error:n?.message||String(n),failedAt:Date.now()}),A.delete(e)}function U(e){return $.get(e)==="ready"?A.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Q(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(n,r){super(`in-process sub-graph fallback: ${n}${r?` (${r})`:""}`),this.fallback=!0,this.reason=n,this.detail=r||null,this.name="SubgraphFallback"}},L=new K,H=Promise.resolve();async function ee(e,n){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(r.length===0)return n();let t=L.getStore()===!0,s=null;if(!t){let a=H;H=new Promise(i=>{s=i}),await a}let o=new Map;try{for(let[a,i]of r)o.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return b.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${t?" (nested)":""}`),await L.run(!0,n)}finally{for(let[a,i]of o)i===void 0?delete process.env[a]:process.env[a]=i;s&&s()}}function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),n=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||n,t=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!r||!t||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:t,authToken:s}}async function ne({apiBase:e,authToken:n,body:r}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)})}catch(o){throw new l("network",`begin fetch failed: ${o.message}`)}let 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 l("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function E({apiBase:e,authToken:n,payload:r}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)});t.ok||b.warn(`[in-process subgraph] finalize returned ${t.status} for ${r.childExecutionId}`)}catch(t){b.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function re(e,n){let r=w(n,".ready"),t=w(n,"graph.mjs");if(I(r)&&I(t))return;Y(n,{recursive:!0});let s=w(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 l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let y=j("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=j("tar",["-xzf","-","-C",n],{stdio:["pipe","inherit","inherit"]});y.stdout.pipe(S.stdin);let f,m,h=()=>{if(f!==void 0&&m!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(m!==0)return p(new Error(`tar exited ${m}`));d()}};y.on("close",v=>{f=v,h()}),S.on("close",v=>{m=v,h()}),y.on("error",p),S.on("error",p)});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 l("bundle-extract-failed",a.message)}}async function oe(e){let n=w(e,"graph.mjs");if(!I(n))throw new l("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(Z(n).href)}catch(s){throw new l("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 l("entry-class-missing","no buildGraph() class export found");return t}async function ge(e,n={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=B(),t;try{t=te()}catch(c){throw c}b.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let s=await ne({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:n.input||{},...n.conversationId?{conversationId:n.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:y,bundleReady:S,nodeConfigs:f}=s,m=Q();if(a&&a!==m)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new l("runtime-mismatch",`${m} vs ${a}`);if(!S||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new l("no-bundle","workflow bundle not built yet");let h=U(e);if(!h){let c=w(x,`${y}@${p||"0"}`);try{await re(i,c);try{ae()}catch{}}catch(u){throw u.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{h=await oe(c),M(e,h,{workflowUuid:y,version:p,runtimeTag:a,cacheDir:c})}catch(u){throw D(e,u),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new l("import-failed",u.message)}}let v=Date.now(),G=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,F=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,J={...n.input||{},...F?{nodeConfigs:f}:{}},g,T;try{g=await ee(G,async()=>{let u=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return O({executionId:o,parentExecutionId:r.executionId,conversationId:n.conversationId!==void 0?n.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>u.run(n.parentAgent,J,{signal:n.signal}))}),T=g&&typeof g=="object"&&"state"in g?g.state:g}catch(c){throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(g&&typeof g=="object"&&g.stoppedExternally){await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:T,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:T,durationMs:Date.now()-v}}),{finalState:T,executionId:o}}function we(){try{if(!I(x))return{bytes:0,entries:0};let e=C(x),n=0;for(let r of e)try{n+=z(w(x,r))}catch{}return{bytes:n,entries:e.length}}catch{return{bytes:0,entries:0}}}function z(e){let n=0,r=[e];for(;r.length;){let t=r.pop(),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(w(t,a))}else n+=s.size}return n}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!I(x))return{evicted:0,freedBytes:0};let n=C(x),r=[],t=0;for(let i of n){let d=w(x,i),p;try{p=N(d)}catch{continue}let y=p.isDirectory()?z(d):p.size;t+=y,r.push({name:i,full:d,size:y,mtimeMs:p.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(w(i.full,".lock")))try{W(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){b.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&b.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 b.debug(`[sub-graph cache] evict failed: ${n.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,ae as evictCacheIfOver,we as getCacheStats,ge as runInProcessSubgraph};
|
|
1
|
+
import{mkdirSync as Y,existsSync as b,statSync as G,readdirSync as C,rmSync as W}from"node:fs";import{spawn as U}from"node:child_process";import{join as w}from"node:path";import{pathToFileURL as Z}from"node:url";import{AsyncLocalStorage as K}from"node:async_hooks";var O=()=>{},q={debug:O,info:O,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},T={impl:q};var m={debug:(...e)=>T.impl.debug?.(...e),info:(...e)=>T.impl.info?.(...e),warn:(...e)=>T.impl.warn?.(...e),error:(...e)=>T.impl.error?.(...e)};import{AsyncLocalStorage as V}from"node:async_hooks";var B=new V;function _(){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,agent:null,signal:null})}function R(e,r){let n=B.getStore()||_(),t=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return B.run(t,r)}var A=new Map,$=new Map,P=new Map;function j(e,r,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof r!="function")throw new Error("subgraph-registry.register: factory must be a function");A.set(e,r),$.set(e,"ready"),P.set(e,{...n,cachedAt:Date.now()})}function D(e,r){$.set(e,"failed"),P.set(e,{error:r?.message||String(r),failedAt:Date.now()}),A.delete(e)}function M(e){return $.get(e)==="ready"?A.get(e):null}var x=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Q(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var l=class extends Error{constructor(r,n){super(`in-process sub-graph fallback: ${r}${n?` (${n})`:""}`),this.fallback=!0,this.reason=r,this.detail=n||null,this.name="SubgraphFallback"}},z=new K,L=Promise.resolve();async function ee(e,r){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(n.length===0)return r();let t=z.getStore()===!0,s=null;if(!t){let a=L;L=new Promise(i=>{s=i}),await a}let o=new Map;try{for(let[a,i]of n)o.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return m.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${t?" (nested)":""}`),await z.run(!0,r)}finally{for(let[a,i]of o)i===void 0?delete process.env[a]:process.env[a]=i;s&&s()}}function te(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),r=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||r,t=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!n||!t||!s)throw new l("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:t,authToken:s}}async function ne({apiBase:e,authToken:r,body:n}){let t;try{t=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)})}catch(o){throw new l("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 '${n.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 l("begin-status",`begin returned ${t.status}`)}return s?.data||s}async function E({apiBase:e,authToken:r,payload:n}){try{let t=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(n)});t.ok||m.warn(`[in-process subgraph] finalize returned ${t.status} for ${n.childExecutionId}`)}catch(t){m.warn(`[in-process subgraph] finalize failed: ${t.message}`)}}async function re(e,r){let n=w(r,".ready"),t=w(r,"graph.mjs");if(b(n)&&b(t))return;Y(r,{recursive:!0});let s=w(r,".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(b(n)&&b(t))return;await new Promise(i=>setTimeout(i,100))}throw new l("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((d,p)=>{let g=U("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),S=U("tar",["-xzf","-","-C",r],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(S.stdin);let f,I,h=()=>{if(f!==void 0&&I!==void 0){if(f!==0)return p(new Error(`curl exited ${f}`));if(I!==0)return p(new Error(`tar exited ${I}`));d()}};g.on("close",v=>{f=v,h()}),S.on("close",v=>{I=v,h()}),g.on("error",p),S.on("error",p)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(n,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new l("bundle-extract-failed",a.message)}}async function oe(e){let r=w(e,"graph.mjs");if(!b(r))throw new l("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(Z(r).href)}catch(s){throw new l("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let t=n.default||Object.values(n).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!t)throw new l("entry-class-missing","no buildGraph() class export found");return t}async function ye(e,r={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=_(),t;try{t=te()}catch(c){throw c}m.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let s=await ne({apiBase:t.apiBase,authToken:t.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:r.input||{},...r.conversationId?{conversationId:r.conversationId}:{}}}),{childExecutionId:o,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:d,workflowVersion:p,workflowUuid:g,bundleReady:S,nodeConfigs:f}=s,I=Q();if(a&&a!==I)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,discard:!0}}),new l("runtime-mismatch",`${I} vs ${a}`);if(!S||!i)throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,discard:!0}}),new l("no-bundle","workflow bundle not built yet");let h=M(e);if(!h){let c=w(x,`${g}@${p||"0"}`);try{await re(i,c);try{ae()}catch{}}catch(u){throw u.fallback&&await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason}}}),u}try{h=await oe(c),j(e,h,{workflowUuid:g,version:p,runtimeTag:a,cacheDir:c})}catch(u){throw D(e,u),await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:u.message,code:u.reason||"IMPORT_FAILED"}}}),u.fallback?u:new l("import-failed",u.message)}}let v=Date.now(),N=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,F=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0,J={...r.input||{},...F?{nodeConfigs:f}:{}},y,k;try{y=await ee(N,async()=>{let u=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return R({executionId:o,parentExecutionId:n.executionId,conversationId:r.conversationId!==void 0?r.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>u.run(r.parentAgent,J,{signal:r.signal}))}),k=y&&typeof y=="object"&&"state"in y?y.state:y}catch(c){throw await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"failed",error:{message:c.message,code:c.code||"CHILD_THREW",stack:c.stack},durationMs:Date.now()-v}}),c}if(y&&typeof y=="object"&&y.stoppedExternally){await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"canceled",finalState:k,durationMs:Date.now()-v}});let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=o,c}return await E({apiBase:t.apiBase,authToken:t.authToken,payload:{childExecutionId:o,status:"completed",finalState:k,durationMs:Date.now()-v}}),{finalState:k,executionId:o}}function we(){try{if(!b(x))return{bytes:0,entries:0};let e=C(x),r=0;for(let n of e)try{r+=H(w(x,n))}catch{}return{bytes:r,entries:e.length}}catch{return{bytes:0,entries:0}}}function H(e){let r=0,n=[e];for(;n.length;){let t=n.pop(),s;try{s=G(t)}catch{continue}if(s.isDirectory()){let o;try{o=C(t)}catch{continue}for(let a of o)n.push(w(t,a))}else r+=s.size}return r}function ae({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!b(x))return{evicted:0,freedBytes:0};let r=C(x),n=[],t=0;for(let i of r){let d=w(x,i),p;try{p=G(d)}catch{continue}let g=p.isDirectory()?H(d):p.size;t+=g,n.push({name:i,full:d,size:g,mtimeMs:p.mtimeMs})}if(t<=e)return{evicted:0,freedBytes:0,totalBytes:t};n.sort((i,d)=>i.mtimeMs-d.mtimeMs);let s=Math.floor(e*.7),o=0,a=0;for(let i of n){if(t-o<=s)break;if(!b(w(i.full,".lock")))try{W(i.full,{recursive:!0,force:!0}),o+=i.size,a+=1}catch(d){m.debug(`[sub-graph cache] evict skip ${i.name}: ${d.message}`)}}return a>0&&m.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(o/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:o,totalBytes:t-o}}catch(r){return m.debug(`[sub-graph cache] evict failed: ${r.message}`),{evicted:0,freedBytes:0}}}export{l as SubgraphFallback,ae as evictCacheIfOver,we as getCacheStats,ye as runInProcessSubgraph};
|