@zibby/agent-workflow 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/exec-context.d.ts +53 -0
- package/dist/exec-context.js +1 -0
- package/dist/graph-compiler.js +17 -17
- package/dist/graph.js +19 -19
- package/dist/in-process-subgraph.d.ts +59 -0
- package/dist/in-process-subgraph.js +1 -0
- package/dist/index.js +37 -37
- package/dist/sub-graph-executor.js +1 -1
- package/dist/subgraph-registry.d.ts +48 -0
- package/dist/subgraph-registry.js +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Vt=Object.defineProperty;var we=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var pe=(t,e)=>()=>(t&&(e=t(t=0)),e);var qe=(t,e)=>{for(var o in e)Vt(t,o,{get:e[o],enumerable:!0})};function Qt(t){X.impl={...Qe,...t}}var Xe,Qe,X,I,L=pe(()=>{Xe=()=>{},Qe={debug:Xe,info:Xe,warn:(...t)=>console.warn("[workflow]",...t),error:(...t)=>console.error("[workflow]",...t)},X={impl:Qe};I={debug:(...t)=>X.impl.debug?.(...t),info:(...t)=>X.impl.info?.(...t),warn:(...t)=>X.impl.warn?.(...t),error:(...t)=>X.impl.error?.(...t)}});var be,ve=pe(()=>{be=class{constructor(e,o,r=0){this.name=e,this.description=o,this.priority=r}async invoke(e,o={}){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 ft={};qe(ft,{clearSkills:()=>pt,getAllSkills:()=>ut,getSkill:()=>Z,hasSkill:()=>lt,listSkillIds:()=>dt,registerSkill:()=>ct});function ct(t){if(!t||typeof t.id!="string")throw new Error("Skill definition must include a string id");Y.set(t.id,Object.freeze({...t}))}function Z(t){return Y.get(t)||null}function lt(t){return Y.has(t)}function ut(){return new Map(Y)}function dt(){return Array.from(Y.keys())}function pt(){Y.clear()}var xe,Y,te=pe(()=>{xe=Symbol.for("@zibby/agent-workflow.skills");globalThis[xe]||(globalThis[xe]=new Map);Y=globalThis[xe]});var oe={};qe(oe,{getAgentStrategy:()=>Ae,invokeAgent:()=>mt,listStrategies:()=>gt,registerStrategy:()=>ht});function ht(t){if(!t||typeof t.getName!="function"||typeof t.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=F.findIndex(o=>o.getName()===t.getName());e>=0?F[e]=t:F.push(t)}function gt(){return F.map(t=>t.getName())}function Ae(t={}){let{state:e={},preferredAgent:o=null}=t,r=o||e.agentType||process.env.AGENT_TYPE;if(!r){let i=F.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}I.debug(`[workflow] agent selection: requested=${r}`);let n=F.find(i=>i.getName()===r);if(!n){let i=F.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!n.canHandle(t))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${n.getName()}`),n}async function mt(t,e={},o={}){let r=Ae(e),n=e.state?.config||o.config||{},i=n.models||{},s=o.nodeName&&i[o.nodeName]||null,a=i.default||null,c=n.agent?.[r.name]?.model||null,l=s||a||c||o.model||null,u={...o,model:l,workspace:e.state?.workspace||o.workspace,schema:o.schema||e.schema,images:o.images||e.images||[],skills:o.skills||e.skills||[],config:n},f=t,d=u.skills||[];if(d.length>0&&!o.skipPromptFragments){let S=d.map(g=>{let w=Z(g)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);S.length>0&&(f+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${S.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let m=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return m&&(f+=`
|
|
6
6
|
|
|
7
7
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
8
8
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
9
9
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`)
|
|
13
|
-
${
|
|
14
|
-
`)}`);return e}},
|
|
15
|
-
`?(s+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,s+=c):e.inEsc?(s+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,s+=c,e.col>=
|
|
16
|
-
${
|
|
11
|
+
${m}
|
|
12
|
+
`),I.debug(`[workflow] prompt length: ${f.length} chars`),r.invoke(f,u)}var ke,F,z=pe(()=>{ve();L();te();ke=Symbol.for("@zibby/agent-workflow.strategies");globalThis[ke]||(globalThis[ke]=[]);F=globalThis[ke]});var qt=new Set(["__proto__","constructor","prototype"]);function ye(t){if(qt.has(t))throw new Error(`Invalid state key: "${t}"`)}var V=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,o){ye(e),this._history.push({...this._state}),this._state[e]=o}update(e){let o=Object.getOwnPropertyNames(e);for(let r of o)ye(r);this._history.push({...this._state});for(let r of o)this._state[r]=e[r]}append(e,o){ye(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(o)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};var q=class{constructor(e){this.schema=e}parse(e){let o=e.match(/```json\s*([\s\S]*?)\s*```/);if(o)return this.validate(JSON.parse(o[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(n=>n[0]);for(let n of r)try{return this.validate(JSON.parse(n))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let o=[];for(let[r,n]of Object.entries(this.schema)){if(n.required&&!(r in e)&&o.push(`Missing required field: ${r}`),r in e&&n.type){let i=typeof e[r];i!==n.type&&o.push(`Field '${r}' expected ${n.type}, got ${i}`)}if(n.validate&&r in e){let i=n.validate(e[r]);i&&o.push(`Field '${r}': ${i}`)}}if(o.length>0)throw new Error(`Output validation failed:
|
|
13
|
+
${o.join(`
|
|
14
|
+
`)}`);return e}},Xt={string:(t=!0)=>({type:"string",required:t}),number:(t=!0)=>({type:"number",required:t}),boolean:(t=!0)=>({type:"boolean",required:t}),array:(t=!0)=>({type:"object",required:t,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(t,e=!0)=>({type:"string",required:e,validate:o=>t.includes(o)?null:`must be one of: ${t.join(", ")}`})};L();import{writeFileSync as Ne,readFileSync as St,existsSync as wt,mkdirSync as so}from"node:fs";import{join as Oe,dirname as io}from"node:path";import x from"chalk";var at="__WORKFLOW_GRAPH_LOG__",Q=x.gray("\u2502"),eo=x.gray("\u250C"),et=x.gray("\u2514"),_e=x.green("\u25C6"),tt=x.hex("#c084fc")("\u25C6"),ot=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),nt=`${Q} `,rt=2;function st(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function it(t,e){return(o,r,n)=>{if(typeof o!="string")return t(o,r,n);let i=process.stdout.columns||120,s="";for(let a=0;a<o.length;a++){let c=o[a];e.lineStart&&(s+=nt,e.col=rt,e.lineStart=!1),c===`
|
|
15
|
+
`?(s+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,s+=c):e.inEsc?(s+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,s+=c,e.col>=i&&(s+=`
|
|
16
|
+
${nt}`,e.col=rt))}return t(s,r,n)}}var fe=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},o={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=o,process.stdout.write=it(this._origStdoutWrite,e),process.stderr.write=it(this._origStderrWrite,o)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
17
17
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
18
18
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
19
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let
|
|
20
|
-
`;this._origStdoutWrite?this._origStdoutWrite(
|
|
21
|
-
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${
|
|
22
|
-
`)):process.stdout.write.bind(process.stdout)(`${e} ${
|
|
23
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
24
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
25
|
-
`)}stepMemory(e){let
|
|
26
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
27
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
28
|
-
|
|
29
|
-
${n}`);let a=r(),c=a.cwd||process.cwd(),l=a.sessionPath;try{if(l){let p=Ne(l,B);if(ut(p)){let g=JSON.parse(lt(p,"utf-8"));g.currentNode=this.name,be(p,JSON.stringify(g,null,2),"utf-8")}let u=Ne(l,"..",B);if(ut(u))try{let g=JSON.parse(lt(u,"utf-8"));g.currentNode=this.name,be(u,JSON.stringify(g,null,2),"utf-8")}catch{}}}catch(p){$.debug(`[workflow] could not update session info: ${p.message}`)}let d=null;for(let p=0;p<=this.retries;p++)try{$.debug(`[workflow] node '${this.name}' attempt ${p}`);let u=r().config||{},g=u.agents||{},m=this.config.agent??g[this.name]??null,h={state:r()};m&&(h.preferredAgent=m);let E={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:u,nodeName:this.name,timeout:this.config?.timeout||3e5},I=e?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(Z(),ee))).invokeAgent);let f=await I(n,h,E),y,v;if(typeof f=="string"?(y=f,v=null):f.structured?(y=f.raw||JSON.stringify(f.structured,null,2),v=f.structured):(y=f.raw||JSON.stringify(f,null,2),v=f.extracted||null),l)try{let S=Ne(l,this.name,"raw_stream_output.txt");Gt(Jt(S),{recursive:!0}),be(S,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(S){$.debug(`[workflow] could not save raw output: ${S.message}`)}if(this.isZodSchema&&v){$.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(v,null,2)}`);let S=v;if(typeof this.onComplete=="function")try{S=await this.onComplete(r(),v)}catch(P){$.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:S,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:y}),raw:y}}catch(S){throw new Error(`onComplete failed: ${S.message}`,{cause:S})}if(this.parser){let S=this.parser.parse(y);return $.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(S,null,2)}`),b.step("Output parsed"),{success:!0,output:S,raw:y}}return{success:!0,output:y,raw:y}}catch(u){d=u,p<this.retries&&$.info(`[workflow] node '${this.name}' failed, retrying (${p+1}/${this.retries})\u2026`)}return{success:!1,error:d.message,raw:null}}},te=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}};M();var Yt=2e3,Zt=600*1e3,Ht=new Set(["completed","failed","canceled","timeout"]);function Kt(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function Vt(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function zt(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function qt(){return process.env.EXECUTION_ID||null}function Xt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function dt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=Kt(),r=Vt(),i=zt(),n=qt(),s=`${t}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(o)}/trigger`,a={input:e.input||{},...n?{parentExecutionId:n}:{},...e.conversationId?{conversationId:e.conversationId}:{}};$.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${n||"<none>"}`);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(a)});if(!c.ok){let f=null,y="";try{f=await c.json(),y=f?.error||f?.message||JSON.stringify(f)}catch{y=await c.text().catch(()=>"")}if(c.status===429){let S=f?.quotaInfo||{},P=new Error(`Sub-graph '${o}' 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 P.code="SUBGRAPH_QUOTA_EXCEEDED",P.status=429,P.subgraph=o,P.quotaInfo=S,P}if(c.status===400){let S=new Error(`Sub-graph '${o}' rejected input: ${y}`);throw S.code="SUBGRAPH_INVALID_INPUT",S.status=400,S.subgraph=o,S.validationErrors=f?.validationErrors||null,S.missing=f?.missing||null,S}let v=new Error(`Sub-graph '${o}' trigger rejected (${c.status}): ${y}`);throw v.code="SUBGRAPH_TRIGGER_FAILED",v.status=c.status,v.subgraph=o,v}let l=await c.json(),d=l?.data?.jobId||l?.jobId;if(!d)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return $.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:o};let p=Number.isFinite(e.timeoutMs)?e.timeoutMs:Zt,u=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Yt,g=`${t}/executions/${encodeURIComponent(d)}`,m=Date.now()+p,h="accepted",E=0;for(;Date.now()<m;){await new Promise(S=>setTimeout(S,u)),E+=1;let f=await fetch(g,{headers:{Authorization:`Bearer ${i}`}});if(!f.ok){if(f.status>=500){$.warn(`[sub-graph] status poll for ${d} returned ${f.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${f.status}`)}let y=await f.json(),v=y?.data||y?.execution||y;if(h=v?.status||h,Ht.has(h)){if(h!=="completed"){let W=new Error(`Sub-graph '${o}' (${d}) ended in status '${h}'`);throw W.subgraphJobId=d,W.subgraphStatus=h,W}let S=v?.finalState||v?.state||{},P=Xt(S,e.output);return $.info(`[sub-graph] '${o}' (${d}) completed after ${E} polls`),P}}let I=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(p/1e3)}s (last status: ${h})`);throw I.subgraphJobId=d,I.subgraphStatus=h,I}import{existsSync as pt,readFileSync as Qt}from"node:fs";import{join as ke,dirname as ft}from"node:path";var oe=class{static async loadContext(e,t,r={}){let i={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=ft(ke(t,e));for(let c of n){let l=await this.findAndMergeContextFiles(c,a,t);if(l){let d=c.replace(/\.[^.]+$/,"").toLowerCase();i[d]=l}}}let s=r.discovery||{};for(let[a,c]of Object.entries(s))try{let l=ke(t,c);pt(l)&&(i[a]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${a}' from '${c}': ${l.message}`)}return i}static async findAndMergeContextFiles(e,t,r){let i=[],n=t;for(;n.startsWith(r);){let s=ke(n,e);if(pt(s))try{i.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=ft(n);if(a===n)break;n=a}return i.length===0?null:i.every(s=>typeof s=="string")?i.join(`
|
|
19
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let o=`${at}${JSON.stringify(e)}
|
|
20
|
+
`;this._origStdoutWrite?this._origStdoutWrite(o):process.stdout.write(o)}_writeDot(e,o){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
21
|
+
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${o}
|
|
22
|
+
`)):process.stdout.write.bind(process.stdout)(`${e} ${o}
|
|
23
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(_e,e):process.stdout.write.bind(process.stdout)(`${Q} ${_e} ${e}
|
|
24
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(tt,e):process.stdout.write.bind(process.stdout)(`${Q} ${tt} ${e}
|
|
25
|
+
`)}stepMemory(e){let o=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ot,o):process.stdout.write.bind(process.stdout)(`${Q} ${ot} ${o}
|
|
26
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${Q} ${Ie} ${x.red(e)}
|
|
27
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${eo} ${e}`),this._startIntercepting()}nodeComplete(e,o={}){this._stopIntercepting();let{duration:r,details:n}=o;if(n)for(let s of n)this._rawWrite(`${_e} ${s}`);let i=r?x.dim(` ${st(r)}`):"";this._rawWrite(`${et} ${x.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,o,r={}){this._stopIntercepting();let{duration:n}=r,i=n?x.dim(` ${st(n)}`):"";this._rawWrite(`${Ie} ${x.red(o)}`),this._rawWrite(`${et} ${x.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,o){this._rawWrite(x.dim(` ${e} \u2192 ${o}`)),this._rawWrite("")}graphComplete(){}},v=new fe;var ee=".zibby/output",Ee="sessions",j=".session-info.json",$e=".zibby-stop",to="result.json",oo="raw_stream_output.txt",no="events.json",ro={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",GIT:"git",SLACK:"slack",LARK:"lark",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session"},Te=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];var D=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new q(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,o){let r=()=>o&&typeof o.getAll=="function"?o.getAll():e,n=f=>o&&typeof o.get=="function"?o.get(f):e?.[f];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let f=await this.customExecute(e);return typeof f=="object"&&f!==null&&f.success===!1?{success:!1,error:f.error||"Node execution failed",raw:f.raw||null}:this.isZodSchema?(I.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){return I.error(`[workflow] node '${this.name}' failed: ${f.message}`),f.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(f.issues||f.errors,null,2)}`),{success:!1,error:f.message,raw:null}}}let i=typeof this.prompt=="function"?this.prompt(r()):this.prompt,s=n("_skillHints");s&&(i=`${s}
|
|
28
|
+
|
|
29
|
+
${i}`);let a=r(),c=a.cwd||process.cwd(),l=a.sessionPath;try{if(l){let f=Oe(l,j);if(wt(f)){let m=JSON.parse(St(f,"utf-8"));m.currentNode=this.name,Ne(f,JSON.stringify(m,null,2),"utf-8")}let d=Oe(l,"..",j);if(wt(d))try{let m=JSON.parse(St(d,"utf-8"));m.currentNode=this.name,Ne(d,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(f){I.debug(`[workflow] could not update session info: ${f.message}`)}let u=null;for(let f=0;f<=this.retries;f++)try{I.debug(`[workflow] node '${this.name}' attempt ${f}`);let d=r().config||{},m=d.agents||{},S=this.config.agent??m[this.name]??null,g={state:r()};S&&(g.preferredAgent=S);let w={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},$=e?._coreInvokeAgent;$||($=(await Promise.resolve().then(()=>(z(),oe))).invokeAgent);let p=await $(i,g,w),y,T;if(typeof p=="string"?(y=p,T=null):p.structured?(y=p.raw||JSON.stringify(p.structured,null,2),T=p.structured):(y=p.raw||JSON.stringify(p,null,2),T=p.extracted||null),l)try{let h=Oe(l,this.name,"raw_stream_output.txt");so(io(h),{recursive:!0}),Ne(h,typeof y=="string"?y:JSON.stringify(y),"utf-8")}catch(h){I.debug(`[workflow] could not save raw output: ${h.message}`)}if(this.isZodSchema&&T){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(T,null,2)}`);let h=T;if(typeof this.onComplete=="function")try{h=await this.onComplete(r(),T)}catch(R){I.warn(`[workflow] onComplete hook failed: ${R.message}`)}return{success:!0,output:h,raw:y}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:y}),raw:y}}catch(h){throw new Error(`onComplete failed: ${h.message}`,{cause:h})}if(this.parser){let h=this.parser.parse(y);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(h,null,2)}`),v.step("Output parsed"),{success:!0,output:h,raw:y}}return{success:!0,output:y,raw:y}}catch(d){u=d,f<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${f+1}/${this.retries})\u2026`)}return{success:!1,error:u.message,raw:null}}},ne=class extends D{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){let r=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}};L();L();import{mkdirSync as lo,existsSync as re,statSync as yn}from"node:fs";import{spawn as Tt}from"node:child_process";import{join as se}from"node:path";import{pathToFileURL as uo}from"node:url";import{AsyncLocalStorage as ao}from"node:async_hooks";var Ce=new ao;function Pe(){let t=Ce.getStore();return t||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function yt(t,e){let o=Ce.getStore()||Pe(),r=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??o.executionId??null,depth:(o.depth||0)+(t.executionId!==o.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:o.conversationId??null,dispatchMode:t.dispatchMode??null});return Ce.run(r,e)}var Re=new Map,Be=new Map,_t=new Map;function It(t,e,o={}){if(!t||typeof t!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Re.set(t,e),Be.set(t,"ready"),_t.set(t,{...o,cachedAt:Date.now()})}function Et(t,e){Be.set(t,"failed"),_t.set(t,{error:e?.message||String(e),failedAt:Date.now()}),Re.delete(t)}function $t(t){return Be.get(t)==="ready"?Re.get(t):null}var po=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function fo(){return Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10)}function ho(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var k=class extends Error{constructor(e,o){super(`in-process sub-graph fallback: ${e}${o?` (${o})`:""}`),this.fallback=!0,this.reason=e,this.detail=o||null,this.name="SubgraphFallback"}};function go(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),o=t||e,r=process.env.PROJECT_ID,n=process.env.PROJECT_API_TOKEN;if(!o||!r||!n)throw new k("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:o,projectId:r,authToken:n}}async function mo({apiBase:t,authToken:e,body:o}){let r;try{r=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)})}catch(i){throw new k("network",`begin fetch failed: ${i.message}`)}let n=null;try{n=await r.json()}catch{}if(!r.ok){if(r.status===404){let i=new Error(`Sub-graph child '${o.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(r.status===429){let i=n?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=i,s}if(r.status===400&&n?.validationErrors){let i=new Error(`Sub-graph rejected input: ${n?.error||n?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=n.validationErrors,i.missing=n.missing,i}throw new k("begin-status",`begin returned ${r.status}`)}return n?.data||n}async function U({apiBase:t,authToken:e,payload:o}){try{let r=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${o.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function So(t,e){let o=se(e,".ready"),r=se(e,"graph.mjs");if(re(o)&&re(r))return;lo(e,{recursive:!0});let n=se(e,".lock"),i=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),c=s(n,"wx");a(c),i=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!i){let s=Date.now()+3e4;for(;Date.now()<s;){if(re(o)&&re(r))return;await new Promise(a=>setTimeout(a,100))}throw new k("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,l)=>{let u=Tt("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),f=Tt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});u.stdout.pipe(f.stdin);let d,m,S=()=>{if(d!==void 0&&m!==void 0){if(d!==0)return l(new Error(`curl exited ${d}`));if(m!==0)return l(new Error(`tar exited ${m}`));c()}};u.on("close",g=>{d=g,S()}),f.on("close",g=>{m=g,S()}),u.on("error",l),f.on("error",l)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(o,"");try{a(n)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(n)}catch{}throw new k("bundle-extract-failed",s.message)}}async function wo(t){let e=se(t,"graph.mjs");if(!re(e))throw new k("entry-missing",`graph.mjs missing under ${t}`);let o;try{o=await import(uo(e).href)}catch(n){throw new k("import-failed",`${n?.code||n?.name||"unknown"}: ${n.message}`)}let r=o.default||Object.values(o).find(n=>typeof n=="function"&&n.prototype?.buildGraph);if(!r)throw new k("entry-class-missing","no buildGraph() class export found");return r}async function bt(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let o=Pe(),r=fo();if((o.depth||0)>=r)throw new k("depth-exceeded",`depth ${o.depth} \u2265 MAX_DEPTH ${r}`);let n;try{n=go()}catch(h){throw h}I.debug(`[in-process subgraph] begin '${t}' parent=${o.executionId||"<root>"}`);let i=await mo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:o.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:c,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d}=i,m=ho();if(a&&a!==m)throw await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new k("runtime-mismatch",`${m} vs ${a}`);if(!d||!c)throw await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new k("no-bundle","workflow bundle not built yet");let S=se(po,`${f}@${u||"0"}`);try{await So(c,S)}catch(h){throw h.fallback&&await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:h.message,code:h.reason}}}),h}let g=$t(t);if(!g)try{g=await wo(S),It(t,g,{workflowUuid:f,version:u,runtimeTag:a,cacheDir:S})}catch(h){throw Et(t,h),await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:h.message,code:h.reason||"IMPORT_FAILED"}}}),h.fallback?h:new k("import-failed",h.message)}let w=Date.now(),p=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph(),y={...e.input||{}},T;try{T=await yt({executionId:s,parentExecutionId:o.executionId,conversationId:e.conversationId!==void 0?e.conversationId:o.conversationId,dispatchMode:"inprocess"},()=>p.run(e.parentAgent,y,{signal:e.signal}))}catch(h){throw await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:h.message,code:h.code||"CHILD_THREW",stack:h.stack},durationMs:Date.now()-w}}),h}if(T?.stoppedExternally){await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:T,durationMs:Date.now()-w}});let h=new Error(`Sub-graph '${t}' canceled by parent abort`);throw h.code="SUBGRAPH_CANCELED",h.subgraphJobId=s,h}return await U({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:T,durationMs:Date.now()-w}}),{finalState:T,executionId:s}}var yo=2e3,_o=600*1e3,Io=new Set(["completed","failed","canceled","timeout"]);function Eo(){let t=process.env.PROGRESS_API_URL;if(!t)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return t.replace(/\/executions\/?$/,"")}function $o(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function To(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function bo(){return process.env.EXECUTION_ID||null}function vt(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((o,r)=>o==null?o:o[r],t):t}async function xt(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${t}'`);let{finalState:p}=await bt(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),y=vt(p,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),y}catch(p){if(p instanceof k||p?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${p.reason||"unknown"} \u2014 using HTTP`);else throw p}let o=Eo(),r=$o(),n=To(),i=bo(),s=`${o}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(t)}/trigger`,a={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(a)});if(!c.ok){let p=null,y="";try{p=await c.json(),y=p?.error||p?.message||JSON.stringify(p)}catch{y=await c.text().catch(()=>"")}if(c.status===429){let h=p?.quotaInfo||{},R=new Error(`Sub-graph '${t}' blocked by execution quota (${h.used??"?"}/${h.limit??"?"} on plan ${h.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=t,R.quotaInfo=h,R}if(c.status===400){let h=new Error(`Sub-graph '${t}' rejected input: ${y}`);throw h.code="SUBGRAPH_INVALID_INPUT",h.status=400,h.subgraph=t,h.validationErrors=p?.validationErrors||null,h.missing=p?.missing||null,h}let T=new Error(`Sub-graph '${t}' trigger rejected (${c.status}): ${y}`);throw T.code="SUBGRAPH_TRIGGER_FAILED",T.status=c.status,T.subgraph=t,T}let l=await c.json(),u=l?.data?.jobId||l?.jobId;if(!u)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${u} (not waiting)`),{jobId:u,status:"accepted",workflow:t};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:_o,d=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:yo,m=`${o}/executions/${encodeURIComponent(u)}`,S=Date.now()+f,g="accepted",w=0;for(;Date.now()<S;){await new Promise(h=>setTimeout(h,d)),w+=1;let p=await fetch(m,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok){if(p.status>=500){I.warn(`[sub-graph] status poll for ${u} returned ${p.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${u}: ${p.status}`)}let y=await p.json(),T=y?.data||y?.execution||y;if(g=T?.status||g,Io.has(g)){if(g!=="completed"){let G=new Error(`Sub-graph '${t}' (${u}) ended in status '${g}'`);throw G.subgraphJobId=u,G.subgraphStatus=g,G}let h=T?.finalState||T?.state||{},R=vt(h,e.output);return I.info(`[sub-graph] '${t}' (${u}) completed after ${w} polls`),R}}let $=new Error(`Sub-graph '${t}' (${u}) timed out after ${Math.round(f/1e3)}s (last status: ${g})`);throw $.subgraphJobId=u,$.subgraphStatus=g,$}import{existsSync as kt,readFileSync as vo}from"node:fs";import{join as Me,dirname as At}from"node:path";var ie=class{static async loadContext(e,o,r={}){let n={},i=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=At(Me(o,e));for(let c of i){let l=await this.findAndMergeContextFiles(c,a,o);if(l){let u=c.replace(/\.[^.]+$/,"").toLowerCase();n[u]=l}}}let s=r.discovery||{};for(let[a,c]of Object.entries(s))try{let l=Me(o,c);kt(l)&&(n[a]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${a}' from '${c}': ${l.message}`)}return n}static async findAndMergeContextFiles(e,o,r){let n=[],i=o;for(;i.startsWith(r);){let s=Me(i,e);if(kt(s))try{n.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=At(i);if(a===i)break;i=a}return n.length===0?null:n.every(s=>typeof s=="string")?n.join(`
|
|
30
30
|
|
|
31
31
|
---
|
|
32
32
|
|
|
33
|
-
`):
|
|
33
|
+
`):n.every(s=>typeof s=="object")?Object.assign({},...n):n[n.length-1]}static async loadFile(e){let o=vo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(o);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),n=await import(r(e).href);return n.default||n}return o}};import{mkdirSync as Ct,existsSync as De,writeFileSync as Nt,unlinkSync as xo}from"node:fs";import{join as W,resolve as Pt}from"node:path";import{config as ko}from"dotenv";import{zodToJsonSchema as Ot}from"zod-to-json-schema";import Ao from"handlebars";function No({traceFrom:t,sessionId:e,sessionPath:o,idSource:r,mkdirFresh:n}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${t} pid=${process.pid} ppid=${s} sessionId=${e} source=${r} mkdir=${n?"yes":"no"} path=${o}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let u=(new Error("session trace").stack||"").split(`
|
|
34
34
|
`).slice(2,14).join(`
|
|
35
|
-
`);console.log(`[zibby:session] stack (${
|
|
36
|
-
${
|
|
37
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
38
|
-
${
|
|
35
|
+
`);console.log(`[zibby:session] stack (${t}):
|
|
36
|
+
${u}`)}}function Rt(){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 Bt(){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 Pt(String(e).trim())}catch{return String(e).trim()}}function Mt(){Rt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Dt({sessionPath:t,sessionId:e}){t&&typeof t=="string"&&(process.env.ZIBBY_SESSION_PATH=t),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Lt(t={}){let e=Te.map(i=>process.env[i]).find(Boolean),o=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${o}`,n=t.paths?.sessionPrefix;return n?`${n}_${r}`:r}function jt({cwd:t=process.cwd(),config:e={},initialState:o={},traceFrom:r="resolveWorkflowSession"}={}){let n=o.sessionPath,i=o.sessionTimestamp,s="initialState.sessionPath";if(!n&&process.env.ZIBBY_SESSION_PATH)try{let l=Pt(String(process.env.ZIBBY_SESSION_PATH));l&&(n=l,s="ZIBBY_SESSION_PATH")}catch{}let a;if(n)a=String(n).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let l=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(l)a=l,s="ZIBBY_SESSION_ID";else{let f=e.sessionId!=null?String(e.sessionId).trim():"";f&&f!=="last"?(a=f,s="config.sessionId"):(a=Lt(e),s="generated")}i=i??Date.now();let u=e.paths?.output||ee;n=W(t,u,Ee,a)}let c=!De(n);return c&&Ct(n,{recursive:!0}),(c||s!=="initialState.sessionPath")&&No({traceFrom:r,sessionId:a,sessionPath:n,idSource:s,mkdirFresh:c}),Dt({sessionPath:n,sessionId:a}),{sessionPath:n,sessionId:a,sessionTimestamp:i}}var ae=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{return this.inputSchema.merge(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,o,r={}){if(!(o instanceof D)&&o&&typeof o=="object"&&typeof o.workflow=="string"){let i=o,s={name:e,_isCustomCode:!0,retries:i.retries,onComplete:i.onComplete,execute:async c=>{let l=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,u;return typeof i.input=="function"?u=i.input(l):i.input&&typeof i.input=="object"?u=i.input:u={},xt(i.workflow,{input:u,async:i.async===!0,conversationId:typeof i.conversationId=="function"?i.conversationId(l):i.conversationId,output:i.output,timeoutMs:i.timeoutMs,pollIntervalMs:i.pollIntervalMs,signal:l?._signal,parentAgent:c?.agent})}},a=new D(s);return a.name=e,this.nodes.set(e,a),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let n=o instanceof D?o:new D(o);return n.name=e,this.nodes.set(e,n),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addConditionalNode(e,o){return this.nodes.set(e,new ne({...o,name:e})),this}addEdge(e,o){return this.edges.set(e,o),this}setNodeType(e,o){return this.nodeTypeMap.set(e,o),this}addConditionalEdges(e,o,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:o,labels:r}),typeof o=="function"&&this.conditionalCodeMap.set(e,o.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,o,r,n,i){let s=r;for(let a=e.length-1;a>=0;a--){let c=e[a],l=s;s=()=>c(o,l,n,i)}return s()}serialize(){let e=[],o={};for(let[l,u]of this.nodes){let f=this.nodeTypeMap.get(l)||l;e.push({id:l,type:f,data:{nodeType:f,label:l}});let d={};u._isCustomCode&&typeof u.execute=="function"&&(d.customCode=u.execute.toString());let m=this.nodePrompts.get(l);if(m&&(d.prompt=m),typeof u.customExecute=="function"&&(d.executeCode=u.customExecute.toString()),u.outputSchema)try{if(typeof u.outputSchema._def<"u"){let w=Ot(u.outputSchema,{target:"openApi3"});d.outputSchema={jsonSchema:w,variables:this._flattenJsonSchemaToVariables(w)}}else d.outputSchema={schema:u.outputSchema}}catch(w){console.warn(`[workflow] failed to convert schema for ${l}:`,w.message)}let S=(this.resolvedToolsMap||{})[l];S?.toolIds&&(d.tools=S.toolIds);let g=Array.isArray(u?.config?.skills)?u.config.skills:Array.isArray(u?.skills)?u.skills:null;g&&g.length>0&&(d.skills=[...g]),Object.keys(d).length>0&&(o[l]=d)}let r=[];for(let[l,u]of this.edges)if(typeof u=="string")r.push({source:l,target:u});else if(u.conditional){let f=this.conditionalCodeMap.get(l)||u.routes.toString(),d=this._inferConditionalTargets(u.routes),m=u.labels||{};for(let S of d){let g={source:l,target:S,data:{conditionalCode:f}};m[S]&&(g.label=m[S]),r.push(g)}}let n=l=>{if(!l)return null;try{return Ot(l,{target:"openApi3"})}catch{return null}},i=this._runtimeSchema(),s=n(i||this.stateSchema),a=n(this.inputSchema),c=n(this.contextSchema);return{nodes:e,edges:r,nodeConfigs:o,stateSchema:s,inputSchema:a,contextSchema:c}}_inferConditionalTargets(e){let o=e.toString(),r=new Set,n=/return\s+['"]([^'"]+)['"]/g,i;for(;(i=n.exec(o))!==null;)r.add(i[1]);return[...r]}_flattenJsonSchemaToVariables(e,o=""){let r=e;if(e.$ref&&e.definitions){let n=e.$ref.replace("#/definitions/","");r=e.definitions[n]||e}return this._flattenSchema(r,o)}_flattenSchema(e,o=""){if(!e||typeof e!="object")return[];let r=[],n=e.properties||{},i=e.required||[];for(let[s,a]of Object.entries(n)){let c=o?`${o}.${s}`:s;r.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!i.includes(s)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${c}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,o=>o.toUpperCase()).trim()}_summarizeNodeOutput(e,o){if(!o||typeof o!="object")return[];let r=[];o.success!==void 0&&r.push(`Result: ${o.success?"passed":"failed"}`);for(let[n,i]of Object.entries(o))if(!(n==="success"||n==="raw"||n==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${n}: ${i}`);else if(Array.isArray(i)){let s=i.length,a=i.filter(l=>l?.passed===!0).length,c=i.some(l=>l?.passed!==void 0);r.push(c?`${n}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${n}: ${s} items`)}if(r.length>=4)break}return r}async run(e,o={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let n=new AbortController;r.signal&&(r.signal.aborted?n.abort():r.signal.addEventListener("abort",()=>n.abort(),{once:!0}));let i=r.strategyAbortTimeoutMs??o.config?.strategyAbortTimeoutMs??5e3,s=o.cwd||process.cwd();ko({path:W(s,".env")});let a=o.config||{};if(!a||Object.keys(a).length===0)try{let E=W(s,".zibby.config.js");De(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=o.agentType;if(!c){let E=a?.agent;E?.provider?c=E.provider:E?.gemini?c="gemini":E?.claude?c="claude":E?.cursor?c="cursor":E?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let l=o.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},u=this._runtimeSchema();if(u){let E=u.safeParse(o);if(!E.success){let A=E.error.issues.map(N=>`${N.path.join(".")}: ${N.message}`);throw console.error("\u274C Initial state validation failed:"),A.forEach(N=>console.error(` - ${N}`)),new Error(`State validation failed: ${A.join(", ")}`)}v.step("State validated against schema")}let f=Bt(),d=o.sessionPath||f;d||Mt();let{sessionPath:m,sessionTimestamp:S,sessionId:g}=jt({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:d,sessionTimestamp:o.sessionTimestamp}});v.step(`Session ${g}`);let w=await ie.loadContext(o.specPath||"",s,l);Object.keys(w).length>0&&v.step(`Context loaded: ${Object.keys(w).join(", ")}`);let $=o.outputPath;!$&&o.specPath&&(e?.calculateOutputPath?$=e.calculateOutputPath(o.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${o.specPath})`));let p=new V({...o,config:a,agentType:c,outputPath:$,sessionPath:m,sessionTimestamp:S,context:w,resolvedTools:this.resolvedToolsMap||{},_signal:n.signal}),y=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:T}=await Promise.resolve().then(()=>(te(),ft)),h=a.skills&&typeof a.skills=="object"?a.skills:{},R=Object.values(h).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),G=E=>{for(let A of R)if(A.id===E)return A;return T(E)},Ge=new Set;for(let[,E]of this.nodes)for(let A of E.config?.skills||[])Ge.add(A);for(let E of Ge){let A=G(E);if(typeof A?.middleware=="function")try{let N=await A.middleware();typeof N=="function"&&y.set(E,N)}catch{}}let _=this.entryPoint,le=[],Je=a?.recursionLimit??100,Gt=0;try{for(;_&&_!=="END";){if(++Gt>Je)throw new Error(`Workflow exceeded recursion limit (${Je}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let A=W(m,$e);if(De(A)){try{xo(A)}catch{}n.abort()}if(n.signal.aborted)return console.warn(`
|
|
37
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),v.step("Workflow stopped externally"),{success:!0,state:p.getAll(),executionLog:le,stoppedExternally:!0};let N=this.nodes.get(_);if(!N)throw new Error(`Node '${_}' not found in graph`);let He=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:_,createdAt:new Date().toISOString(),config:p.get("config")}),Jt=W(m,j);Nt(Jt,He,"utf-8");let Ye=p.get("config")?.paths?.output||ee,Ht=W(s,Ye,j);Ct(W(s,Ye),{recursive:!0});try{Nt(Ht,He,"utf-8")}catch{}let Ze=o.onPipelineProgress;if(typeof Ze=="function")try{Ze({cwd:s,sessionPath:m,sessionId:g,outputBase:p.get("config")?.paths?.output||ee,currentNode:_})}catch{}let Yt=(this.resolvedToolsMap||{})[_]||null;p.set("_currentNodeTools",Yt);let Zt=p.get("nodeConfigs")||{};p.set("_currentNodeConfig",Zt[_]||{}),v.nodeStart(_);let ze=Date.now(),ue=this.nodePrompts.get(_);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(z(),oe));this._invokeAgent=O.invokeAgent}let zt=this._invokeAgent,Se={},Kt=N.config?.skills||[];for(let O of Kt){let C=G(O);if(typeof C?.invokeAgentOptions=="function")try{let b=C.invokeAgentOptions(p.getAll(),{agentType:p.get("agentType"),nodeName:_});b&&typeof b=="object"&&(Se={...Se,...b})}catch(b){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${b.message}`)}}let Ke=async(O,C,b={})=>{let P=zt(O,C,{...Se,...b,signal:n.signal});return P.catch(()=>{}),n.signal.aborted?P:Promise.race([P,new Promise((J,H)=>{let M=()=>{setTimeout(()=>{let K=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);K.name="AbortError",H(K)},i)};n.signal.addEventListener("abort",M,{once:!0})})])},Ve={state:p,invokeAgent:async(O={},C={})=>{let b=C.prompt||"";if(ue){let P=this._compiledPrompts.get(_);P||(P=Ao.compile(ue,{noEscape:!0}),this._compiledPrompts.set(_,P));try{b=P(O)}catch(J){throw console.error(`\u274C Template rendering failed for node '${_}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!b)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return Ke(b,{state:p.getAll(),images:C.images||[]},{model:C.model||p.get("model"),workspace:p.get("workspace"),schema:C.schema,...C,signal:n.signal})},_coreInvokeAgent:Ke,agent:e,nodeId:_,promptTemplate:ue,getPromptTemplate:()=>ue,...p.getAll()};try{let O=(N.config?.skills||[]).map(M=>y.get(M)).filter(Boolean),C=[...this.middleware,...O],b;C.length>0?b=await this._composeMiddleware(C,_,async()=>N.execute(Ve,p),p.getAll(),p):b=await N.execute(Ve,p);let P=Date.now()-ze;if(le.push({node:_,success:b.success,duration:P,timestamp:new Date().toISOString()}),!b.success){if(n.signal.aborted)return v.step("Workflow stopped externally"),{success:!0,state:p.getAll(),executionLog:le,stoppedExternally:!0};p.append("errors",{node:_,error:b.error});let M=N.config?.retries||0,K=`${_}_retries`,de=p.getAll()[K]||0;if(de<M){v.stepInfo(`Retrying (attempt ${de+1}/${M})`),p.update({[K]:de+1,[`${_}_raw`]:b.raw});continue}throw v.nodeFailed(_,b.error,{duration:P}),new Error(`Node '${_}' failed after ${de} attempts: ${b.error}`)}p.update({[_]:b.output});let J=this._summarizeNodeOutput(_,b.output);v.nodeComplete(_,{duration:P,details:J});let H=this.edges.get(_);if(!H)_="END";else if(H.conditional){let M=H.routes(p.getAll());v.route(_,M),_=M}else _=H}catch(O){throw v.isInsideNode&&v.nodeFailed(_,O.message,{duration:Date.now()-ze}),p.set("failed",!0),p.set("failedAt",_),O}}v.graphComplete();let E={success:!0,state:p.getAll(),executionLog:le};return e&&typeof e.onComplete=="function"&&await e.onComplete(E),E}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};var Le=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Le]||(globalThis[Le]=new Map);var ce=globalThis[Le];function Ft(t,e){ce.set(t,e)}function je(t){return ce.get(t)}function he(t){return ce.has(t)}function Oo(){return Array.from(ce.keys())}function Fe(t){let e=ce.get(t);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Ft("ai_agent",{name:"ai_agent",factory:!0,create:(t,e={})=>({name:t,_isCustomCode:!0,execute:async o=>{let r=o?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(z(),oe))).invokeAgent);let n=e.extraPromptInstructions||"Execute the task based on the current state.",i=Co(n,o),s=await r(i,{cwd:o.workspace||process.cwd(),model:o.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:t},raw:typeof s=="string"?s:s.raw}}})});function Co(t,e){let o=/@([\w.]+)/g,r=new Set,n;for(;(n=o.exec(t))!==null;)r.add(n[1]);if(r.size===0)return t;let i=[],s=new Set;for(let a of r){let c=a.split(".")[0];if(s.has(c))continue;let l=a.split(".").reduce((d,m)=>d?.[m],e);if(l===void 0)continue;let u=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),f=a.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());i.push(`## ${f}
|
|
38
|
+
${u}`),a.includes(".")||s.add(c)}return i.length===0?t:`${t}
|
|
39
39
|
|
|
40
40
|
---
|
|
41
41
|
# Referenced Context
|
|
42
42
|
|
|
43
|
-
${
|
|
44
|
-
|
|
45
|
-
`)}`}
|
|
46
|
-
`)}function
|
|
47
|
-
`)}function
|
|
48
|
-
`)}function
|
|
49
|
-
`)}function
|
|
50
|
-
`)}function
|
|
51
|
-
`)}function
|
|
52
|
-
`).map((
|
|
53
|
-
`);s.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of
|
|
54
|
-
`)}function
|
|
43
|
+
${i.join(`
|
|
44
|
+
|
|
45
|
+
`)}`}te();L();var ge={};function We(t,e){if(Array.isArray(e))return Ue(e);let o=ge[t];return!o||o.length===0?null:Ue(o)}function Ue(t){if(!Array.isArray(t)||t.length===0)return null;let e=[],o={},r=[];for(let n of t){let i=Z(n);if(!i){I.warn(`[workflow] unknown skill "${n}" \u2014 skipping`);continue}r.push(n);for(let s of i.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!o[i.serverName])if(typeof i.resolve=="function"){let s=i.resolve();s&&(o[i.serverName]={...s,toolPrefix:n})}else{let s={};for(let a of i.envKeys||[]){let c=process.env[a];c&&(s[a]=c)}o[i.serverName]={command:i.command,args:[...i.args||[]],env:s,toolPrefix:n}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:o}}L();function Po(t,e={}){let{nodes:o,edges:r,nodeConfigs:n={}}=t;if(!Array.isArray(o)||o.length===0)throw new B("Graph must have at least one node");if(!Array.isArray(r))throw new B("Graph edges must be an array");let i=new ae(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let s=new Set,a=new Map,c={};for(let d of o){let m=me(d);a.set(d.id,{...d,resolvedType:m}),m==="decision"&&s.add(d.id)}for(let[d,m]of a){if(s.has(d))continue;let S=m.resolvedType,g=n[d]||{},w=We(S,g.tools);w&&(c[d]=w);let $={};g.prompt&&($.prompt=g.prompt);let p=he(S);if(I.debug(`[workflow] compiler: node "${d}" type="${S}" registered=${p}`),g.customCode&&!p)i.addNode(d,Ut(d,g.customCode,g),$),i.setNodeType(d,S);else if(p){let y=je(S);y.factory?i.addNode(d,y.create(d,{...g,resolvedTools:w}),$):i.addNode(d,y,$),i.setNodeType(d,S)}else if(g.executeCode)i.addNode(d,Ut(d,g.executeCode,g),$),i.setNodeType(d,S);else throw new B(`Unknown node type "${S}" for node "${d}". Did you forget to register it?`)}i.resolvedToolsMap=c;let l=new Set;for(let d of r)s.has(d.target)||l.add(d.target);let u=o.find(d=>!s.has(d.id)&&!l.has(d.id));if(!u)throw new B("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(u.id);let f=Mo(r,"source");for(let d of r)if(!s.has(d.source))if(s.has(d.target)){let m=d.target,S=f.get(m)||[];if(S.length===0)throw new B(`Decision node "${m}" has no outgoing edges`);let g=Do(m,S,s);i.addConditionalEdges(d.source,g)}else i.addEdge(d.source,d.target);return i}function Ro(t){let e=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(t.nodes)||t.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(t.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let o=t.nodeConfigs||{};for(let a of t.nodes){let c=me(a);if(c==="decision"||he(c))continue;let l=o[a.id]||{};l.customCode||l.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(t.nodes.map(a=>a.id));for(let a of t.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 n=new Set(t.nodes.filter(a=>me(a)==="decision").map(a=>a.id)),i=new Set;for(let a of t.edges)n.has(a.target)||i.add(a.target);let s=t.nodes.filter(a=>!n.has(a.id)&&!i.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of n){let c=t.edges.filter(u=>u.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(u=>u.data?.conditionalCode||u.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Bo(t){return!t||!Array.isArray(t.nodes)?[]:t.nodes.filter(e=>me(e)!=="decision").map(e=>e.id)}function me(t){let e=t.data?.nodeType||t.data?.type||t.type;return e==="workflowNode"||e==="custom"||e==="default"?t.id:e}function Mo(t,e){let o=new Map;for(let r of t){let n=r[e];o.has(n)||o.set(n,[]),o.get(n).push(r)}return o}function Do(t,e,o){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new B(`Decision node "${t}" has no conditionalCode on its outgoing edges`);let n=r.data?.conditionalCode||r.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!o.has(a))),s;try{let c=new Function(`return (${n})`)();s=l=>{let u=c(l);return i.has(u)||I.warn(`[workflow] conditional route from "${t}" returned "${u}" which is not in valid targets: ${[...i].join(", ")}`),u}}catch(a){throw new B(`Failed to compile conditionalCode for "${t}": ${a.message}`)}return s}function Ut(t,e,o={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new B(`Failed to compile customCode for node "${t}": ${s.message}`)}let n=r(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(z(),oe));return a(...s)},typeof we<"u"?we:void 0,console),i=null;return o.outputSchema&&(i=o.outputSchema.jsonSchema||o.outputSchema),{name:t,_isCustomCode:!0,outputSchema:i,execute:async s=>{try{let a=await n(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var B=class extends Error{constructor(e){super(e),this.name="CompilationError"}};te();ve();z();function Lo(t,e={}){let{nodes:o,edges:r,nodeConfigs:n={}}=t,i=new Set,s=[],a=new Map;for(let w of o){let $=w.data?.nodeType||w.type;a.set(w.id,$),$==="decision"?i.add(w.id):s.push({id:w.id,nodeType:$,label:w.data?.label||w.id})}let c=s.some(w=>{let $=n[w.id]||{};return!$.customCode&&!$.executeCode}),{toolsPerNode:l,toolIdsByVar:u}=Yo(s,n),{simpleEdges:f,conditionalEdges:d}=Zo(r,i),m=zo(s,r,i),S=[],g=e.workflowType||"workflow";return S.push(Fo(e)),S.push(Uo(g,{usesRegisteredNodes:c})),S.push(Wo(u)),S.push(Go(g)),S.push(Jo(s,n)),S.push(Ho(s,m,f,d,l,g)),S.filter(Boolean).join(`
|
|
46
|
+
`)}function jo(t){let e={};for(let[o,r]of Object.entries(t)){let{tools:n,...i}=r;Object.keys(i).length>0&&(e[o]=i)}return e}function Fo(t){let e=t.workflowType||"workflow";return["// Generated workflow",`// ${t.projectId?`Project: ${t.projectId} | `:""}Type: ${e} | Version: ${t.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
47
|
+
`)}function Uo(t,{usesRegisteredNodes:e=!0}={}){let o=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&o.push("// import './register-nodes.js'; // register custom node types here"),o.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),o.join(`
|
|
48
|
+
`)}function Wo(t){if(t.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[o,r]of t)e.push(`const ${o} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return e.push(""),e.join(`
|
|
49
|
+
`)}function Go(t){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-${t}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
50
|
+
`)}function Jo(t,e){let o=["// \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 t){let n=Wt(r.id),i=e[r.id]?.customCode;if(i)o.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),o.push(`const ${n}_execute = ${i};`);else{let s=Fe(r.nodeType);s?(o.push(`// Default "${r.nodeType}" implementation`),o.push(`const ${n}_execute = ${s};`)):(o.push(`// No template for "${r.nodeType}" \u2014 passthrough`),o.push(`const ${n}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}o.push("")}return o.join(`
|
|
51
|
+
`)}function Ho(t,e,o,r,n,i){let s=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];s.push("export function buildGraph(options = {}) {"),s.push(" const graph = new WorkflowGraph(options);",""),s.push(" // Nodes");for(let c of t){let l=Wt(c.id);s.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),s.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}s.push("",` graph.setEntryPoint('${e}');`,""),(o.length>0||r.length>0)&&s.push(" // Edges");for(let c of o)s.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of r){let l=c.code.split(`
|
|
52
|
+
`).map((u,f)=>f===0?u:` ${u}`).join(`
|
|
53
|
+
`);s.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of t){let l=n.get(c.id);l&&a.push(` '${c.id}': ${l},`)}return a.length>0&&s.push(""," graph.resolvedToolsMap = {",...a," };"),s.push(""," return graph;","}",""),s.push("export { nodeConfigs };",""),s.join(`
|
|
54
|
+
`)}function Yo(t,e){let o=new Map,r=new Map;for(let n of t){let i=e[n.id]?.tools,s;if(Array.isArray(i)&&i.length>0)s=[...i].sort();else{let a=ge[n.nodeType];a?.length>0&&(s=[...a].sort())}if(s){let a=`${s.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(n.id,a),r.has(a)||r.set(a,s)}}return{toolsPerNode:o,toolIdsByVar:r}}function Zo(t,e){let o=[],r=[],n=new Map,i=new Set;for(let s of t)n.has(s.source)||n.set(s.source,[]),n.get(s.source).push(s);for(let s of t)if(!e.has(s.source))if(e.has(s.target)){if(i.has(s.target))continue;i.add(s.target);let c=(n.get(s.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);c&&r.push({source:s.source,code:c.data?.conditionalCode||c.conditionalCode})}else o.push({source:s.source,target:s.target});return{simpleEdges:o,conditionalEdges:r}}function zo(t,e,o){let r=new Set;for(let i of e)o.has(i.target)||r.add(i.target);let n=t.find(i=>!r.has(i.id));return n?n.id:t[0]?.id}function Wt(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}L();export{be as AgentStrategy,Te as CI_ENV_VARS,B as CompilationError,ne as ConditionalNode,ie as ContextLoader,ee as DEFAULT_OUTPUT_BASE,no as EVENTS_FILE,ge as NODE_DEFAULT_TOOLS,D as Node,q as OutputParser,oo as RAW_OUTPUT_FILE,to as RESULT_FILE,Ee as SESSIONS_DIR,j as SESSION_INFO_FILE,ro as SKILLS,$e as STOP_REQUEST_FILE,Xt as SchemaTypes,fe as Timeline,at as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ae as WorkflowGraph,V as WorkflowState,Mt as clearInheritedSessionEnvForFreshRun,pt as clearSkills,Po as compileGraph,Bo as extractSteps,jo as generateNodeConfigsJson,Lo as generateWorkflowCode,Lt as generateWorkflowSessionId,Ae as getAgentStrategy,ut as getAllSkills,je as getNodeImpl,Fe as getNodeTemplate,Ue as getResolvedToolDefinitions,Z as getSkill,he as hasNode,lt as hasSkill,mt as invokeAgent,Oo as listNodeTypes,dt as listSkillIds,gt as listStrategies,Bt as readPinnedSessionPathFromEnv,Ft as registerNode,ct as registerSkill,ht as registerStrategy,We as resolveNodeTools,jt as resolveWorkflowSession,Qt as setLogger,Rt as shouldTrustInheritedSessionEnv,Dt as syncProcessEnvToSession,v as timeline,Ro as validateGraphConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _=()=>{},A={debug:_,info:_,warn:(...t)=>console.warn("[workflow]",...t),error:(...t)=>console.error("[workflow]",...t)},l={impl:A};var d={debug:(...t)=>l.impl.debug?.(...t),info:(...t)=>l.impl.info?.(...t),warn:(...t)=>l.impl.warn?.(...t),error:(...t)=>l.impl.error?.(...t)};var P=2e3,m=600*1e3,O=new Set(["completed","failed","canceled","timeout"]);function U(){let t=process.env.PROGRESS_API_URL;if(!t)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return t.replace(/\/executions\/?$/,"")}function j(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function x(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function J(){return process.env.EXECUTION_ID||null}function C(t,r){return r==null?t:typeof r=="function"?r(t):typeof r=="string"?r.split(".").reduce((p,g)=>p==null?p:p[g],t):t}async function M(t,r={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let p=U(),g=j(),$=x(),h=J(),w=`${p}/projects/${encodeURIComponent(g)}/workflows/${encodeURIComponent(t)}/trigger`,T={input:r.input||{},...h?{parentExecutionId:h}:{},...r.conversationId?{conversationId:r.conversationId}:{}};d.info(`[sub-graph] dispatching '${t}' (${r.async?"async":"sync"}) from parent ${h||"<none>"}`);let o=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`},body:JSON.stringify(T)});if(!o.ok){let n=null,i="";try{n=await o.json(),i=n?.error||n?.message||JSON.stringify(n)}catch{i=await o.text().catch(()=>"")}if(o.status===429){let e=n?.quotaInfo||{},c=new Error(`Sub-graph '${t}' blocked by execution quota (${e.used??"?"}/${e.limit??"?"} on plan ${e.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw c.code="SUBGRAPH_QUOTA_EXCEEDED",c.status=429,c.subgraph=t,c.quotaInfo=e,c}if(o.status===400){let e=new Error(`Sub-graph '${t}' rejected input: ${i}`);throw e.code="SUBGRAPH_INVALID_INPUT",e.status=400,e.subgraph=t,e.validationErrors=n?.validationErrors||null,e.missing=n?.missing||null,e}let u=new Error(`Sub-graph '${t}' trigger rejected (${o.status}): ${i}`);throw u.code="SUBGRAPH_TRIGGER_FAILED",u.status=o.status,u.subgraph=t,u}let b=await o.json(),s=b?.data?.jobId||b?.jobId;if(!s)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(b).slice(0,200)}`);if(r.async)return d.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${s} (not waiting)`),{jobId:s,status:"accepted",workflow:t};let E=Number.isFinite(r.timeoutMs)?r.timeoutMs:m,y=Number.isFinite(r.pollIntervalMs)?r.pollIntervalMs:P,R=`${p}/executions/${encodeURIComponent(s)}`,v=Date.now()+E,a="accepted",S=0;for(;Date.now()<v;){await new Promise(e=>setTimeout(e,y)),S+=1;let n=await fetch(R,{headers:{Authorization:`Bearer ${$}`}});if(!n.ok){if(n.status>=500){d.warn(`[sub-graph] status poll for ${s} returned ${n.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${s}: ${n.status}`)}let i=await n.json(),u=i?.data||i?.execution||i;if(a=u?.status||a,O.has(a)){if(a!=="completed"){let I=new Error(`Sub-graph '${t}' (${s}) ended in status '${a}'`);throw I.subgraphJobId=s,I.subgraphStatus=a,I}let e=u?.finalState||u?.state||{},c=C(e,r.output);return d.info(`[sub-graph] '${t}' (${s}) completed after ${S} polls`),c}}let f=new Error(`Sub-graph '${t}' (${s}) timed out after ${Math.round(E/1e3)}s (last status: ${a})`);throw f.subgraphJobId=s,f.subgraphStatus=a,f}export{M as dispatchSubgraph};
|
|
1
|
+
var U=()=>{},q={debug:U,info:U,warn:(...t)=>console.warn("[workflow]",...t),error:(...t)=>console.error("[workflow]",...t)},v={impl:q};var I={debug:(...t)=>v.impl.debug?.(...t),info:(...t)=>v.impl.info?.(...t),warn:(...t)=>v.impl.warn?.(...t),error:(...t)=>v.impl.error?.(...t)};import{mkdirSync as N,existsSync as _,statSync as lt}from"node:fs";import{spawn as G}from"node:child_process";import{join as x}from"node:path";import{pathToFileURL as X}from"node:url";import{AsyncLocalStorage as F}from"node:async_hooks";var P=new F;function B(){let t=P.getStore();return t||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function k(t,e){let r=P.getStore()||B(),s=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(t.executionId!==r.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId??null,dispatchMode:t.dispatchMode??null});return P.run(s,e)}var O=new Map,C=new Map,D=new Map;function M(t,e,r={}){if(!t||typeof t!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");O.set(t,e),C.set(t,"ready"),D.set(t,{...r,cachedAt:Date.now()})}function j(t,e){C.set(t,"failed"),D.set(t,{error:e?.message||String(e),failedAt:Date.now()}),O.delete(t)}function L(t){return C.get(t)==="ready"?O.get(t):null}var V=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function K(){return Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10)}function Y(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var p=class extends Error{constructor(e,r){super(`in-process sub-graph fallback: ${e}${r?` (${r})`:""}`),this.fallback=!0,this.reason=e,this.detail=r||null,this.name="SubgraphFallback"}};function Z(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=t||e,s=process.env.PROJECT_ID,n=process.env.PROJECT_API_TOKEN;if(!r||!s||!n)throw new p("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:s,authToken:n}}async function W({apiBase:t,authToken:e,body:r}){let s;try{s=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)})}catch(i){throw new p("network",`begin fetch failed: ${i.message}`)}let n=null;try{n=await s.json()}catch{}if(!s.ok){if(s.status===404){let i=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw i.code="SUBGRAPH_NOT_FOUND",i.status=404,i}if(s.status===429){let i=n?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${i.used??"?"}/${i.limit??"?"} on ${i.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=i,a}if(s.status===400&&n?.validationErrors){let i=new Error(`Sub-graph rejected input: ${n?.error||n?.message||"validation failed"}`);throw i.code="SUBGRAPH_INVALID_INPUT",i.status=400,i.validationErrors=n.validationErrors,i.missing=n.missing,i}throw new p("begin-status",`begin returned ${s.status}`)}return n?.data||n}async function $({apiBase:t,authToken:e,payload:r}){try{let s=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});s.ok||I.warn(`[in-process subgraph] finalize returned ${s.status} for ${r.childExecutionId}`)}catch(s){I.warn(`[in-process subgraph] finalize failed: ${s.message}`)}}async function Q(t,e){let r=x(e,".ready"),s=x(e,"graph.mjs");if(_(r)&&_(s))return;N(e,{recursive:!0});let n=x(e,".lock"),i=!1;try{let{openSync:a,closeSync:l}=await import("node:fs"),h=a(n,"wx");l(h),i=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!i){let a=Date.now()+3e4;for(;Date.now()<a;){if(_(r)&&_(s))return;await new Promise(l=>setTimeout(l,100))}throw new p("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((h,w)=>{let d=G("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),E=G("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(E.stdin);let y,b,m=()=>{if(y!==void 0&&b!==void 0){if(y!==0)return w(new Error(`curl exited ${y}`));if(b!==0)return w(new Error(`tar exited ${b}`));h()}};d.on("close",u=>{y=u,m()}),E.on("close",u=>{b=u,m()}),d.on("error",w),E.on("error",w)});let{writeFileSync:a,unlinkSync:l}=await import("node:fs");a(r,"");try{l(n)}catch{}}catch(a){try{let{unlinkSync:l}=await import("node:fs");l(n)}catch{}throw new p("bundle-extract-failed",a.message)}}async function tt(t){let e=x(t,"graph.mjs");if(!_(e))throw new p("entry-missing",`graph.mjs missing under ${t}`);let r;try{r=await import(X(e).href)}catch(n){throw new p("import-failed",`${n?.code||n?.name||"unknown"}: ${n.message}`)}let s=r.default||Object.values(r).find(n=>typeof n=="function"&&n.prototype?.buildGraph);if(!s)throw new p("entry-class-missing","no buildGraph() class export found");return s}async function H(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=B(),s=K();if((r.depth||0)>=s)throw new p("depth-exceeded",`depth ${r.depth} \u2265 MAX_DEPTH ${s}`);let n;try{n=Z()}catch(o){throw o}I.debug(`[in-process subgraph] begin '${t}' parent=${r.executionId||"<root>"}`);let i=await W({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:a,runtimeTag:l,bundlePresignedUrl:h,sourcesPresignedUrl:w,workflowVersion:d,workflowUuid:E,bundleReady:y}=i,b=Y();if(l&&l!==b)throw await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"canceled",error:{message:`runtimeTag mismatch: parent=${b} child=${l}`,code:"RUNTIME_MISMATCH"}}}),new p("runtime-mismatch",`${b} vs ${l}`);if(!y||!h)throw await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new p("no-bundle","workflow bundle not built yet");let m=x(V,`${E}@${d||"0"}`);try{await Q(h,m)}catch(o){throw o.fallback&&await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:o.message,code:o.reason}}}),o}let u=L(t);if(!u)try{u=await tt(m),M(t,u,{workflowUuid:E,version:d,runtimeTag:l,cacheDir:m})}catch(o){throw j(t,o),await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:o.message,code:o.reason||"IMPORT_FAILED"}}}),o.fallback?o:new p("import-failed",o.message)}let T=Date.now(),c=await(typeof u=="function"&&u.prototype?.buildGraph?new u:u).buildGraph(),f={...e.input||{}},g;try{g=await k({executionId:a,parentExecutionId:r.executionId,conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>c.run(e.parentAgent,f,{signal:e.signal}))}catch(o){throw await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"failed",error:{message:o.message,code:o.code||"CHILD_THREW",stack:o.stack},durationMs:Date.now()-T}}),o}if(g?.stoppedExternally){await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"canceled",finalState:g,durationMs:Date.now()-T}});let o=new Error(`Sub-graph '${t}' canceled by parent abort`);throw o.code="SUBGRAPH_CANCELED",o.subgraphJobId=a,o}return await $({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:a,status:"completed",finalState:g,durationMs:Date.now()-T}}),{finalState:g,executionId:a}}var et=2e3,nt=600*1e3,rt=new Set(["completed","failed","canceled","timeout"]);function ot(){let t=process.env.PROGRESS_API_URL;if(!t)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return t.replace(/\/executions\/?$/,"")}function st(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function at(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function it(){return process.env.EXECUTION_ID||null}function J(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((r,s)=>r==null?r:r[s],t):t}async function mt(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${t}'`);let{finalState:c}=await H(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),f=J(c,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),f}catch(c){if(c instanceof p||c?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${c.reason||"unknown"} \u2014 using HTTP`);else throw c}let r=ot(),s=st(),n=at(),i=it(),a=`${r}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(t)}/trigger`,l={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let h=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(l)});if(!h.ok){let c=null,f="";try{c=await h.json(),f=c?.error||c?.message||JSON.stringify(c)}catch{f=await h.text().catch(()=>"")}if(h.status===429){let o=c?.quotaInfo||{},S=new Error(`Sub-graph '${t}' blocked by execution quota (${o.used??"?"}/${o.limit??"?"} on plan ${o.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw S.code="SUBGRAPH_QUOTA_EXCEEDED",S.status=429,S.subgraph=t,S.quotaInfo=o,S}if(h.status===400){let o=new Error(`Sub-graph '${t}' rejected input: ${f}`);throw o.code="SUBGRAPH_INVALID_INPUT",o.status=400,o.subgraph=t,o.validationErrors=c?.validationErrors||null,o.missing=c?.missing||null,o}let g=new Error(`Sub-graph '${t}' trigger rejected (${h.status}): ${f}`);throw g.code="SUBGRAPH_TRIGGER_FAILED",g.status=h.status,g.subgraph=t,g}let w=await h.json(),d=w?.data?.jobId||w?.jobId;if(!d)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(w).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:t};let E=Number.isFinite(e.timeoutMs)?e.timeoutMs:nt,y=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:et,b=`${r}/executions/${encodeURIComponent(d)}`,m=Date.now()+E,u="accepted",T=0;for(;Date.now()<m;){await new Promise(o=>setTimeout(o,y)),T+=1;let c=await fetch(b,{headers:{Authorization:`Bearer ${n}`}});if(!c.ok){if(c.status>=500){I.warn(`[sub-graph] status poll for ${d} returned ${c.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${c.status}`)}let f=await c.json(),g=f?.data||f?.execution||f;if(u=g?.status||u,rt.has(u)){if(u!=="completed"){let R=new Error(`Sub-graph '${t}' (${d}) ended in status '${u}'`);throw R.subgraphJobId=d,R.subgraphStatus=u,R}let o=g?.finalState||g?.state||{},S=J(o,e.output);return I.info(`[sub-graph] '${t}' (${d}) completed after ${T} polls`),S}}let A=new Error(`Sub-graph '${t}' (${d}) timed out after ${Math.round(E/1e3)}s (last status: ${u})`);throw A.subgraphJobId=d,A.subgraphStatus=u,A}export{mt as dispatchSubgraph};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Synchronously check whether `name` is in-process executable.
|
|
3
|
+
*
|
|
4
|
+
* Returns false for entries that are mid-fetch — callers should treat
|
|
5
|
+
* that as "not ready, fall back to HTTP this time" rather than waiting
|
|
6
|
+
* (waiting defeats the purpose: HTTP dispatch is the same latency).
|
|
7
|
+
*/
|
|
8
|
+
export function has(name: any): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Register a child workflow as available in-process. Idempotent — a
|
|
11
|
+
* second call with the same name replaces the factory (intentional: a
|
|
12
|
+
* lazy load can supersede a stale eager-prefetched entry if the
|
|
13
|
+
* versions differ).
|
|
14
|
+
*
|
|
15
|
+
* @param {string} name — workflow name as written in `{ workflow: name }`
|
|
16
|
+
* @param {() => Promise<{ graph, AgentClass }>} factory
|
|
17
|
+
* Async factory that returns a fresh graph instance per call. Each
|
|
18
|
+
* sub-graph invocation gets its own graph so state is not shared.
|
|
19
|
+
* @param {object} [meta] — bookkeeping written for diagnostics
|
|
20
|
+
*/
|
|
21
|
+
export function register(name: string, factory: () => Promise<{
|
|
22
|
+
graph: any;
|
|
23
|
+
AgentClass: any;
|
|
24
|
+
}>, meta?: object): void;
|
|
25
|
+
/**
|
|
26
|
+
* Mark a child as currently being fetched. Lets concurrent first-call
|
|
27
|
+
* dispatches for the same name observe "in flight" and either wait or
|
|
28
|
+
* fall back. We choose **fall back**: blocking on an inflight fetch
|
|
29
|
+
* has the same latency budget as the HTTP path; defer to a future PR
|
|
30
|
+
* if we want to dedupe waiters.
|
|
31
|
+
*/
|
|
32
|
+
export function markLoading(name: any): void;
|
|
33
|
+
export function markFailed(name: any, err: any): void;
|
|
34
|
+
/**
|
|
35
|
+
* Get the factory for `name`, or null if not ready. Returns the factory
|
|
36
|
+
* itself; callers invoke it to materialize a fresh graph.
|
|
37
|
+
*/
|
|
38
|
+
export function get(name: any): any;
|
|
39
|
+
export function getState(name: any): any;
|
|
40
|
+
export function getMeta(name: any): any;
|
|
41
|
+
/** Diagnostics: snapshot the current registry state. */
|
|
42
|
+
export function list(): {
|
|
43
|
+
name: any;
|
|
44
|
+
state: any;
|
|
45
|
+
meta: any;
|
|
46
|
+
}[];
|
|
47
|
+
/** Reset — only for tests. Don't call in production. */
|
|
48
|
+
export function _reset(): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o=new Map,e=new Map,n=new Map;function i(t){return e.get(t)==="ready"}function a(t,r,s={}){if(!t||typeof t!="string")throw new Error("subgraph-registry.register: name required");if(typeof r!="function")throw new Error("subgraph-registry.register: factory must be a function");o.set(t,r),e.set(t,"ready"),n.set(t,{...s,cachedAt:Date.now()})}function u(t){e.has(t)||e.set(t,"loading")}function c(t,r){e.set(t,"failed"),n.set(t,{error:r?.message||String(r),failedAt:Date.now()}),o.delete(t)}function f(t){return e.get(t)==="ready"?o.get(t):null}function g(t){return e.get(t)||"absent"}function p(t){return n.get(t)||null}function l(){let t=[];for(let[r,s]of e.entries())t.push({name:r,state:s,meta:n.get(r)||null});return t}function d(){o.clear(),e.clear(),n.clear()}export{d as _reset,f as get,p as getMeta,g as getState,i as has,l as list,c as markFailed,u as markLoading,a as register};
|