@zibby/agent-workflow 2.0.4 → 2.0.6
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 +1 -0
- package/dist/failure-class.d.ts +193 -0
- package/dist/failure-class.js +1 -0
- package/dist/fetch-deadline.d.ts +78 -0
- package/dist/fetch-deadline.js +1 -0
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.js +20 -20
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +33 -33
- package/dist/node.js +18 -18
- package/dist/sub-graph-executor.d.ts +2 -0
- package/dist/sub-graph-executor.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ln=Object.defineProperty;var Ce=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var be=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var It=(n,e)=>{for(var t in e)Ln(n,t,{get:e[t],enumerable:!0})};function Wn(n){le.impl={...At,...n}}var vt,At,De,le,v,H=be(()=>{vt=()=>{},At={debug:vt,info:vt,warn:(...n)=>console.warn("[workflow]",...n),error:(...n)=>console.error("[workflow]",...n)},De=Symbol.for("@zibby/agent-workflow.logger");globalThis[De]||(globalThis[De]={impl:At});le=globalThis[De];v={debug:(...n)=>le.impl.debug?.(...n),info:(...n)=>le.impl.info?.(...n),warn:(...n)=>le.impl.warn?.(...n),error:(...n)=>le.impl.error?.(...n)}});var Ze,Ke=be(()=>{Ze=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var Kt={};It(Kt,{clearSkills:()=>Zt,getAllSkills:()=>Jt,getSkill:()=>te,getSkillSource:()=>zt,hasSkill:()=>Ht,listSkillIds:()=>Yt,registerSkill:()=>Wt});function Wt(n,e={}){if(!n||typeof n.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:r=!1}=e,s=n.id;if(Z.has(s)&&!r){let i=pe.get(s);if(!(i===t)){let a=i||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${s}" is already registered by ${a}; ${l} 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).`)}}Z.set(s,Object.freeze({...n})),t===void 0?pe.delete(s):pe.set(s,t)}function te(n){return Z.get(n)||null}function Ht(n){return Z.has(n)}function zt(n){return pe.get(n)||null}function Jt(){return new Map(Z)}function Yt(){return Array.from(Z.keys())}function Zt(){Z.clear(),pe.clear()}var Ve,qe,Z,pe,fe=be(()=>{Ve=Symbol.for("@zibby/agent-workflow.skills"),qe=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Ve]||(globalThis[Ve]=new Map);globalThis[qe]||(globalThis[qe]=new Map);Z=globalThis[Ve],pe=globalThis[qe]});var he={};It(he,{getAgentStrategy:()=>tt,invokeAgent:()=>Xt,listStrategies:()=>qt,registerStrategy:()=>Vt,resolveInvocationExtras:()=>et,resolveInvocationModel:()=>Qe});function Vt(n){if(!n||typeof n.getName!="function"||typeof n.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=K.findIndex(t=>t.getName()===n.getName());e>=0?K[e]=n:K.push(n)}function qt(){return K.map(n=>n.getName())}function Qe({config:n={},options:e={},strategyName:t,envModel:r,nodeConfigModel:s}={}){let i=n.models||{},o=typeof s=="string"&&s.trim()?s.trim():null,a=e.nodeName&&i[e.nodeName]||null,l=i.default||null,u=n.agent?.[t]?.model||null,w=(typeof r=="string"?r.trim():"")||null;return o||a||l||u||e.model||w||null}function et({options:n={},stateView:e={},context:t={}}={}){return{workspace:e.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||e.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[]}}function tt(n={}){let{state:e={},preferredAgent:t=null}=n,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let i=K.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}v.debug(`[workflow] agent selection: requested=${r}`);let s=K.find(i=>i.getName()===r);if(!s){let i=K.map(o=>o.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!s.canHandle(n))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return v.debug(`[workflow] using agent: ${s.getName()}`),s}async function Xt(n,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},i=tt(s),o=r.config||t.config||{},a=r._currentNodeConfig||{},l=typeof a.agent=="string"?a.agent.trim():"",u=!l||l===i.name?a.model:null,w=Qe({config:o,options:t,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:u}),p={...t,model:w,...et({options:t,stateView:r,context:e}),config:o},c=n,m=p.skills||[];if(m.length>0&&!t.skipPromptFragments){let b=t.connectedIntegrations;if(!b){let y=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof y=="string"&&y.trim()!==""){b={};for(let g of y.split(",").map(h=>h.trim()).filter(Boolean))b[g]=!0}}let A=y=>{let g=y&&y.requiresIntegration;return!g||!b?!0:(Array.isArray(g)?g:[g]).some(S=>b[S]===!0)},f=i.name==="assistant",I=y=>y?.inProcessOnly!==!0||f,$=m.map(y=>{let g=te(y);if(!A(g)||!I(g))return null;let h=g?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);$.length>0&&(c+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${$.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let d=r._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let b=d.length<=8,A=d.map(f=>{let I=f?.id??f?.storeId??"",$=(f?.name??"").toString().trim()||I,y=f?.type?` \xB7 ${f.type}`:"",g=(f?.description||"").toString().replace(/\s+/g," ").trim(),h=`- ${$} \xB7 ${g||"(no description)"}${y} (id: ${I})`;if(b&&f?.schema&&typeof f.schema=="object"){let S=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);S.length&&(h+=`
|
|
6
|
+
fields: ${S.join(", ")}`)}return h});c+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${A.join(`
|
|
10
|
+
`)}`}let _=r._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(c+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
|
-
${
|
|
17
|
-
`)
|
|
16
|
+
${_}
|
|
17
|
+
`),v.debug(`[workflow] prompt length: ${c.length} chars`),i.invoke(c,p)}var Xe,K,ne=be(()=>{Ke();H();fe();Xe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Xe]||(globalThis[Xe]=[]);K=globalThis[Xe]});var Fn=new Set(["__proto__","constructor","prototype"]);function Be(n){if(Fn.has(n))throw new Error(`Invalid state key: "${n}"`)}var ae=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){Be(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)Be(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){Be(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 V from"handlebars";var ce=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 r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of r)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[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&s.type){let i=typeof e[r];i!==s.type&&t.push(`Field '${r}' expected ${s.type}, got ${i}`)}if(s.validate&&r in e){let i=s.validate(e[r]);i&&t.push(`Field '${r}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}},
|
|
20
|
-
`?(
|
|
21
|
-
${
|
|
19
|
+
`)}`);return e}},Gn={string:(n=!0)=>({type:"string",required:n}),number:(n=!0)=>({type:"number",required:n}),boolean:(n=!0)=>({type:"boolean",required:n}),array:(n=!0)=>({type:"object",required:n,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(n,e=!0)=>({type:"string",required:e,validate:t=>n.includes(t)?null:`must be one of: ${n.join(", ")}`})};H();import{writeFileSync as nt,readFileSync as Qt,existsSync as en,mkdirSync as Xn}from"node:fs";import{join as rt,dirname as Qn}from"node:path";import x from"chalk";var Mt="__WORKFLOW_GRAPH_LOG__",ue=x.gray("\u2502"),Hn=x.gray("\u250C"),$t=x.gray("\u2514"),je=x.green("\u25C6"),kt=x.hex("#c084fc")("\u25C6"),Nt=x.hex("#2dd4bf")("\u25C6"),Ue=x.red("\u25C6"),Ot=`${ue} `,xt=2;function Rt(n){return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Pt(n,e){return(t,r,s)=>{if(typeof t!="string")return n(t,r,s);let i=process.stdout.columns||120,o="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(o+=Ot,e.col=xt,e.lineStart=!1),l===`
|
|
20
|
+
`?(o+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,o+=l):e.inEsc?(o+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,o+=l,e.col>=i&&(o+=`
|
|
21
|
+
${Ot}`,e.col=xt))}return n(o,r,s)}}var Te=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=Pt(this._origStdoutWrite,e),process.stderr.write=Pt(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
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=`${
|
|
24
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Mt}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(je,e):process.stdout.write.bind(process.stdout)(`${ue} ${je} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(kt,e):process.stdout.write.bind(process.stdout)(`${ue} ${kt} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Nt,t):process.stdout.write.bind(process.stdout)(`${ue} ${Nt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ue,x.red(e)):process.stdout.write.bind(process.stdout)(`${ue} ${Ue} ${x.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Hn} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:s}=t;if(s)for(let o of s)this._rawWrite(`${je} ${o}`);let i=r?x.dim(` ${Rt(r)}`):"";this._rawWrite(`${$t} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,i=s?x.dim(` ${Rt(s)}`):"";this._rawWrite(`${Ue} ${x.red(t)}`),this._rawWrite(`${$t} ${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(){}},R=new Te;var de=".zibby/output",Le="sessions",Y=".session-info.json",Fe=".zibby-stop",zn="result.json",Jn="raw_stream_output.txt",Yn="events.json",Zn=Object.freeze(["codebase-memory","code-scan","artifact"]),Ge=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var Ct=Object.freeze({authentication_failed:"deterministic",oauth_org_not_allowed:"deterministic",billing_error:"deterministic",invalid_request:"deterministic",max_output_tokens:"deterministic",rate_limit:"transient",server_error:"transient",unknown:"inconclusive"}),Bt=Object.freeze([/stream idle timeout/i,/partial response received/i,/no chunks received/i,/stream ended without receiving any events/i,/stream completed without receiving/i,/socket hang up/i,/premature close/i,/\b(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|ENETRESET|EHOSTUNREACH)\b/,/\bfetch failed\b/i,/\bnetwork (?:error|timeout)\b/i,/request timed out/i,/\brequest timeout\b/i,/\boverloaded(?:_error)?\b/i,/\brate[_ ]limit(?:_error|ed)?\b/i,/\b(?:HTTP|http_status|status(?:\s*code)?)[:= ]\s*(?:429|5\d\d)\b/i,/\b(?:429|500|502|503|504|529)\s+(?:too many requests|internal server error|bad gateway|service unavailable|gateway time-?out|overloaded)\b/i]),Kn=Object.freeze([/\bAbortError\b/,/\bAPIUserAbortError\b/,/\boperation was aborted\b/i,/\bcanceled by parent abort\b/i,/\bstopped by operator\b/i]),Dt=/provider error \[([a-z_]+)(?:\s+http\s+(\d{3}))?\]/i;function Vn({kind:n,status:e,text:t}){let r=typeof n=="string"&&n.trim()?n.trim():"unclassified",s=Number(e),i=Number.isInteger(s)&&s>=100&&s<=599?` http ${s}`:"",a=(typeof t=="string"?t.trim():"")||"the provider reported a failure but gave no message";return`provider error [${r}${i}]: ${a}`}function ze(n){if(n==null)return"";if(typeof n=="string")return n;if(typeof n!="object")return String(n);let e=n;return[e.message,e.name,e.code,e.providerErrorText,e.cause?.message??(typeof e.cause=="string"?e.cause:void 0),e.cause?.code].filter(r=>typeof r=="string"||typeof r=="number").join(" | ")}function jt(n){if(n&&typeof n=="object"){let t=n.providerErrorKind;if(typeof t=="string"&&t.trim())return t.trim()}let e=Dt.exec(ze(n));return e?e[1].toLowerCase():null}function Ut(n){if(n&&typeof n=="object"){let r=Number(n.providerErrorStatus);if(Number.isInteger(r)&&r>=100&&r<=599)return r}let e=Dt.exec(ze(n)),t=e&&e[2]?Number(e[2]):NaN;return Number.isInteger(t)?t:null}function Je(n){let e=ze(n);if(!e)return"deterministic";for(let s of Kn)if(s.test(e))return"deterministic";let t=jt(n);if(t){let s=Ct[t];if(s==="transient"||s==="deterministic")return s}let r=Ut(n);if(r===429||r>=500&&r<=599)return"transient";for(let s of Bt)if(s.test(e))return"transient";return"deterministic"}function qn(n){return Je(n)==="transient"}var We=2,Lt=5;function Ft(n=process.env){let e=n?.AGENT_TRANSIENT_RETRIES;if(e==null||String(e).trim()==="")return We;let t=Number(e);return!Number.isFinite(t)||t<0?We:Math.min(Lt,Math.floor(t))}var Ie=5e3,Ye=3e4;function Gt(n=process.env){let e=n?.AGENT_TRANSIENT_BACKOFF_MS;if(e==null||String(e).trim()==="")return Ie;let t=Number(e);return!Number.isFinite(t)||t<0?Ie:Math.min(Ye,Math.floor(t))}function He(n,e=Math.random,t=Ie){if(!(t>0))return 0;let r=Math.max(1,Math.floor(Number(n)||1)),s=Math.min(Ye,t*2**(r-1)),i=1+(e()-.5)*.4;return Math.max(1,Math.round(s*i))}function ve(n,{env:e=process.env,rand:t=Math.random}={}){let r=Math.max(0,Math.floor(Number(n)||0)),s=Ft(e),i=Gt(e),o=0,a=0;return{get attemptsMade(){return 1+o+a},get transientUsed(){return a},get transientMax(){return s},next(l){let u=Je(l);return o<r?(o+=1,{retry:!0,paidBy:"declared",delayMs:u==="transient"?He(o,t,i):0,failureClass:u,index:o,of:r}):u==="transient"&&a<s?(a+=1,{retry:!0,paidBy:"transient",delayMs:He(a,t,i),failureClass:u,index:a,of:s}):{retry:!1,delayMs:0,failureClass:u}}}}async function tn(n,e,t,r){if(!e.retry)return!1;if(r())return v.info(`[workflow] node '${n}': run aborted \u2014 not retrying`),!1;let s=t?.message??String(t??"");return e.paidBy==="transient"?v.warn(`[workflow] node '${n}': TRANSIENT provider failure \u2014 ${s}. Retrying in ${Math.round(e.delayMs/1e3)}s (transient retry ${e.index}/${e.of}; the workspace is untouched, so files this node already wrote survive into the retry).`):v.info(`[workflow] node '${n}' failed (${e.failureClass}), retrying (${e.index}/${e.of})\u2026`),e.delayMs>0&&(await new Promise(i=>setTimeout(i,e.delayMs)),r())?(v.info(`[workflow] node '${n}': run aborted during backoff \u2014 not retrying`),!1):!0}V.helpers.inc||V.registerHelper("inc",n=>Number(n)+1);V.helpers.json||V.registerHelper("json",n=>JSON.stringify(n,null,2));V.helpers.eq||V.registerHelper("eq",(n,e)=>n===e);var G=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 ce(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 v.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=m=>t&&typeof t.get=="function"?t.get(m):e?.[m],i=()=>s("_signal")?.aborted===!0;if(typeof this.customExecute=="function"){v.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let m=ve(this.retries),d=null,_=null;for(;;){try{let f=await this.customExecute(e);if(typeof f=="object"&&f!==null&&f.success===!1)_=null,d={success:!1,error:f.error||`node '${this.name}' returned { success: false } with no \`error\` field. On a custom-code node \`success\` is RESERVED: the engine reads it as "this node failed" and stops the graph. If it was meant as a DOMAIN fact (no diff to commit, a PR deliberately skipped), give that fact its own field name and return the outcome \u2014 or set \`error\` to say what actually failed.`,raw:f.raw||null};else return this.isZodSchema?(v.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(f),raw:null}):{success:!0,output:f,raw:null}}catch(f){v.error(`[workflow] node '${this.name}' failed: ${f.message}`),f.name==="ZodError"&&v.error(`Schema errors: ${JSON.stringify(f.issues||f.errors,null,2)}`),_=f,d={success:!1,error:f.message,raw:null}}let b=_??d?.error,A=m.next(b);if(!await tn(this.name,A,b,i))break}return d&&(d.attempts=m.attemptsMade),d}let o;typeof this.prompt=="function"?o=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=V.compile(this.prompt,{noEscape:!0})),o=this._compiledPrompt(r())):o=this.prompt;let a=s("_skillHints");a&&(o=`${a}
|
|
33
33
|
|
|
34
|
-
${i}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=ze(u,G);if(Ct(d)){let p=JSON.parse(Pt(d,"utf-8"));p.currentNode=this.name,He(d,JSON.stringify(p,null,2),"utf-8")}let c=ze(u,"..",G);if(Ct(c))try{let p=JSON.parse(Pt(c,"utf-8"));p.currentNode=this.name,He(c,JSON.stringify(p,null,2),"utf-8")}catch{}}}catch(d){$.debug(`[workflow] could not update session info: ${d.message}`)}let g=null;for(let d=0;d<=this.retries;d++)try{$.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=o().config||{},p=c.agents||{},f=this.config.agent??p[this.name]??null,v={state:o()};f&&(v.preferredAgent=f);let k={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(X(),ue))).invokeAgent);let h=await I(i,v,k),_,b;if(typeof h=="string"?(_=h,b=null):h.structured?(_=h.raw||JSON.stringify(h.structured,null,2),b=h.structured):(_=h.raw||JSON.stringify(h,null,2),b=h.extracted||null),u)try{let m=ze(u,this.name,"raw_stream_output.txt");An(xn(m),{recursive:!0}),He(m,typeof _=="string"?_:JSON.stringify(_),"utf-8")}catch(m){$.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&b){$.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(b,null,2)}`);let m=b;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),b)}catch(y){$.warn(`[workflow] onComplete hook failed: ${y.message}`)}return{success:!0,output:m,raw:_}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:_}),raw:_}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(_);return $.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),O.step("Output parsed"),{success:!0,output:m,raw:_}}return{success:!0,output:_,raw:_}}catch(c){g=c,d<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:g.message,raw:null}}};U();U();import{mkdirSync as Pn,existsSync as Z,statSync as Gt,readdirSync as Ht,rmSync as Cn}from"node:fs";import{spawn as Ft}from"node:child_process";import{join as W}from"node:path";import{pathToFileURL as Rn}from"node:url";import{AsyncLocalStorage as Mn}from"node:async_hooks";import{AsyncLocalStorage as Nn}from"node:async_hooks";var pe=new Nn;function Q(){let n=pe.getStore();return n||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 Rt(n,e){let t=pe.getStore()||Q(),o=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return pe.run(o,e)}function Mt(n,e,t){let o=pe.getStore()||Q(),s=Object.freeze({...o,agent:n??o.agent??null,signal:e??o.signal??null});return pe.run(s,t)}var Je=new Map,Ye=new Map,jt=new Map;function Bt(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Je.set(n,e),Ye.set(n,"ready"),jt.set(n,{...t,cachedAt:Date.now()})}function Dt(n,e){Ye.set(n,"failed"),jt.set(n,{error:e?.message||String(e),failedAt:Date.now()}),Je.delete(n)}function Lt(n){return Ye.get(n)==="ready"?Je.get(n):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function jn(){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"}};function _e(n,e,t,o="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${o})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=o,s&&(i.subgraphTransportError=s),i}function Bn(n,e=process.env,t=process.uptime()){let o=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,r=Number.isFinite(s)&&s>0?s-i:null;if(o===null&&r===null)return null;let a=o===null?r:r===null?o:Math.min(o,r);return Math.max(1,a)}function Dn(n,e){let t=new AbortController,o=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{o=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>o,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var Ut=new Mn,Wt=Promise.resolve();async function Ln(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let o=Ut.getStore()===!0,s=null;if(!o){let r=Wt;Wt=new Promise(a=>{s=a}),await r}let i=new Map;try{for(let[r,a]of t)i.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return $.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${o?" (nested)":""}`),await Ut.run(!0,e)}finally{for(let[r,a]of i)a===void 0?delete process.env[r]:process.env[r]=a;s&&s()}}function Fn(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!o||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:o,authToken:s}}async function Un({apiBase:n,authToken:e,body:t}){let o;try{o=await fetch(`${n}/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 o.json()}catch{}if(!o.ok){if(o.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(o.status===429){let i=s?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=i,r}if(o.status===400&&s?.validationErrors){let i=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=s.validationErrors,i.missing=s.missing,i}throw new P("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function Y({apiBase:n,authToken:e,payload:t}){try{let o=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});o.ok||$.warn(`[in-process subgraph] finalize returned ${o.status} for ${t.childExecutionId}`)}catch(o){$.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function Wn(n,e){let t=W(e,".ready"),o=W(e,"graph.mjs");if(Z(t)&&Z(o))return;Pn(e,{recursive:!0});let s=W(e,".lock"),i=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(s,"wx");a(l),i=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!i){let r=Date.now()+3e4;for(;Date.now()<r;){if(Z(t)&&Z(o))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((l,u)=>{let g=Ft("curl",["-fsSL",n],{stdio:["ignore","pipe","inherit"]}),d=Ft("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});g.stdout.pipe(d.stdin);let c,p,f=()=>{if(c!==void 0&&p!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(p!==0)return u(new Error(`tar exited ${p}`));l()}};g.on("close",v=>{c=v,f()}),d.on("close",v=>{p=v,f()}),g.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(s)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new P("bundle-extract-failed",r.message)}}async function Gn(n){let e=W(n,"graph.mjs");if(!Z(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(Rn(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new P("entry-class-missing","no buildGraph() class export found");return o}async function zt(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=Q(),o;try{o=Fn()}catch(w){throw w}$.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await Un({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:g,bundleReady:d,nodeConfigs:c}=s,p=jn();if(r&&r!==p)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${p} vs ${r}`);if(!d||!a)throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let f=Lt(n);if(!f){let w=W(Se,`${g}@${u||"0"}`);try{await Wn(a,w);try{zn()}catch{}}catch(T){throw T.fallback&&await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:T.message,code:T.reason}}}),T}try{f=await Gn(w),Bt(n,f,{workflowUuid:g,version:u,runtimeTag:r,cacheDir:w})}catch(T){throw Dt(n,T),await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"failed",error:{message:T.message,code:T.reason||"IMPORT_FAILED"}}}),T.fallback?T:new P("import-failed",T.message)}}let v=Date.now(),k=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,I=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...I?{nodeConfigs:c}:{}},_=Bn(e.timeoutMs),b=Dn(e.signal,_),m,y;try{m=await Ln(k,async()=>{let T=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph();return Rt({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>T.run(e.parentAgent,h,{signal:b.signal}))}),y=m&&typeof m=="object"&&"state"in m?m.state:m}catch(w){let T=b.timedOut();throw await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:T?"timeout":"failed",error:T?{message:`aborted at the declared ${Math.round(_/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:w.message,code:w.code||"CHILD_THREW",stack:w.stack},durationMs:Date.now()-v}}),T?_e(n,i,_):w}finally{b.dispose()}if(m&&typeof m=="object"&&m.stoppedExternally){let w=b.timedOut();if(await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:w?"timeout":"canceled",finalState:y,durationMs:Date.now()-v}}),w)throw _e(n,i,_);let T=new Error(`Sub-graph '${n}' canceled by parent abort`);throw T.code="SUBGRAPH_CANCELED",T.subgraphJobId=i,T}return await Y({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:i,status:"completed",finalState:y,durationMs:Date.now()-v}}),{finalState:y,executionId:i}}function Hn(n){let e=0,t=[n];for(;t.length;){let o=t.pop(),s;try{s=Gt(o)}catch{continue}if(s.isDirectory()){let i;try{i=Ht(o)}catch{continue}for(let r of i)t.push(W(o,r))}else e+=s.size}return e}function zn({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Z(Se))return{evicted:0,freedBytes:0};let e=Ht(Se),t=[],o=0;for(let a of e){let l=W(Se,a),u;try{u=Gt(l)}catch{continue}let g=u.isDirectory()?Hn(l):u.size;o+=g,t.push({name:a,full:l,size:g,mtimeMs:u.mtimeMs})}if(o<=n)return{evicted:0,freedBytes:0,totalBytes:o};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,r=0;for(let a of t){if(o-i<=s)break;if(!Z(W(a.full,".lock")))try{Cn(a.full,{recursive:!0,force:!0}),i+=a.size,r+=1}catch(l){$.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&$.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:i,totalBytes:o-i}}catch(e){return $.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Jn=2e3,Yn=600*1e3,Zn=new Set(["completed","failed","canceled","timeout"]);function Kn(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function Vn(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function qn(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function Xn(){return process.env.EXECUTION_ID||null}function Jt(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,o)=>t==null?t:t[o],n):n}async function Ze(n,e={}){if(!n||typeof n!="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 o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=o)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:Yn;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{$.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:b}=await zt(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),m=Jt(b,e.output);return $.info(`[sub-graph] '${n}' completed in-process`),m}catch(b){if(b instanceof P||b?.fallback)$.info(`[sub-graph] in-process fallback for '${n}': ${b.reason||"unknown"} \u2014 using HTTP`);else throw b}let i=Kn(),r=Vn(),a=qn(),l=Xn(),u=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(n)}/trigger`,g={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};$.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let d=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(g)});if(!d.ok){let b=null,m="";try{b=await d.json(),m=b?.error||b?.message||JSON.stringify(b)}catch{m=await d.text().catch(()=>"")}if(d.status===429){let w=b?.quotaInfo||{},T=new Error(`Sub-graph '${n}' blocked by execution quota (${w.used??"?"}/${w.limit??"?"} on plan ${w.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw T.code="SUBGRAPH_QUOTA_EXCEEDED",T.status=429,T.subgraph=n,T.quotaInfo=w,T}if(d.status===400){let w=new Error(`Sub-graph '${n}' rejected input: ${m}`);throw w.code="SUBGRAPH_INVALID_INPUT",w.status=400,w.subgraph=n,w.validationErrors=b?.validationErrors||null,w.missing=b?.missing||null,w}let y=new Error(`Sub-graph '${n}' trigger rejected (${d.status}): ${m}`);throw y.code="SUBGRAPH_TRIGGER_FAILED",y.status=d.status,y.subgraph=n,y}let c=await d.json(),p=c?.data?.jobId||c?.jobId;if(!p)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:n};let f=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Jn,v=`${i}/executions/${encodeURIComponent(p)}`,k=Date.now()+s,I="accepted",h=0,_=null;for(;Date.now()<k;){await new Promise(w=>setTimeout(w,f)),h+=1;let b;try{b=await fetch(v,{headers:{Authorization:`Bearer ${a}`}})}catch(w){_=w?.message||String(w),$.warn(`[sub-graph] status poll for ${p} could not reach the API (${_}), will retry`);continue}if(!b.ok){if(b.status>=500){$.warn(`[sub-graph] status poll for ${p} returned ${b.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${b.status}`)}let m;try{m=await b.json()}catch(w){_=w?.message||String(w),$.warn(`[sub-graph] status poll for ${p} returned an unreadable body (${_}), will retry`);continue}let y=m?.data||m?.execution||m;if(I=y?.status||I,Zn.has(I)){if(I!=="completed"){let te=new Error(`Sub-graph '${n}' (${p}) ended in status '${I}'`);throw te.subgraphJobId=p,te.subgraphStatus=I,te}let w=y?.finalState||y?.state||{},T=Jt(w,e.output);return $.info(`[sub-graph] '${n}' (${p}) completed after ${h} polls`),T}}throw _e(n,p,s,I,_)}import{existsSync as Yt,readFileSync as Qn}from"node:fs";import{join as Ke,dirname as Zt}from"node:path";var fe=class{static async loadContext(e,t,o={}){let s={},i=o.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Zt(Ke(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let g=l.replace(/\.[^.]+$/,"").toLowerCase();s[g]=u}}}let r=o.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ke(t,l);Yt(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,o){let s=[],i=t;for(;i.startsWith(o);){let r=Ke(i,e);if(Yt(r))try{s.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Zt(i);if(a===i)break;i=a}return s.length===0?null:s.every(r=>typeof r=="string")?s.join(`
|
|
34
|
+
${o}`);let l=r(),u=l.cwd||process.cwd(),w=l.sessionPath;try{if(w){let m=rt(w,Y);if(en(m)){let _=JSON.parse(Qt(m,"utf-8"));_.currentNode=this.name,nt(m,JSON.stringify(_,null,2),"utf-8")}let d=rt(w,"..",Y);if(en(d))try{let _=JSON.parse(Qt(d,"utf-8"));_.currentNode=this.name,nt(d,JSON.stringify(_,null,2),"utf-8")}catch{}}}catch(m){v.debug(`[workflow] could not update session info: ${m.message}`)}let p=ve(this.retries),c=null;for(;;)try{v.debug(`[workflow] node '${this.name}' attempt ${p.attemptsMade-1}`);let m=r().config||{},d=m.agents||{},_=this.config.agent??d[this.name]??null,b={state:r()};_&&(b.preferredAgent=_);let A={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:w,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(ne(),he))).invokeAgent);let I=await f(o,b,A),$,y;if(typeof I=="string"?($=I,y=null):I.structured?($=I.raw||JSON.stringify(I.structured,null,2),y=I.structured):($=I.raw||JSON.stringify(I,null,2),y=I.extracted||null),w)try{let g=rt(w,this.name,"raw_stream_output.txt");Xn(Qn(g),{recursive:!0}),nt(g,typeof $=="string"?$:JSON.stringify($),"utf-8")}catch(g){v.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&y){v.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let g=y;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),y)}catch(h){v.warn(`[workflow] onComplete hook failed: ${h.message}`)}return{success:!0,output:g,raw:$}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:$}),raw:$}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse($);return v.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),R.step("Output parsed"),{success:!0,output:g,raw:$}}return{success:!0,output:$,raw:$}}catch(m){c=m;let d=p.next(m);if(!await tn(this.name,d,m,i))break}return{success:!1,error:c.message,raw:null,attempts:p.attemptsMade}}};H();H();import{mkdirSync as or,existsSync as X,statSync as pn,readdirSync as fn,rmSync as sr}from"node:fs";import{spawn as ln}from"node:child_process";import{join as z}from"node:path";import{pathToFileURL as ir}from"node:url";import{AsyncLocalStorage as ar}from"node:async_hooks";import{AsyncLocalStorage as er}from"node:async_hooks";var ge=new er;function re(){let n=ge.getStore();return n||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 nn(n,e){let t=ge.getStore()||re(),r=Object.freeze({executionId:n.executionId,parentExecutionId:n.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(n.executionId!==t.executionId?1:0),conversationId:n.conversationId!==void 0?n.conversationId:t.conversationId??null,dispatchMode:n.dispatchMode??null,agent:n.agent!==void 0?n.agent:t.agent??null,signal:n.signal!==void 0?n.signal:t.signal??null});return ge.run(r,e)}function rn(n,e,t){let r=ge.getStore()||re(),s=Object.freeze({...r,agent:n??r.agent??null,signal:e??r.signal??null});return ge.run(s,t)}var ot=new Map,st=new Map,on=new Map;function sn(n,e,t={}){if(!n||typeof n!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ot.set(n,e),st.set(n,"ready"),on.set(n,{...t,cachedAt:Date.now()})}function an(n,e){st.set(n,"failed"),on.set(n,{error:e?.message||String(e),failedAt:Date.now()}),ot.delete(n)}function cn(n){return st.get(n)==="ready"?ot.get(n):null}function me(n,e,t=process.env){let r=Number(t[n]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):e}function it(n,e){return{signal:AbortSignal.timeout(n),label:`after ${n}ms (${e})`}}function ye(n,e){return it(me(n,e),n)}function U(n){return n?.name==="TimeoutError"||n?.name==="AbortError"}var Ae=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function cr(){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"}};function $e(n,e,t,r="timeout",s=null){let i=new Error(`Sub-graph '${n}' (${e}) timed out after ${Math.round(t/1e3)}s (last status: ${r})`+(s?`; the status API was unreachable on the last attempt (${s})`:""));return i.code="SUBGRAPH_TIMEOUT",i.subgraphJobId=e,i.subgraphStatus=r,s&&(i.subgraphTransportError=s),i}function lr(n,e=process.env,t=process.uptime()){let r=Number.isFinite(n)?Number(n):null,s=Number(e&&e.MAX_WORKFLOW_DURATION_MS),i=Number.isFinite(t)&&t>0?t*1e3:0,o=Number.isFinite(s)&&s>0?s-i:null;if(r===null&&o===null)return null;let a=r===null?o:o===null?r:Math.min(r,o);return Math.max(1,a)}function ur(n,e){let t=new AbortController,r=!1,s=null,i=()=>{t.abort(n?.reason)};return n&&(n.aborted?i():n.addEventListener("abort",i,{once:!0})),e!=null&&!t.signal.aborted&&(s=setTimeout(()=>{r=!0,t.abort(new Error("sub-graph deadline exceeded"))},e),typeof s.unref=="function"&&s.unref()),{signal:t.signal,timedOut:()=>r,dispose(){s&&(clearTimeout(s),s=null),n&&n.removeEventListener("abort",i)}}}var un=new ar,dn=Promise.resolve();async function dr(n,e){let t=n&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).filter(([o,a])=>typeof o=="string"&&o&&typeof a=="string"):[];if(t.length===0)return e();let r=un.getStore()===!0,s=null;if(!r){let o=dn;dn=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 v.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await un.run(!0,e)}finally{for(let[o,a]of i)a===void 0?delete process.env[o]:process.env[o]=a;s&&s()}}function pr(){let n=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=n||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new P("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function fr({apiBase:n,authToken:e,body:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),s;try{s=await fetch(`${n}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal})}catch(o){throw new P(U(o)?"begin-timeout":"network",U(o)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${o.message}`)}let i=null;try{i=await s.json()}catch(o){if(U(o))throw new P("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!s.ok){if(s.status===404){let o=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw o.code="SUBGRAPH_NOT_FOUND",o.status=404,o}if(s.status===429){let o=i?.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(s.status===400&&i?.validationErrors){let o=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.validationErrors=i.validationErrors,o.missing=i.missing,o}throw new P("begin-status",`begin returned ${s.status}`)}return i?.data||i}async function q({apiBase:n,authToken:e,payload:t}){let r=ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let s=await fetch(`${n}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t),signal:r.signal});s.ok||v.warn(`[in-process subgraph] finalize returned ${s.status} for ${t.childExecutionId}`)}catch(s){v.warn(`[in-process subgraph] finalize ${U(s)?`TIMED OUT ${r.label}`:`failed: ${s.message}`}`)}}async function hr(n,e){let t=z(e,".ready"),r=z(e,"graph.mjs");if(X(t)&&X(r))return;or(e,{recursive:!0});let s=z(e,".lock"),i=!1;try{let{openSync:o,closeSync:a}=await import("node:fs"),l=o(s,"wx");a(l),i=!0}catch(o){if(o.code!=="EEXIST")throw o}if(!i){let o=Date.now()+3e4;for(;Date.now()<o;){if(X(t)&&X(r))return;await new Promise(a=>setTimeout(a,100))}throw new P("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let w=Math.ceil(1e4/1e3),p=Math.ceil(me("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),c=ln("curl",["-fsSL","--connect-timeout",String(w),"--max-time",String(p),n],{stdio:["ignore","pipe","inherit"]}),m=ln("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});c.stdout.pipe(m.stdin);let d,_,b=()=>{if(d!==void 0&&_!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(_!==0)return u(new Error(`tar exited ${_}`));l()}};c.on("close",A=>{d=A,b()}),m.on("close",A=>{_=A,b()}),c.on("error",u),m.on("error",u)});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 gr(n){let e=z(n,"graph.mjs");if(!X(e))throw new P("entry-missing",`graph.mjs missing under ${n}`);let t;try{t=await import(ir(e).href)}catch(s){throw new P("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new P("entry-class-missing","no buildGraph() class export found");return r}async function hn(n,e={}){if(!n||typeof n!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=pr()}catch(h){throw h}v.debug(`[in-process subgraph] begin '${n}' parent=${t.executionId||"<root>"}`);let s=await fr({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:n,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:i,runtimeTag:o,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:w,bundleReady:p,nodeConfigs:c}=s,m=cr();if(o&&o!==m)throw await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new P("runtime-mismatch",`${m} vs ${o}`);if(!p||!a)throw await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,discard:!0}}),new P("no-bundle","workflow bundle not built yet");let d=cn(n);if(!d){let h=z(Ae,`${w}@${u||"0"}`);try{await hr(a,h);try{yr()}catch{}}catch(S){throw S.fallback&&await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{d=await gr(h),sn(n,d,{workflowUuid:w,version:u,runtimeTag:o,cacheDir:h})}catch(S){throw an(n,S),await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new P("import-failed",S.message)}}let _=Date.now(),b=s.env&&typeof s.env=="object"&&!Array.isArray(s.env)?s.env:null,A=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,f={...e.input||{},...A?{nodeConfigs:c}:{}},I=lr(e.timeoutMs),$=ur(e.signal,I),y,g;try{y=await dr(b,async()=>{let S=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return nn({executionId:i,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>S.run(e.parentAgent,f,{signal:$.signal}))}),g=y&&typeof y=="object"&&"state"in y?y.state:y}catch(h){let S=$.timedOut();throw await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:S?"timeout":"failed",error:S?{message:`aborted at the declared ${Math.round(I/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-_}}),S?$e(n,i,I):h}finally{$.dispose()}if(y&&typeof y=="object"&&y.stoppedExternally){let h=$.timedOut();if(await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:h?"timeout":"canceled",finalState:g,durationMs:Date.now()-_}}),h)throw $e(n,i,I);let S=new Error(`Sub-graph '${n}' canceled by parent abort`);throw S.code="SUBGRAPH_CANCELED",S.subgraphJobId=i,S}return await q({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:i,status:"completed",finalState:g,durationMs:Date.now()-_}}),{finalState:g,executionId:i}}function mr(n){let e=0,t=[n];for(;t.length;){let r=t.pop(),s;try{s=pn(r)}catch{continue}if(s.isDirectory()){let i;try{i=fn(r)}catch{continue}for(let o of i)t.push(z(r,o))}else e+=s.size}return e}function yr({cap:n=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!X(Ae))return{evicted:0,freedBytes:0};let e=fn(Ae),t=[],r=0;for(let a of e){let l=z(Ae,a),u;try{u=pn(l)}catch{continue}let w=u.isDirectory()?mr(l):u.size;r+=w,t.push({name:a,full:l,size:w,mtimeMs:u.mtimeMs})}if(r<=n)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(n*.7),i=0,o=0;for(let a of t){if(r-i<=s)break;if(!X(z(a.full,".lock")))try{sr(a.full,{recursive:!0,force:!0}),i+=a.size,o+=1}catch(l){v.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return o>0&&v.info(`[sub-graph cache] evicted ${o} entr(y/ies), freed ${(i/1024/1024).toFixed(1)}MB`),{evicted:o,freedBytes:i,totalBytes:r-i}}catch(e){return v.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Sr=2e3,_r=600*1e3,Er=new Set(["completed","failed","canceled","timeout"]);var br=()=>ye("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Tr(n){let e=me("SUBGRAPH_POLL_TIMEOUT_MS",15e3),t=Math.max(1,Math.min(e,n-Date.now()));return it(t,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ir(){let n=process.env.PROGRESS_API_URL;if(!n)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 n.replace(/\/executions\/?$/,"")}function vr(){let n=process.env.PROJECT_ID;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return n}function Ar(){let n=process.env.PROJECT_API_TOKEN;if(!n)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return n}function $r(){return process.env.EXECUTION_ID||null}function gn(n,e){return e==null?n:typeof e=="function"?e(n):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],n):n}async function at(n,e={}){if(!n||typeof n!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re();e.parentAgent==null&&t.agent&&(e.parentAgent=t.agent),e.signal==null&&t.signal&&(e.signal=t.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${n}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let s=Number.isFinite(e.timeoutMs)?e.timeoutMs:_r;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{v.debug(`[sub-graph] trying in-process for '${n}'`);let{finalState:y}=await hn(n,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent,timeoutMs:s}),g=gn(y,e.output);return v.info(`[sub-graph] '${n}' completed in-process`),g}catch(y){if(y instanceof P||y?.fallback)v.info(`[sub-graph] in-process fallback for '${n}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Ir(),o=vr(),a=Ar(),l=$r(),u=`${i}/projects/${encodeURIComponent(o)}/workflows/${encodeURIComponent(n)}/trigger`,w={input:e.input||{},...l?{parentExecutionId:l}:{},...e.conversationId?{conversationId:e.conversationId}:{}};v.info(`[sub-graph] dispatching '${n}' (${e.async?"async":"sync"}) from parent ${l||"<none>"}`);let p=br(),c;try{c=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(w),signal:p.signal})}catch(y){if(!U(y))throw y;let g=new Error(`Sub-graph '${n}' trigger TIMED OUT ${p.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=y,g}if(!c.ok){let y=null,g="";try{y=await c.json(),g=y?.error||y?.message||JSON.stringify(y)}catch{g=await c.text().catch(()=>"")}if(c.status===429){let S=y?.quotaInfo||{},N=new Error(`Sub-graph '${n}' blocked by execution quota (${S.used??"?"}/${S.limit??"?"} on plan ${S.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw N.code="SUBGRAPH_QUOTA_EXCEEDED",N.status=429,N.subgraph=n,N.quotaInfo=S,N}if(c.status===400){let S=new Error(`Sub-graph '${n}' rejected input: ${g}`);throw S.code="SUBGRAPH_INVALID_INPUT",S.status=400,S.subgraph=n,S.validationErrors=y?.validationErrors||null,S.missing=y?.missing||null,S}let h=new Error(`Sub-graph '${n}' trigger rejected (${c.status}): ${g}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=c.status,h.subgraph=n,h}let m;try{m=await c.json()}catch(y){if(!U(y))throw y;let g=new Error(`Sub-graph '${n}' trigger body read TIMED OUT ${p.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw g.code="SUBGRAPH_TRIGGER_TIMEOUT",g.subgraph=n,g.timedOut=!0,g.cause=y,g}let d=m?.data?.jobId||m?.jobId;if(!d)throw new Error(`Sub-graph '${n}' trigger returned no jobId: ${JSON.stringify(m).slice(0,200)}`);if(e.async)return v.info(`[sub-graph] async dispatch of '${n}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:n};let _=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Sr,b=`${i}/executions/${encodeURIComponent(d)}`,A=Date.now()+s,f="accepted",I=0,$=null;for(;Date.now()<A;){await new Promise(N=>setTimeout(N,_)),I+=1;let y=Tr(A),g;try{g=await fetch(b,{headers:{Authorization:`Bearer ${a}`},signal:y.signal})}catch(N){$=U(N)?`poll TIMED OUT ${y.label}`:N?.message||String(N),v.warn(`[sub-graph] status poll for ${d} could not reach the API (${$}), will retry`);continue}if(!g.ok){if(g.status>=500){v.warn(`[sub-graph] status poll for ${d} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${g.status}`)}let h;try{h=await g.json()}catch(N){$=U(N)?`poll body read TIMED OUT ${y.label}`:N?.message||String(N),v.warn(`[sub-graph] status poll for ${d} returned an unreadable body (${$}), will retry`);continue}let S=h?.data||h?.execution||h;if(f=S?.status||f,Er.has(f)){if(f!=="completed"){let J=new Error(`Sub-graph '${n}' (${d}) ended in status '${f}'`);throw J.subgraphJobId=d,J.subgraphStatus=f,J}let N=S?.finalState||S?.state||{},W=gn(N,e.output);return v.info(`[sub-graph] '${n}' (${d}) completed after ${I} polls`),W}}throw $e(n,d,s,f,$)}import{existsSync as mn,readFileSync as kr}from"node:fs";import{join as ct,dirname as yn}from"node:path";var we=class{static async loadContext(e,t,r={}){let s={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=yn(ct(t,e));for(let l of i){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let w=l.replace(/\.[^.]+$/,"").toLowerCase();s[w]=u}}}let o=r.discovery||{};for(let[a,l]of Object.entries(o))try{let u=ct(t,l);mn(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],i=t;for(;i.startsWith(r);){let o=ct(i,e);if(mn(o))try{s.unshift(await this.loadFile(o))}catch(l){console.warn(`[workflow] could not load ${e} from ${o}: ${l.message}`)}let a=yn(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
|
-
`):s.every(
|
|
38
|
+
`):s.every(o=>typeof o=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=kr(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(e).href);return s.default||s}return t}};import{mkdirSync as _n,existsSync as lt,writeFileSync as wn,unlinkSync as Nr}from"node:fs";import{join as Q,resolve as En}from"node:path";import{config as Or}from"dotenv";import{zodToJsonSchema as Sn}from"zod-to-json-schema";import{z as Ne}from"zod";import xr from"handlebars";function Rr({traceFrom:n,sessionId:e,sessionPath:t,idSource:r,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=${n} pid=${process.pid} ppid=${o} sessionId=${e} source=${r} mkdir=${s?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let w=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${n}):
|
|
41
|
-
${g}`)}}function Qt(){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 en(){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 Xt(String(e).trim())}catch{return String(e).trim()}}function tn(){Qt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function nn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function on(n={}){let e=Me.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),o=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${o}`:o}function rn({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:o="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Xt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,r="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,r="config.sessionId"):(a=on(e),r="generated")}i=i??Date.now();let g=e.paths?.output||ce;s=K(n,g,Ce,a)}let l=!Ve(s);return l&&qt(s,{recursive:!0}),(l||r!=="initialState.sessionPath")&&oo({traceFrom:o,sessionId:a,sessionPath:s,idSource:r,mkdirFresh:l}),nn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var ee=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,o={}){if(!(t instanceof F)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let g=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(g):r.input&&typeof r.input=="object"?d=r.input:d={},Ze(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(g):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:g?._signal,parentAgent:u?.agent})}},l=new F(a);return l.name=e,this.nodes.set(e,l),o.prompt&&this.nodePrompts.set(e,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}let s=!(t instanceof F)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof F?t:new F(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),o.prompt?this.nodePrompts.set(e,o.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(o).length>0&&this.nodeOptions.set(e,o),this}addEdge(e,t){let o=this.edges.get(e);return o===void 0?this.edges.set(e,t):typeof o=="string"?o!==t&&this.edges.set(e,[o,t]):Array.isArray(o)?o.includes(t)||o.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:o}={}){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:o}),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,o=i=>{t.set(i,1);for(let r of this._simpleTargets(i)){if(!r||r==="END")continue;let a=t.get(r)||0;a===1?e.add(`${i}->${r}`):a===0&&o(r)}t.set(i,2)};this.entryPoint&&o(this.entryPoint);let s=new Map;for(let[i]of this.edges)for(let r of this._simpleTargets(i))!r||r==="END"||e.has(`${i}->${r}`)||s.set(r,(s.get(r)||0)+1);return{backEdges:e,joinDegree:s}}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,o,s,i){let r=o;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,s,i)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let p=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let v=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;v&&(f.description=v);let k=this.nodePrompts.get(d);if(k)f.prompt=k;else if(typeof c.prompt=="function")try{let y=c.prompt({});typeof y=="string"&&y.trim()&&(f.prompt=y,f.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString());let I=c?.config?.dispatchesWorkflow;if(typeof I=="string"&&I.trim())f.dispatchesWorkflow=I.trim();else if(Array.isArray(I)){let y=[...new Set(I.filter(w=>typeof w=="string").map(w=>w.trim()).filter(Boolean))];y.length&&(f.dispatchesWorkflow=y)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(f.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let y=null;if(typeof be?.toJSONSchema=="function")try{y=be.toJSONSchema(c.outputSchema)}catch{}if(!y)try{y=Vt(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=y?{jsonSchema:y,variables:this._flattenJsonSchemaToVariables(y)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let h=(this.resolvedToolsMap||{})[d];h?.toolIds&&(f.tools=h.toolIds);let _=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;_&&_.length>0&&(f.skills=[..._]);let b=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;b&&b.length>0&&(f.plugins=b.map(y=>y&&typeof y=="object"?{...y}:y));let m=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;m&&m.length>0&&(f.stores=m.map(y=>y&&typeof y=="object"?{...y}:y)),Object.keys(f).length>0&&(t[d]=f)}let o=[];for(let[d,c]of this.edges)if(typeof c=="string")o.push({source:d,target:c});else if(Array.isArray(c))for(let p of c)o.push({source:d,target:p});else if(c.conditional){let p=this.conditionalCodeMap.get(d)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),v=c.labels||{},k=this.nodes.get(d),I=k?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!k,h=d;if(!I){let _=`${d}__branch`;e.push({id:_,type:"decision",data:{nodeType:"decision",label:_}}),o.push({source:d,target:_}),h=_}for(let _ of f){let b={source:h,target:_,data:{conditionalCode:p}};v[_]&&(b.label=v[_]),o.push(b)}}let s=d=>{if(!d)return null;if(typeof be?.toJSONSchema=="function")try{return be.toJSONSchema(d)}catch{}try{return Vt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let i=0;for(let d of o)if(d.target==="END"){i+=1;let c=`END__${i}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:d,target:c})}let r=this._topoOrderNodes(e,o),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),g=s(this.contextSchema);return{nodes:r,edges:o,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:g}}_topoOrderNodes(e,t){let o=new Map(e.map((d,c)=>[d.id,c])),s=new Map(e.map(d=>[d.id,d])),i=new Map(e.map(d=>[d.id,0])),r=new Map(e.map(d=>[d.id,[]]));for(let d of t)r.has(d.source)&&i.has(d.target)&&(r.get(d.source).push(d.target),i.set(d.target,i.get(d.target)+1));let a=new Set,l=new Set(o.keys()),u=[...l].filter(d=>i.get(d)===0),g=[];for(;g.length<e.length;){let d;if(u.length>0){if(u.sort((c,p)=>o.get(c)-o.get(p)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,p)=>o.get(c)-o.get(p))[0];a.add(d),l.delete(d),g.push(s.get(d));for(let c of r.get(d)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return g}_inferConditionalTargets(e,t){let o=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=i.exec(o))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,g;for(;(g=u.exec(o))!==null;)l.add(g[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let o=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");o=e.definitions[s]||e}return this._flattenSchema(o,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let o=[],s=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(s)){let l=t?`${t}.${r}`:r;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let o=[];t.success!==void 0&&o.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)o.push(`${s}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${s}: ${r} items`)}if(o.length>=4)break}return o}async run(e,t={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(E){let S=new Error(`agent.normalizeInput() rejected the trigger input: ${E?.message||E}`);throw S.cause=E,S.code=E?.code||"NORMALIZE_INPUT_FAILED",S}let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=o.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();to({path:K(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let E=K(r,".zibby.config.js");Ve(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let E=a?.agent;E?.provider?l=E.provider:E?.gemini?l="gemini":E?.claude?l="claude":E?.cursor?l="cursor":E?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},g=this._runtimeSchema();if(g){let E=g.safeParse(t);if(!E.success){let S=E.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),S.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${S.join(", ")}`)}O.step("State validated against schema")}let d=en(),c=t.sessionPath||d;c||tn();let{sessionPath:p,sessionTimestamp:f,sessionId:v}=rn({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${v}`);let k=await fe.loadContext(t.specPath||"",r,u);Object.keys(k).length>0&&O.step(`Context loaded: ${Object.keys(k).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 h=new re({...t,config:a,agentType:l,outputPath:I,sessionPath:p,sessionTimestamp:f,context:k,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),_=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:b}=await Promise.resolve().then(()=>(de(),At)),m=a.skills&&typeof a.skills=="object"?a.skills:{},y=Object.values(m).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),w=E=>{for(let S of y)if(S.id===E)return S;return b(E)},T=new Set;for(let[,E]of this.nodes)for(let S of E.config?.skills||[])T.add(S);for(let E of T){let S=w(E);if(typeof S?.middleware=="function")try{let R=await S.middleware();typeof R=="function"&&_.set(E,R)}catch{}}let{backEdges:te,joinDegree:ln}=this._analyzeFlow(),$e=new Map,ne=[],Te=(E,S,R)=>{if(!E||E==="END")return;let D=ln.get(E)||0;if(R&&D>1&&!te.has(`${S}->${E}`)){let oe=($e.get(E)||0)+1;if(oe<D){$e.set(E,oe);return}$e.set(E,0)}ne.includes(E)||ne.push(E)};this.entryPoint&&ne.push(this.entryPoint);let ge=[],ot=a?.recursionLimit??100,dn=0;try{for(;ne.length>0;){let S=ne.pop();if(!S||S==="END")continue;if(++dn>ot)throw new Error(`Workflow exceeded recursion limit (${ot}) \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 R=K(p,Re);if(Ve(R)){try{eo(R)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
43
|
-
${
|
|
41
|
+
${w}`)}}function bn(){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 En(String(e).trim())}catch{return String(e).trim()}}function In(){bn()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function vn({sessionPath:n,sessionId:e}){n&&typeof n=="string"&&(process.env.ZIBBY_SESSION_PATH=n),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function An(n={}){let e=Ge.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=n.paths?.sessionPrefix;return s?`${s}_${r}`:r}function $n({cwd:n=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,i=t.sessionTimestamp,o="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=En(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,o="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,o="ZIBBY_SESSION_ID";else{let p=e.sessionId!=null?String(e.sessionId).trim():"";p&&p!=="last"?(a=p,o="config.sessionId"):(a=An(e),o="generated")}i=i??Date.now();let w=e.paths?.output||de;s=Q(n,w,Le,a)}let l=!lt(s);return l&&_n(s,{recursive:!0}),(l||o!=="initialState.sessionPath")&&Rr({traceFrom:r,sessionId:a,sessionPath:s,idSource:o,mkdirFresh:l}),vn({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var oe=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,r={}){if(!(t instanceof G)&&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 u=>{let w=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,p;return typeof o.input=="function"?p=o.input(w):o.input&&typeof o.input=="object"?p=o.input:p={},at(o.workflow,{input:p,async:o.async===!0,conversationId:typeof o.conversationId=="function"?o.conversationId(w):o.conversationId,output:o.output,timeoutMs:o.timeoutMs,pollIntervalMs:o.pollIntervalMs,signal:w?._signal,parentAgent:u?.agent})}},l=new G(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=!(t instanceof G)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,i=t instanceof G?t:new G(s?{...t,_isRouter:!0}:t);return i.name=e,this.nodes.set(e,i),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){let r=this.edges.get(e);return r===void 0?this.edges.set(e,t):typeof r=="string"?r!==t&&this.edges.set(e,[r,t]):Array.isArray(r)?r.includes(t)||r.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:r}={}){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:r}),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,r=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&&r(o)}t.set(i,2)};this.entryPoint&&r(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,r,s,i){let o=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=o;o=()=>l(t,u,s,i)}return o()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let m=this.nodeTypeMap.get(p)||(c?.config?._isRouter===!0?"decision":p);e.push({id:p,type:m,data:{nodeType:m,label:p}});let d={};c._isCustomCode&&typeof c.execute=="function"&&(d.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(d.description=_);let b=this.nodePrompts.get(p);if(b)d.prompt=b;else if(typeof c.prompt=="function")try{let h=c.prompt({});typeof h=="string"&&h.trim()&&(d.prompt=h,d.promptIsCode=!0)}catch{}typeof c.customExecute=="function"&&(d.executeCode=c.customExecute.toString());let A=c?.config?.dispatchesWorkflow;if(typeof A=="string"&&A.trim())d.dispatchesWorkflow=A.trim();else if(Array.isArray(A)){let h=[...new Set(A.filter(S=>typeof S=="string").map(S=>S.trim()).filter(Boolean))];h.length&&(d.dispatchesWorkflow=h)}if(typeof c?.config?.agent=="string"&&c.config.agent.trim()&&(d.agent=c.config.agent.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let h=null;if(typeof Ne?.toJSONSchema=="function")try{h=Ne.toJSONSchema(c.outputSchema)}catch{}if(!h)try{h=Sn(c.outputSchema,{target:"openApi3"})}catch{}d.outputSchema=h?{jsonSchema:h,variables:this._flattenJsonSchemaToVariables(h)}:{schema:c.outputSchema}}else d.outputSchema={schema:c.outputSchema};let f=(this.resolvedToolsMap||{})[p];f?.toolIds&&(d.tools=f.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(d.skills=[...I]);let $=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;$&&$.length>0&&(d.plugins=$.map(h=>h&&typeof h=="object"?{...h}:h));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(d.stores=y.map(h=>h&&typeof h=="object"?{...h}:h));let g=Array.isArray(c?.config?.uses)?c.config.uses:typeof c?.config?.uses=="string"?[c.config.uses]:Array.isArray(c?.uses)?c.uses:typeof c?.uses=="string"?[c.uses]:null;if(g&&g.length>0){let h=new Set,S=[];for(let N of g){let W=typeof N=="string"?N.trim():"";!W||h.has(W)||(h.add(W),S.push(W))}S.length>0&&(d.uses=S)}Object.keys(d).length>0&&(t[p]=d)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(Array.isArray(c))for(let m of c)r.push({source:p,target:m});else if(c.conditional){let m=this.conditionalCodeMap.get(p)||c.routes.toString(),d=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},b=this.nodes.get(p),A=b?.config?._isRouter===!0||this.nodeTypeMap.get(p)==="decision"||!b,f=p;if(!A){let I=`${p}__branch`;e.push({id:I,type:"decision",data:{nodeType:"decision",label:I}}),r.push({source:p,target:I}),f=I}for(let I of d){let $={source:f,target:I,data:{conditionalCode:m}};_[I]&&($.label=_[I]),r.push($)}}let s=p=>{if(!p)return null;if(typeof Ne?.toJSONSchema=="function")try{return Ne.toJSONSchema(p)}catch{}try{return Sn(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let p of r)if(p.target==="END"){i+=1;let c=`END__${i}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){i+=1;let c=`END__${i}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let o=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=s(a||this.stateSchema),u=s(this.inputSchema),w=s(this.contextSchema);return{nodes:o,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:w}}_topoOrderNodes(e,t){let r=new Map(e.map((p,c)=>[p.id,c])),s=new Map(e.map(p=>[p.id,p])),i=new Map(e.map(p=>[p.id,0])),o=new Map(e.map(p=>[p.id,[]]));for(let p of t)o.has(p.source)&&i.has(p.target)&&(o.get(p.source).push(p.target),i.set(p.target,i.get(p.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(p=>i.get(p)===0),w=[];for(;w.length<e.length;){let p;if(u.length>0){if(u.sort((c,m)=>r.get(c)-r.get(m)),p=u.shift(),a.has(p))continue}else p=[...l].sort((c,m)=>r.get(c)-r.get(m))[0];a.add(p),l.delete(p),w.push(s.get(p));for(let c of o.get(p)||[])i.set(c,i.get(c)-1),i.get(c)<=0&&!a.has(c)&&u.push(c)}return w}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,o;for(;(o=i.exec(r))!==null;){let u=o[2]!==void 0?o[2]:o[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,w;for(;(w=u.exec(r))!==null;)l.add(w[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},i=e.required||[];for(let[o,a]of Object.entries(s)){let l=t?`${t}.${o}`:o;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(o),optional:!i.includes(o)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.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)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let o=i.length,a=i.filter(u=>u?.passed===!0).length,l=i.some(u=>u?.passed!==void 0);r.push(l?`${s}: ${a}/${o} passed${o-a?`, ${o-a} failed`:""}`:`${s}: ${o} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");if(e&&typeof e.normalizeInput=="function"&&t&&typeof t=="object"&&!Array.isArray(t))try{t=e.normalizeInput(t)??t}catch(T){let E=new Error(`agent.normalizeInput() rejected the trigger input: ${T?.message||T}`);throw E.cause=T,E.code=T?.code||"NORMALIZE_INPUT_FAILED",E}let s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,o=t.cwd||process.cwd();Or({path:Q(o,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=Q(o,".zibby.config.js");lt(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},w=this._runtimeSchema();if(w){let T=w.safeParse(t);if(!T.success){let E=T.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),E.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${E.join(", ")}`)}R.step("State validated against schema")}let p=Tn(),c=t.sessionPath||p;c||In();let{sessionPath:m,sessionTimestamp:d,sessionId:_}=$n({cwd:o,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});R.step(`Session ${_}`);let b=await we.loadContext(t.specPath||"",o,u);Object.keys(b).length>0&&R.step(`Context loaded: ${Object.keys(b).join(", ")}`);let A=t.outputPath;!A&&t.specPath&&(e?.calculateOutputPath?A=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ae({...t,config:a,agentType:l,outputPath:A,sessionPath:m,sessionTimestamp:d,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),I=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:$}=await Promise.resolve().then(()=>(fe(),Kt)),y=a.skills&&typeof a.skills=="object"?a.skills:{},g=Object.values(y).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),h=T=>{for(let E of g)if(E.id===T)return E;return $(T)},S=new Set;for(let[,T]of this.nodes)for(let E of T.config?.skills||[])S.add(E);for(let T of S){let E=h(T);if(typeof E?.middleware=="function")try{let C=await E.middleware();typeof C=="function"&&I.set(T,C)}catch{}}let{backEdges:N,joinDegree:W}=this._analyzeFlow(),J=new Map,se=[],Pe=(T,E,C)=>{if(!T||T==="END")return;let L=W.get(T)||0;if(C&&L>1&&!N.has(`${E}->${T}`)){let ie=(J.get(T)||0)+1;if(ie<L){J.set(T,ie);return}J.set(T,0)}se.includes(T)||se.push(T)};this.entryPoint&&se.push(this.entryPoint);let _e=[],mt=a?.recursionLimit??100,xn=0;try{for(;se.length>0;){let E=se.pop();if(!E||E==="END")continue;if(++xn>mt)throw new Error(`Workflow exceeded recursion limit (${mt}) \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 C=Q(m,Fe);if(lt(C)){try{Nr(C)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:_e,stoppedExternally:!0};let L=this.nodes.get(E);if(!L)throw new Error(`Node '${E}' not found in graph`);let ie=JSON.stringify({sessionPath:m,sessionTimestamp:d,currentNode:E,createdAt:new Date().toISOString(),config:f.get("config")}),Rn=Q(m,Y);wn(Rn,ie,"utf-8");let yt=f.get("config")?.paths?.output||de,Pn=Q(o,yt,Y);_n(Q(o,yt),{recursive:!0});try{wn(Pn,ie,"utf-8")}catch{}let wt=t.onPipelineProgress;if(typeof wt=="function")try{wt({cwd:o,sessionPath:m,sessionId:_,outputBase:f.get("config")?.paths?.output||de,currentNode:E})}catch{}let Mn=(this.resolvedToolsMap||{})[E]||null;f.set("_currentNodeTools",Mn);let Cn=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Cn[E]||{}),R.nodeStart(E);let St=Date.now(),Ee=this.nodePrompts.get(E);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(ne(),he));this._invokeAgent=O.invokeAgent}let Bn=this._invokeAgent,Me={},Dn=L.config?.skills||[];for(let O of Dn){let M=h(O);if(typeof M?.invokeAgentOptions=="function")try{let k=M.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:E});k&&typeof k=="object"&&(Me={...Me,...k})}catch(k){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${k.message}`)}}let _t=async(O,M,k={})=>{let B=Bn(O,M,{...Me,...k,signal:s.signal});return B.catch(()=>{}),s.signal.aborted?B:Promise.race([B,new Promise((ee,F)=>{let D=()=>{setTimeout(()=>{let Tt=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);Tt.name="AbortError",F(Tt)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},jn=async(O={},M={})=>{let k=M.prompt||"";if(Ee){let B=this._compiledPrompts.get(E);B||(B=xr.compile(Ee,{noEscape:!0}),this._compiledPrompts.set(E,B));try{k=B(O)}catch(ee){throw console.error(`\u274C Template rendering failed for node '${E}':`,ee.message),new Error(`Template rendering failed: ${ee.message}`,{cause:ee})}}else if(!k)throw new Error(`No prompt template configured for node '${E}' and no prompt provided in options`);return _t(k,{state:f.getAll(),images:M.images||[]},{model:M.model||f.get("model"),workspace:f.get("workspace"),schema:M.schema,...M,signal:s.signal,nodeName:E})},Et=f.getAll(),Un=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let O of Un)Object.prototype.hasOwnProperty.call(Et,O)&&console.warn(`[workflow] node "${E}": state key "${O}" is shadowed by the engine context prop; read it via context.state.get('${O}')`);let bt={...Et,state:f,invokeAgent:jn,_coreInvokeAgent:_t,agent:e,nodeId:E,promptTemplate:Ee,getPromptTemplate:()=>Ee};try{let O=(L.config?.skills||[]).map(D=>I.get(D)).filter(Boolean),M=[...this.middleware,...O],k;k=await rn(e,s.signal,async()=>M.length>0?this._composeMiddleware(M,E,async()=>L.execute(bt,f),f.getAll(),f):L.execute(bt,f));let B=Date.now()-St;if(_e.push({node:E,success:k.success,duration:B,timestamp:new Date().toISOString()}),!k.success){if(s.signal.aborted)return R.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:_e,stoppedExternally:!0};f.append("errors",{node:E,error:k.error});let D=Number.isInteger(k.attempts)&&k.attempts>0?k.attempts:(L.config?.retries||0)+1;throw R.nodeFailed(E,k.error,{duration:B}),new Error(`Node '${E}' failed after ${D} attempt(s): ${k.error}`)}f.update({[E]:k.output});let ee=this._summarizeNodeOutput(E,k.output);R.nodeComplete(E,{duration:B,details:ee});let F=this.edges.get(E);if(F)if(F.conditional){let D=F.routes(f.getAll());R.route(E,D),Pe(D,E,!1)}else if(Array.isArray(F))for(let D=F.length-1;D>=0;D--)Pe(F[D],E,!0);else Pe(F,E,!0)}catch(O){throw R.isInsideNode&&R.nodeFailed(E,O.message,{duration:Date.now()-St}),f.set("failed",!0),f.set("failedAt",E),O}}R.graphComplete();let T={success:!0,state:f.getAll(),executionLog:_e};return e&&typeof e.onComplete=="function"&&await e.onComplete(T),T}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(T){console.warn(`[workflow] agent.cleanup() failed: ${T.message}`)}}}};var ut=Symbol.for("@zibby/agent-workflow.nodes");globalThis[ut]||(globalThis[ut]=new Map);var Se=globalThis[ut];function kn(n,e){Se.set(n,e)}function dt(n){return Se.get(n)}function Oe(n){return Se.has(n)}function Pr(){return Array.from(Se.keys())}function pt(n){let e=Se.get(n);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}kn("ai_agent",{name:"ai_agent",factory:!0,create:(n,e={})=>({name:n,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(ne(),he))).invokeAgent);let s=e.extraPromptInstructions||"Execute the task based on the current state.",i=Mr(s,t),o=await r(i,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:o,nodeId:n},raw:typeof o=="string"?o:o.raw}}})});function Mr(n,e){let t=/@([\w.]+)/g,r=new Set,s;for(;(s=t.exec(n))!==null;)r.add(s[1]);if(r.size===0)return n;let i=[],o=new Set;for(let a of r){let l=a.split(".")[0];if(o.has(l))continue;let u=a.split(".").reduce((c,m)=>c?.[m],e);if(u===void 0)continue;let w=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),p=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());i.push(`## ${p}
|
|
43
|
+
${w}`),a.includes(".")||o.add(l)}return i.length===0?n:`${n}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
48
|
${i.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}
|
|
51
|
-
`)}function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`).map((
|
|
58
|
-
`);
|
|
59
|
-
`)}function
|
|
50
|
+
`)}`}fe();H();var xe={};function ht(n,e){if(Array.isArray(e))return ft(e);let t=xe[n];return!t||t.length===0?null:ft(t)}function ft(n){if(!Array.isArray(n)||n.length===0)return null;let e=[],t={},r=[];for(let s of n){let i=te(s);if(!i){v.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let o of i.tools||[])e.push({name:o.name,description:o.description,input_schema:o.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let o=i.resolve();o&&(t[i.serverName]={...o,toolPrefix:s})}else{let o={};for(let a of i.envKeys||[]){let l=process.env[a];l&&(o[a]=l)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:o,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}H();function Cr(n,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=n;if(!Array.isArray(t)||t.length===0)throw new j("Graph must have at least one node");if(!Array.isArray(r))throw new j("Graph edges must be an array");let i=new oe(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let o=new Set,a=new Map,l={};for(let c of t){let m=Re(c);a.set(c.id,{...c,resolvedType:m}),m==="decision"&&o.add(c.id)}for(let[c,m]of a){if(o.has(c))continue;let d=m.resolvedType,_=s[c]||{},b=ht(d,_.tools);b&&(l[c]=b);let A={};_.prompt&&(A.prompt=_.prompt);let f=Oe(d);if(v.debug(`[workflow] compiler: node "${c}" type="${d}" registered=${f}`),_.customCode&&!f)i.addNode(c,Nn(c,_.customCode,_),A),i.setNodeType(c,d);else if(f){let I=dt(d);I.factory?i.addNode(c,I.create(c,{..._,resolvedTools:b}),A):i.addNode(c,I,A),i.setNodeType(c,d)}else if(_.executeCode)i.addNode(c,Nn(c,_.executeCode,_),A),i.setNodeType(c,d);else throw new j(`Unknown node type "${d}" for node "${c}". Did you forget to register it?`)}i.resolvedToolsMap=l;let u=new Set;for(let c of r)o.has(c.target)||u.add(c.target);let w=t.find(c=>!o.has(c.id)&&!u.has(c.id));if(!w)throw new j("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(w.id);let p=jr(r,"source");for(let c of r)if(!o.has(c.source))if(o.has(c.target)){let m=c.target,d=p.get(m)||[];if(d.length===0)throw new j(`Decision node "${m}" has no outgoing edges`);let _=Ur(m,d,o);i.addConditionalEdges(c.source,_)}else i.addEdge(c.source,c.target);return i}function Br(n){let e=[];if(!n||typeof n!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(n.nodes)||n.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(n.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=n.nodeConfigs||{};for(let a of n.nodes){let l=Re(a);if(l==="decision"||Oe(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(n.nodes.map(a=>a.id));for(let a of n.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let s=new Set(n.nodes.filter(a=>Re(a)==="decision").map(a=>a.id)),i=new Set;for(let a of n.edges)s.has(a.target)||i.add(a.target);let o=n.nodes.filter(a=>!s.has(a.id)&&!i.has(a.id));o.length===0?e.push("No entry point found (every node has incoming edges)"):o.length>1&&e.push(`Multiple entry points found: ${o.map(a=>a.id).join(", ")}`);for(let a of s){let l=n.edges.filter(w=>w.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(w=>w.data?.conditionalCode||w.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Dr(n){return!n||!Array.isArray(n.nodes)?[]:n.nodes.filter(e=>Re(e)!=="decision").map(e=>e.id)}function Re(n){let e=n.data?.nodeType||n.data?.type||n.type;return e==="workflowNode"||e==="custom"||e==="default"?n.id:e}function jr(n,e){let t=new Map;for(let r of n){let s=r[e];t.has(s)||t.set(s,[]),t.get(s).push(r)}return t}function Ur(n,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new j(`Decision node "${n}" has no conditionalCode on its outgoing edges`);let s=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),o;try{let l=new Function(`return (${s})`)();o=u=>{let w=l(u);return i.has(w)||v.warn(`[workflow] conditional route from "${n}" returned "${w}" which is not in valid targets: ${[...i].join(", ")}`),w}}catch(a){throw new j(`Failed to compile conditionalCode for "${n}": ${a.message}`)}return o}function Nn(n,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(o){throw new j(`Failed to compile customCode for node "${n}": ${o.message}`)}let s=r(async(...o)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(ne(),he));return a(...o)},typeof Ce<"u"?Ce:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:n,_isCustomCode:!0,outputSchema:i,execute:async o=>{try{let a=await s(o);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var j=class extends Error{constructor(e){super(e),this.name="CompilationError"}};fe();var gt=/^[a-z][a-z0-9_]{0,40}$/;function Lr(n){if(n==null)return[];if(!Array.isArray(n))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return n.forEach((r,s)=>{if(r==null||typeof r!="object"||Array.isArray(r)){e.push(`stores[${s}] must be an object { name, description }`);return}let{name:i}=r;if(typeof i!="string"||i.length===0){e.push(`stores[${s}] is missing a string "name"`);return}gt.test(i)||e.push(`stores[${s}] name "${i}" is invalid \u2014 must match ${gt} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(i)?e.push(`stores[${s}] duplicate store name "${i}" (also at index ${t.get(i)}) \u2014 store names must be unique within a workflow`):t.set(i,s)}),e}Ke();ne();function Fr(n,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=n,i=new Set,o=[],a=new Map;for(let b of t){let A=b.data?.nodeType||b.type;a.set(b.id,A),A==="decision"?i.add(b.id):o.push({id:b.id,nodeType:A,label:b.data?.label||b.id})}let l=o.some(b=>{let A=s[b.id]||{};return!A.customCode&&!A.executeCode}),{toolsPerNode:u,toolIdsByVar:w}=Kr(o,s),{simpleEdges:p,conditionalEdges:c}=Vr(r,i),m=qr(o,r,i),d=[],_=e.workflowType||"workflow";return d.push(Wr(e)),d.push(Hr(_,{usesRegisteredNodes:l})),d.push(zr(w)),d.push(Jr(_)),d.push(Yr(o,s)),d.push(Zr(o,m,p,c,u,_)),d.filter(Boolean).join(`
|
|
51
|
+
`)}function Gr(n){let e={};for(let[t,r]of Object.entries(n)){let{tools:s,...i}=r;Object.keys(i).length>0&&(e[t]=i)}return e}function Wr(n){let e=n.workflowType||"workflow";return["// Generated workflow",`// ${n.projectId?`Project: ${n.projectId} | `:""}Type: ${e} | Version: ${n.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
|
+
`)}function Hr(n,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
53
|
+
`)}function zr(n){if(n.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,r]of n)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return e.push(""),e.join(`
|
|
54
|
+
`)}function Jr(n){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${n}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
55
|
+
`)}function Yr(n,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let r of n){let s=On(r.id),i=e[r.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),t.push(`const ${s}_execute = ${i};`);else{let o=pt(r.nodeType);o?(t.push(`// Default "${r.nodeType}" implementation`),t.push(`const ${s}_execute = ${o};`)):(t.push(`// No template for "${r.nodeType}" \u2014 passthrough`),t.push(`const ${s}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
56
|
+
`)}function Zr(n,e,t,r,s,i){let o=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];o.push("export function buildGraph(options = {}) {"),o.push(" const graph = new WorkflowGraph(options);",""),o.push(" // Nodes");for(let l of n){let u=On(l.id);o.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),o.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}o.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||r.length>0)&&o.push(" // Edges");for(let l of t)o.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of r){let u=l.code.split(`
|
|
57
|
+
`).map((w,p)=>p===0?w:` ${w}`).join(`
|
|
58
|
+
`);o.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of n){let u=s.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&o.push(""," graph.resolvedToolsMap = {",...a," };"),o.push(""," return graph;","}",""),o.push("export { nodeConfigs };",""),o.join(`
|
|
59
|
+
`)}function Kr(n,e){let t=new Map,r=new Map;for(let s of n){let i=e[s.id]?.tools,o;if(Array.isArray(i)&&i.length>0)o=[...i].sort();else{let a=xe[s.nodeType];a?.length>0&&(o=[...a].sort())}if(o){let a=`${o.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(s.id,a),r.has(a)||r.set(a,o)}}return{toolsPerNode:t,toolIdsByVar:r}}function Vr(n,e){let t=[],r=[],s=new Map,i=new Set;for(let o of n)s.has(o.source)||s.set(o.source,[]),s.get(o.source).push(o);for(let o of n)if(!e.has(o.source))if(e.has(o.target)){if(i.has(o.target))continue;i.add(o.target);let l=(s.get(o.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&r.push({source:o.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:o.source,target:o.target});return{simpleEdges:t,conditionalEdges:r}}function qr(n,e,t){let r=new Set;for(let i of e)t.has(i.target)||r.add(i.target);let s=n.find(i=>!r.has(i.id));return s?s.id:n[0]?.id}function On(n){return n.replace(/[^a-zA-Z0-9]/g,"_")}H();var Xr=`## Composing deployed agents (wrapper over marketplace bricks)
|
|
60
60
|
|
|
61
61
|
**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
|
|
62
62
|
modify a brick template's source and never rebuild its logic from scratch.
|
|
@@ -125,4 +125,4 @@ template workflow.json) and paste the exact array. The platform then
|
|
|
125
125
|
automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
|
|
126
126
|
listed in a deployed wrapper's composedOf stops receiving standalone webhook
|
|
127
127
|
events), so the same event never double-fires a brick inside AND outside the
|
|
128
|
-
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{
|
|
128
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Ze as AgentStrategy,Ge as CI_ENV_VARS,Xr as COMPOSE_KNOWLEDGE,j as CompilationError,we as ContextLoader,de as DEFAULT_OUTPUT_BASE,Ie as DEFAULT_TRANSIENT_BACKOFF_MS,We as DEFAULT_TRANSIENT_RETRIES,Yn as EVENTS_FILE,oe as Graph,Ye as MAX_TRANSIENT_BACKOFF_MS,Lt as MAX_TRANSIENT_RETRIES,xe as NODE_DEFAULT_TOOLS,Zn as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,G as Node,ce as OutputParser,Ct as PROVIDER_ERROR_KIND_CLASS,Jn as RAW_OUTPUT_FILE,zn as RESULT_FILE,Le as SESSIONS_DIR,Y as SESSION_INFO_FILE,Fe as STOP_REQUEST_FILE,gt as STORE_NAME_REGEX,Gn as SchemaTypes,Bt as TRANSIENT_MESSAGE_PATTERNS,Te as Timeline,Mt as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,oe as WorkflowGraph,ae as WorkflowState,Je as classifyFailure,In as clearInheritedSessionEnvForFreshRun,Zt as clearSkills,Cr as compileGraph,ve as createAttemptBudget,at as dispatchSubgraph,Dr as extractSteps,Vn as formatProviderError,Gr as generateNodeConfigsJson,Fr as generateWorkflowCode,An as generateWorkflowSessionId,tt as getAgentStrategy,Jt as getAllSkills,dt as getNodeImpl,pt as getNodeTemplate,ft as getResolvedToolDefinitions,te as getSkill,zt as getSkillSource,Oe as hasNode,Ht as hasSkill,Xt as invokeAgent,qn as isTransientFailure,Pr as listNodeTypes,Yt as listSkillIds,qt as listStrategies,jt as providerErrorKindOf,Ut as providerErrorStatusOf,Tn as readPinnedSessionPathFromEnv,kn as registerNode,Wt as registerSkill,Vt as registerStrategy,et as resolveInvocationExtras,Qe as resolveInvocationModel,ht as resolveNodeTools,$n as resolveWorkflowSession,Wn as setLogger,bn as shouldTrustInheritedSessionEnv,vn as syncProcessEnvToSession,R as timeline,Gt as transientBackoffBaseMs,He as transientBackoffMs,Ft as transientRetryBudget,Br as validateGraphConfig,Lr as validateStoreDefs};
|