@zibby/agent-workflow 0.4.39 → 0.6.0
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 -1
- package/dist/agents/base.d.ts +10 -19
- package/dist/agents/base.js +1 -1
- package/dist/code-generator.d.ts +2 -2
- package/dist/code-generator.js +12 -12
- package/dist/compose-knowledge.d.ts +1 -1
- package/dist/constants.d.ts +9 -9
- package/dist/context-loader.d.ts +2 -2
- package/dist/context-loader.js +2 -2
- package/dist/exec-context.d.ts +28 -14
- package/dist/graph-compiler.d.ts +6 -6
- package/dist/graph-compiler.js +16 -16
- package/dist/graph.d.ts +46 -63
- package/dist/graph.js +16 -16
- package/dist/in-process-subgraph.d.ts +58 -25
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.d.ts +45 -18
- package/dist/index.js +27 -27
- package/dist/logger.d.ts +13 -12
- package/dist/logger.js +1 -1
- package/dist/node-registry.d.ts +5 -5
- package/dist/node-registry.js +8 -8
- package/dist/node.d.ts +14 -12
- package/dist/node.js +11 -11
- package/dist/output-parser.d.ts +3 -27
- package/dist/output-parser.js +2 -2
- package/dist/skill-registry.d.ts +7 -21
- package/dist/state.d.ts +8 -4
- package/dist/state.js +1 -1
- package/dist/stores.d.ts +8 -11
- package/dist/strategy-registry.d.ts +18 -12
- package/dist/strategy-registry.js +8 -8
- package/dist/sub-graph-executor.d.ts +36 -8
- package/dist/sub-graph-executor.js +1 -1
- package/dist/subgraph-registry.d.ts +37 -16
- package/dist/timeline.d.ts +35 -20
- package/dist/timeline.js +8 -8
- package/dist/tool-resolver.d.ts +8 -15
- package/dist/tool-resolver.js +1 -1
- package/package.json +5 -3
package/dist/index.js
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
1
|
-
var uo=Object.defineProperty;var Ie=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ge=(o,e)=>()=>(o&&(e=o(o=0)),e);var
|
|
1
|
+
var uo=Object.defineProperty;var Ie=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ge=(o,e,t)=>()=>{if(t)throw t[0];try{return o&&(e=o(o=0)),e}catch(n){throw t=[n],n}};var rt=(o,e)=>{for(var t in e)uo(o,t,{get:e[t],enumerable:!0})};function ho(o){ne.impl={...it,...o}}var st,it,ne,E,W=ge(()=>{st=()=>{},it={debug:st,info:st,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ne={impl:it};E={debug:(...o)=>ne.impl.debug?.(...o),info:(...o)=>ne.impl.info?.(...o),warn:(...o)=>ne.impl.warn?.(...o),error:(...o)=>ne.impl.error?.(...o)}});var Ne,Oe=ge(()=>{Ne=class{constructor(e,t,n=0){this.name=e,this.description=t,this.priority=n}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 bt={};rt(bt,{clearSkills:()=>_t,getAllSkills:()=>wt,getSkill:()=>q,getSkillSource:()=>yt,hasSkill:()=>mt,listSkillIds:()=>St,registerSkill:()=>gt});function gt(o,e={}){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");let{source:t,override:n=!1}=e,i=o.id;if(G.has(i)&&!n){let s=ie.get(i);if(!(s===t)){let a=s||"first-party",l=t||"first-party";throw new Error(`Skill id collision: "${i}" 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).`)}}G.set(i,Object.freeze({...o})),t===void 0?ie.delete(i):ie.set(i,t)}function q(o){return G.get(o)||null}function mt(o){return G.has(o)}function yt(o){return ie.get(o)||null}function wt(){return new Map(G)}function St(){return Array.from(G.keys())}function _t(){G.clear(),ie.clear()}var Pe,Ce,G,ie,ae=ge(()=>{Pe=Symbol.for("@zibby/agent-workflow.skills"),Ce=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[Pe]||(globalThis[Pe]=new Map);globalThis[Ce]||(globalThis[Ce]=new Map);G=globalThis[Pe],ie=globalThis[Ce]});var ce={};rt(ce,{getAgentStrategy:()=>je,invokeAgent:()=>$t,listStrategies:()=>It,registerStrategy:()=>Et,resolveInvocationModel:()=>vt});function Et(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=H.findIndex(t=>t.getName()===o.getName());e>=0?H[e]=o:H.push(o)}function It(){return H.map(o=>o.getName())}function vt({config:o={},options:e={},strategyName:t,envModel:n}={}){let i=o.models||{},s=e.nodeName&&i[e.nodeName]||null,r=i.default||null,a=o.agent?.[t]?.model||null,l=(typeof n=="string"?n.trim():"")||null;return s||r||a||e.model||l||null}function je(o={}){let{state:e={},preferredAgent:t=null}=o,n=t||e.agentType||process.env.AGENT_TYPE;if(!n){let s=H.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}E.debug(`[workflow] agent selection: requested=${n}`);let i=H.find(s=>s.getName()===n);if(!i){let s=H.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${s}`)}if(!i.canHandle(o))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return E.debug(`[workflow] using agent: ${i.getName()}`),i}async function $t(o,e={},t={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:n},s=je(i),r=n.config||t.config||{},a=vt({config:r,options:t,strategyName:s.name,envModel:process.env.MODEL}),l={...t,model:a,workspace:n.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],extraMcpServers:t.extraMcpServers||n.extraMcpServers||e.extraMcpServers||[],plugins:t.plugins||e.plugins||[],config:r},u=o,f=l.skills||[];if(f.length>0&&!t.skipPromptFragments){let y=f.map(h=>{let g=q(h)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);y.length>0&&(u+=`
|
|
2
2
|
|
|
3
3
|
${y.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let d=
|
|
5
|
+
`)}`)}let d=n._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let y=d.length<=8,h=d.map(g=>{let I=g?.id??g?.storeId??"",_=(g?.name??"").toString().trim()||I,m=g?.type?` \xB7 ${g.type}`:"",w=(g?.description||"").toString().replace(/\s+/g," ").trim(),S=`- ${_} \xB7 ${w||"(no description)"}${m} (id: ${I})`;if(y&&g?.schema&&typeof g.schema=="object"){let p=g.schema.properties&&typeof g.schema.properties=="object"?Object.keys(g.schema.properties):Object.keys(g.schema);p.length&&(S+=`
|
|
6
6
|
fields: ${p.join(", ")}`)}return S});u+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${h.join(`
|
|
10
|
-
`)}`}let c=
|
|
10
|
+
`)}`}let c=n._currentNodeConfig?.extraPromptInstructions?.trim();return c&&(u+=`
|
|
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
16
|
${c}
|
|
17
|
-
`),E.debug(`[workflow] prompt length: ${u.length} chars`),s.invoke(u,l)}var Re,H,X=ge(()=>{Oe();
|
|
17
|
+
`),E.debug(`[workflow] prompt length: ${u.length} chars`),s.invoke(u,l)}var Re,H,X=ge(()=>{Oe();W();ae();Re=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Re]||(globalThis[Re]=[]);H=globalThis[Re]});var po=new Set(["__proto__","constructor","prototype"]);function ve(o){if(po.has(o))throw new Error(`Invalid state key: "${o}"`)}var te=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){ve(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let n of t)ve(n);this._history.push({...this._state});for(let n of t)this._state[n]=e[n]}append(e,t){ve(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 J from"handlebars";var oe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(i=>i[0]);for(let i of n)try{return this.validate(JSON.parse(i))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[n,i]of Object.entries(this.schema)){if(i.required&&!(n in e)&&t.push(`Missing required field: ${n}`),n in e&&i.type){let s=typeof e[n];s!==i.type&&t.push(`Field '${n}' expected ${i.type}, got ${s}`)}if(i.validate&&n in e){let s=i.validate(e[n]);s&&t.push(`Field '${n}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}},fo={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};
|
|
20
|
-
`?(
|
|
21
|
-
${dt}`,e.col=ut))}return o(n,
|
|
19
|
+
`)}`);return e}},fo={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};W();import{writeFileSync as Be,readFileSync as Tt,existsSync as kt,mkdirSync as _o}from"node:fs";import{join as Me,dirname as bo}from"node:path";import N from"chalk";var ht="__WORKFLOW_GRAPH_LOG__",re=N.gray("\u2502"),go=N.gray("\u250C"),at=N.gray("\u2514"),$e=N.green("\u25C6"),ct=N.hex("#c084fc")("\u25C6"),lt=N.hex("#2dd4bf")("\u25C6"),Te=N.red("\u25C6"),dt=`${re} `,ut=2;function pt(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function ft(o,e){return(t,n,i)=>{if(typeof t!="string")return o(t,n,i);let s=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(r+=dt,e.col=ut,e.lineStart=!1),l===`
|
|
20
|
+
`?(r+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,r+=l):e.inEsc?(r+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,r+=l,e.col>=s&&(r+=`
|
|
21
|
+
${dt}`,e.col=ut))}return o(r,n,i)}}var me=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=ft(this._origStdoutWrite,e),process.stderr.write=ft(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
24
|
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${ht}${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($e,e):process.stdout.write.bind(process.stdout)(`${
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Te,N.red(e)):process.stdout.write.bind(process.stdout)(`${
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot($e,e):process.stdout.write.bind(process.stdout)(`${re} ${$e} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(ct,e):process.stdout.write.bind(process.stdout)(`${re} ${ct} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=N.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(lt,t):process.stdout.write.bind(process.stdout)(`${re} ${lt} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Te,N.red(e)):process.stdout.write.bind(process.stdout)(`${re} ${Te} ${N.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${go} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:n,details:i}=t;if(i)for(let r of i)this._rawWrite(`${$e} ${r}`);let s=n?N.dim(` ${pt(n)}`):"";this._rawWrite(`${at} ${N.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,n={}){this._stopIntercepting();let{duration:i}=n,s=i?N.dim(` ${pt(i)}`):"";this._rawWrite(`${Te} ${N.red(t)}`),this._rawWrite(`${at} ${N.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(N.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new me;var se=".zibby/output",ke="sessions",U=".session-info.json",Ae=".zibby-stop",mo="result.json",yo="raw_stream_output.txt",wo="events.json",So=Object.freeze(["codebase-memory","code-scan","artifact"]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];J.helpers.inc||J.registerHelper("inc",o=>Number(o)+1);J.helpers.json||J.registerHelper("json",o=>JSON.stringify(o,null,2));J.helpers.eq||J.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new oe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return E.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let n=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){E.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(E.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return E.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&E.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=J.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(n())):s=this.prompt;let r=i("_skillHints");r&&(s=`${r}
|
|
33
33
|
|
|
34
|
-
${s}`);let a=r(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Me(u,W);if(kt(d)){let y=JSON.parse(Tt(d,"utf-8"));y.currentNode=this.name,Be(d,JSON.stringify(y,null,2),"utf-8")}let c=Me(u,"..",W);if(kt(c))try{let y=JSON.parse(Tt(c,"utf-8"));y.currentNode=this.name,Be(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(d){E.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{E.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=r().config||{},y=c.agents||{},h=this.config.agent??y[this.name]??null,g={state:r()};h&&(g.preferredAgent=h);let I={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let m=await _(s,g,I),w,S;if(typeof m=="string"?(w=m,S=null):m.structured?(w=m.raw||JSON.stringify(m.structured,null,2),S=m.structured):(w=m.raw||JSON.stringify(m,null,2),S=m.extracted||null),u)try{let p=Me(u,this.name,"raw_stream_output.txt");_o(bo(p),{recursive:!0}),Be(p,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),S)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:w}),raw:w}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(w);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:w}}return{success:!0,output:w,raw:w}}catch(c){f=c,d<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as vo,existsSync as Y,statSync as Bt,readdirSync as Mt,rmSync as $o}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as To}from"node:url";import{AsyncLocalStorage as ko}from"node:async_hooks";import{AsyncLocalStorage as Eo}from"node:async_hooks";var De=new Eo;function le(){let o=De.getStore();return o||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 At(o,e){let t=De.getStore()||le(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return De.run(r,e)}var Le=new Map,Fe=new Map,xt=new Map;function Nt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(o,e),Fe.set(o,"ready"),xt.set(o,{...t,cachedAt:Date.now()})}function Ot(o,e){Fe.set(o,"failed"),xt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(o)}function Pt(o){return Fe.get(o)==="ready"?Le.get(o):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ao(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=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"}},Rt=new ko,jt=Promise.resolve();async function xo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=Rt.getStore()===!0,i=null;if(!r){let n=jt;jt=new Promise(a=>{i=a}),await n}let s=new Map;try{for(let[n,a]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[n,a]of s)a===void 0?delete process.env[n]:process.env[n]=a;i&&i()}}function No(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!r||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:i}}async function Oo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await r.json()}catch{}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=i?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${r.status}`)}return i?.data||i}async function z({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||E.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){E.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function Po(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(Y(t)&&Y(r))return;vo(e,{recursive:!0});let i=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),l=n(i,"wx");a(l),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=Ct("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,y,h=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};f.on("close",g=>{c=g,h()}),d.on("close",g=>{y=g,h()}),f.on("error",u),d.on("error",u)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(i)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",n.message)}}async function Co(o){let e=U(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(To(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let r=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function Dt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),r;try{r=No()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await Oo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=i,y=Ao();if(n&&n!==y)throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${n}`);if(!d||!a)throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let h=Pt(o);if(!h){let p=U(ye,`${f}@${u||"0"}`);try{await Po(a,p);try{jo()}catch{}}catch($){throw $.fallback&&await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await Co(p),Nt(o,h,{workflowUuid:f,version:u,runtimeTag:n,cacheDir:p})}catch($){throw Ot(o,$),await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let g=Date.now(),I=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},w,S;try{w=await xo(I,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return At({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),S=w&&typeof w=="object"&&"state"in w?w.state:w}catch(p){throw await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-g}}),p}if(w&&typeof w=="object"&&w.stoppedExternally){await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:S,durationMs:Date.now()-g}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await z({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:S,durationMs:Date.now()-g}}),{finalState:S,executionId:s}}function Ro(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),i;try{i=Bt(r)}catch{continue}if(i.isDirectory()){let s;try{s=Mt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=i.size}return e}function jo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Mt(ye),t=[],r=0;for(let a of e){let l=U(ye,a),u;try{u=Bt(l)}catch{continue}let f=u.isDirectory()?Ro(l):u.size;r+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,n=0;for(let a of t){if(r-s<=i)break;if(!Y(U(a.full,".lock")))try{$o(a.full,{recursive:!0,force:!0}),s+=a.size,n+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return n>0&&E.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bo=2e3,Mo=600*1e3,Do=new Set(["completed","failed","canceled","timeout"]);function Lo(){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 Fo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Uo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Wo(){return process.env.EXECUTION_ID||null}function Lt(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 Ue(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await Dt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Lt(S,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof O||S?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let i=Lo(),s=Fo(),n=Uo(),a=Wo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(u)});if(!f.ok){let S=null,p="";try{S=await f.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=S?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=S?.validationErrors||null,k.missing=S?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:Mo,h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bo,g=`${i}/executions/${encodeURIComponent(c)}`,I=Date.now()+y,_="accepted",m=0;for(;Date.now()<I;){await new Promise(k=>setTimeout(k,h)),m+=1;let S=await fetch(g,{headers:{Authorization:`Bearer ${n}`}});if(!S.ok){if(S.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Do.has(_)){if(_!=="completed"){let b=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw b.subgraphJobId=c,b.subgraphStatus=_,b}let k=$?.finalState||$?.state||{},M=Lt(k,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),M}}let w=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${_})`);throw w.subgraphJobId=c,w.subgraphStatus=_,w}import{existsSync as Ft,readFileSync as Go}from"node:fs";import{join as We,dirname as Ut}from"node:path";var de=class{static async loadContext(e,t,r={}){let i={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ut(We(t,e));for(let l of s){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=u}}}let n=r.discovery||{};for(let[a,l]of Object.entries(n))try{let u=We(t,l);Ft(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,t,r){let i=[],s=t;for(;s.startsWith(r);){let n=We(s,e);if(Ft(n))try{i.unshift(await this.loadFile(n))}catch(l){console.warn(`[workflow] could not load ${e} from ${n}: ${l.message}`)}let a=Ut(s);if(a===s)break;s=a}return i.length===0?null:i.every(n=>typeof n=="string")?i.join(`
|
|
34
|
+
${s}`);let a=n(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Me(u,U);if(kt(d)){let y=JSON.parse(Tt(d,"utf-8"));y.currentNode=this.name,Be(d,JSON.stringify(y,null,2),"utf-8")}let c=Me(u,"..",U);if(kt(c))try{let y=JSON.parse(Tt(c,"utf-8"));y.currentNode=this.name,Be(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(d){E.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{E.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=n().config||{},y=c.agents||{},h=this.config.agent??y[this.name]??null,g={state:n()};h&&(g.preferredAgent=h);let I={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let m=await _(s,g,I),w,S;if(typeof m=="string"?(w=m,S=null):m.structured?(w=m.raw||JSON.stringify(m.structured,null,2),S=m.structured):(w=m.raw||JSON.stringify(m,null,2),S=m.extracted||null),u)try{let p=Me(u,this.name,"raw_stream_output.txt");_o(bo(p),{recursive:!0}),Be(p,typeof w=="string"?w:JSON.stringify(w),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&S){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let p=S;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),S)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:w}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:w}),raw:w}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(w);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:w}}return{success:!0,output:w,raw:w}}catch(c){f=c,d<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};W();W();import{mkdirSync as vo,existsSync as Y,statSync as Bt,readdirSync as Mt,rmSync as $o}from"node:fs";import{spawn as Ct}from"node:child_process";import{join as F}from"node:path";import{pathToFileURL as To}from"node:url";import{AsyncLocalStorage as ko}from"node:async_hooks";import{AsyncLocalStorage as Eo}from"node:async_hooks";var De=new Eo;function le(){let o=De.getStore();return o||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 At(o,e){let t=De.getStore()||le(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return De.run(n,e)}var Le=new Map,We=new Map,xt=new Map;function Nt(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(o,e),We.set(o,"ready"),xt.set(o,{...t,cachedAt:Date.now()})}function Ot(o,e){We.set(o,"failed"),xt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(o)}function Pt(o){return We.get(o)==="ready"?Le.get(o):null}var ye=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function Ao(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=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"}},Rt=new ko,jt=Promise.resolve();async function xo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Rt.getStore()===!0,i=null;if(!n){let r=jt;jt=new Promise(a=>{i=a}),await r}let s=new Map;try{for(let[r,a]of t)s.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Rt.run(!0,e)}finally{for(let[r,a]of s)a===void 0?delete process.env[r]:process.env[r]=a;i&&i()}}function No(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!n||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:i}}async function Oo({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=i?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=s,r}if(n.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function z({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Po(o,e){let t=F(e,".ready"),n=F(e,"graph.mjs");if(Y(t)&&Y(n))return;vo(e,{recursive:!0});let i=F(e,".lock"),s=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(i,"wx");a(l),s=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!s){let r=Date.now()+3e4;for(;Date.now()<r;){if(Y(t)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=Ct("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=Ct("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,y,h=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};f.on("close",g=>{c=g,h()}),d.on("close",g=>{y=g,h()}),f.on("error",u),d.on("error",u)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(i)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",r.message)}}async function Co(o){let e=F(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(To(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function Dt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=le(),n;try{n=No()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await Oo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=i,y=Ao();if(r&&r!==y)throw await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${r}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${r}`);if(!d||!a)throw await z({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 O("no-bundle","workflow bundle not built yet");let h=Pt(o);if(!h){let p=F(ye,`${f}@${u||"0"}`);try{await Po(a,p);try{jo()}catch{}}catch($){throw $.fallback&&await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{h=await Co(p),Nt(o,h,{workflowUuid:f,version:u,runtimeTag:r,cacheDir:p})}catch($){throw Ot(o,$),await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let g=Date.now(),I=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},w,S;try{w=await xo(I,async()=>{let $=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph();return At({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),S=w&&typeof w=="object"&&"state"in w?w.state:w}catch(p){throw await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-g}}),p}if(w&&typeof w=="object"&&w.stoppedExternally){await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:S,durationMs:Date.now()-g}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await z({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:S,durationMs:Date.now()-g}}),{finalState:S,executionId:s}}function Ro(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),i;try{i=Bt(n)}catch{continue}if(i.isDirectory()){let s;try{s=Mt(n)}catch{continue}for(let r of s)t.push(F(n,r))}else e+=i.size}return e}function jo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(ye))return{evicted:0,freedBytes:0};let e=Mt(ye),t=[],n=0;for(let a of e){let l=F(ye,a),u;try{u=Bt(l)}catch{continue}let f=u.isDirectory()?Ro(l):u.size;n+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,r=0;for(let a of t){if(n-s<=i)break;if(!Y(F(a.full,".lock")))try{$o(a.full,{recursive:!0,force:!0}),s+=a.size,r+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&E.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:s,totalBytes:n-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Bo=2e3,Mo=600*1e3,Do=new Set(["completed","failed","canceled","timeout"]);function Lo(){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 Wo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Fo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Uo(){return process.env.EXECUTION_ID||null}function Lt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,n)=>t==null?t:t[n],o):o}async function Fe(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=le(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:S}=await Dt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Lt(S,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(S){if(S instanceof O||S?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${S.reason||"unknown"} \u2014 using HTTP`);else throw S}let i=Lo(),s=Wo(),r=Fo(),a=Uo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(u)});if(!f.ok){let S=null,p="";try{S=await f.json(),p=S?.error||S?.message||JSON.stringify(S)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=S?.quotaInfo||{},M=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw M.code="SUBGRAPH_QUOTA_EXCEEDED",M.status=429,M.subgraph=o,M.quotaInfo=k,M}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=S?.validationErrors||null,k.missing=S?.missing||null,k}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:Mo,h=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Bo,g=`${i}/executions/${encodeURIComponent(c)}`,I=Date.now()+y,_="accepted",m=0;for(;Date.now()<I;){await new Promise(k=>setTimeout(k,h)),m+=1;let S=await fetch(g,{headers:{Authorization:`Bearer ${r}`}});if(!S.ok){if(S.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${S.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${S.status}`)}let p=await S.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Do.has(_)){if(_!=="completed"){let b=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw b.subgraphJobId=c,b.subgraphStatus=_,b}let k=$?.finalState||$?.state||{},M=Lt(k,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),M}}let w=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${_})`);throw w.subgraphJobId=c,w.subgraphStatus=_,w}import{existsSync as Wt,readFileSync as Go}from"node:fs";import{join as Ue,dirname as Ft}from"node:path";var de=class{static async loadContext(e,t,n={}){let i={},s=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Ft(Ue(t,e));for(let l of s){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=u}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let u=Ue(t,l);Wt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,t,n){let i=[],s=t;for(;s.startsWith(n);){let r=Ue(s,e);if(Wt(r))try{i.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Ft(s);if(a===s)break;s=a}return i.length===0?null:i.every(r=>typeof r=="string")?i.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):i.every(
|
|
38
|
+
`):i.every(r=>typeof r=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let t=Go(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),i=await import(n(e).href);return i.default||i}return t}};import{mkdirSync as Ht,existsSync as Ge,writeFileSync as Ut,unlinkSync as Ho}from"node:fs";import{join as Z,resolve as Jt}from"node:path";import{config as Jo}from"dotenv";import{zodToJsonSchema as Gt}from"zod-to-json-schema";import{z as we}from"zod";import zo from"handlebars";function Yo({traceFrom:o,sessionId:e,sessionPath:t,idSource:n,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let r=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${r} sessionId=${e} source=${n} mkdir=${i?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let f=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${f}`)}}function zt(){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 Yt(){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 Jt(String(e).trim())}catch{return String(e).trim()}}function Zt(){zt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Vt({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Kt(o={}){let e=xe.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${r}`:r}function qt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Jt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,n="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,n="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,n="config.sessionId"):(a=Kt(e),n="generated")}s=s??Date.now();let f=e.paths?.output||se;i=Z(o,f,ke,a)}let l=!Ge(i);return l&&Ht(i,{recursive:!0}),(l||n!=="initialState.sessionPath")&&Yo({traceFrom:r,sessionId:a,sessionPath:i,idSource:n,mkdirFresh:l}),Vt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=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 L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async u=>{let f=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof n.input=="function"?d=n.input(f):n.input&&typeof n.input=="object"?d=n.input:d={},Ue(n.workflow,{input:d,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(f):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:f?._signal,parentAgent:u?.agent})}},l=new L(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 i=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),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){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return 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}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,i,s){let n=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=n;n=()=>l(t,u,i,s)}return n()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let y=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:y,data:{nodeType:y,label:d}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let g=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;g&&(h.description=g);let I=this.nodePrompts.get(d);if(I)h.prompt=I;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(h.prompt=p,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(h.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Gt(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[d];_?.toolIds&&(h.tools=_.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(h.skills=[...m]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(h.plugins=w.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(h.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(h).length>0&&(t[d]=h)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(d)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),g=c.labels||{},I=this.nodes.get(d),_=I?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!I,m=d;if(!_){let w=`${d}__branch`;e.push({id:w,type:"decision",data:{nodeType:"decision",label:w}}),r.push({source:d,target:w}),m=w}for(let w of h){let S={source:m,target:w,data:{conditionalCode:y}};g[w]&&(S.label=g[w]),r.push(S)}}let i=d=>{if(!d)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(d)}catch{}try{return Gt(d,{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 s=0;for(let d of r)if(d.target==="END"){s+=1;let c=`END__${s}`;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)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let n=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=i(a||this.stateSchema),u=i(this.inputSchema),f=i(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:f}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),i=new Map(e.map(d=>[d.id,d])),s=new Map(e.map(d=>[d.id,0])),n=new Map(e.map(d=>[d.id,[]]));for(let d of t)n.has(d.source)&&s.has(d.target)&&(n.get(d.source).push(d.target),s.set(d.target,s.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>s.get(d)===0),f=[];for(;f.length<e.length;){let d;if(u.length>0){if(u.sort((c,y)=>r.get(c)-r.get(y)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,y)=>r.get(c)-r.get(y))[0];a.add(d),l.delete(d),f.push(i.get(d));for(let c of n.get(d)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&u.push(c)}return f}_inferConditionalTargets(e,t){let r=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let u=n[2]!==void 0?n[2]:n[3];u!==void 0&&u!==""&&i.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 i)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=u.exec(r))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");r=e.definitions[i]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],i=e.properties||{},s=e.required||[];for(let[n,a]of Object.entries(i)){let l=t?`${t}.${n}`:n;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!s.includes(n)}),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[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${i}: ${s}`);else if(Array.isArray(s)){let n=s.length,a=s.filter(u=>u?.passed===!0).length,l=s.some(u=>u?.passed!==void 0);r.push(l?`${i}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${i}: ${n} 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");let i=new AbortController;r.signal&&(r.signal.aborted?i.abort():r.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();Jo({path:Z(n,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let v=Z(n,".zibby.config.js");Ge(v)&&(a=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let v=a?.agent;v?.provider?l=v.provider:v?.gemini?l="gemini":v?.claude?l="claude":v?.cursor?l="cursor":v?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let v=f.safeParse(t);if(!v.success){let P=v.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let d=Yt(),c=t.sessionPath||d;c||Zt();let{sessionPath:y,sessionTimestamp:h,sessionId:g}=qt({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${g}`);let I=await de.loadContext(t.specPath||"",n,u);Object.keys(I).length>0&&x.step(`Context loaded: ${Object.keys(I).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:y,sessionTimestamp:h,context:I,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),w=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ae(),bt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(v=>v&&typeof v=="object"&&typeof v.id=="string"),k=v=>{for(let P of $)if(P.id===v)return P;return S(v)},M=new Set;for(let[,v]of this.nodes)for(let P of v.config?.skills||[])M.add(P);for(let v of M){let P=k(v);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&w.set(v,C)}catch{}}let b=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,to=0;try{for(;b&&b!=="END";){if(++to>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Z(y,Ae);if(Ge(P)){try{Ho(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:pe,stoppedExternally:!0};let C=this.nodes.get(b);if(!C)throw new Error(`Node '${b}' not found in graph`);let qe=JSON.stringify({sessionPath:y,sessionTimestamp:h,currentNode:b,createdAt:new Date().toISOString(),config:m.get("config")}),oo=Z(y,
|
|
43
|
-
${f}`),a.includes(".")||
|
|
41
|
+
${f}`)}}function zt(){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 Yt(){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 Jt(String(e).trim())}catch{return String(e).trim()}}function Zt(){zt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Vt({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Kt(o={}){let e=xe.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${n}`:n}function qt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,r="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Jt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,r="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=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=Kt(e),r="generated")}s=s??Date.now();let f=e.paths?.output||se;i=Z(o,f,ke,a)}let l=!Ge(i);return l&&Ht(i,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Yo({traceFrom:n,sessionId:a,sessionPath:i,idSource:r,mkdirFresh:l}),Vt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async u=>{let f=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof r.input=="function"?d=r.input(f):r.input&&typeof r.input=="object"?d=r.input:d={},Fe(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:u?.agent})}},l=new L(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,i,s){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],u=r;r=()=>l(t,u,i,s)}return r()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let y=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:y,data:{nodeType:y,label:d}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let g=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;g&&(h.description=g);let I=this.nodePrompts.get(d);if(I)h.prompt=I;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(h.prompt=p,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(h.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof we?.toJSONSchema=="function")try{p=we.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Gt(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[d];_?.toolIds&&(h.tools=_.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(h.skills=[...m]);let w=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;w&&w.length>0&&(h.plugins=w.map(p=>p&&typeof p=="object"?{...p}:p));let S=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;S&&S.length>0&&(h.stores=S.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(h).length>0&&(t[d]=h)}let n=[];for(let[d,c]of this.edges)if(typeof c=="string")n.push({source:d,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(d)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),g=c.labels||{},I=this.nodes.get(d),_=I?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!I,m=d;if(!_){let w=`${d}__branch`;e.push({id:w,type:"decision",data:{nodeType:"decision",label:w}}),n.push({source:d,target:w}),m=w}for(let w of h){let S={source:m,target:w,data:{conditionalCode:y}};g[w]&&(S.label=g[w]),n.push(S)}}let i=d=>{if(!d)return null;if(typeof we?.toJSONSchema=="function")try{return we.toJSONSchema(d)}catch{}try{return Gt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let s=0;for(let d of n)if(d.target==="END"){s+=1;let c=`END__${s}`;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)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=i(a||this.stateSchema),u=i(this.inputSchema),f=i(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:f}}_topoOrderNodes(e,t){let n=new Map(e.map((d,c)=>[d.id,c])),i=new Map(e.map(d=>[d.id,d])),s=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)&&s.has(d.target)&&(r.get(d.source).push(d.target),s.set(d.target,s.get(d.target)+1));let a=new Set,l=new Set(n.keys()),u=[...l].filter(d=>s.get(d)===0),f=[];for(;f.length<e.length;){let d;if(u.length>0){if(u.sort((c,y)=>n.get(c)-n.get(y)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,y)=>n.get(c)-n.get(y))[0];a.add(d),l.delete(d),f.push(i.get(d));for(let c of r.get(d)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&u.push(c)}return f}_inferConditionalTargets(e,t){let n=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=s.exec(n))!==null;){let u=r[2]!==void 0?r[2]:r[3];u!==void 0&&u!==""&&i.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 i)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=u.exec(n))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},s=e.required||[];for(let[r,a]of Object.entries(i)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!s.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)n.push(`${i}: ${s}`);else if(Array.isArray(s)){let r=s.length,a=s.filter(u=>u?.passed===!0).length,l=s.some(u=>u?.passed!==void 0);n.push(l?`${i}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${i}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Jo({path:Z(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let v=Z(r,".zibby.config.js");Ge(v)&&(a=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let v=a?.agent;v?.provider?l=v.provider:v?.gemini?l="gemini":v?.claude?l="claude":v?.cursor?l="cursor":v?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let v=f.safeParse(t);if(!v.success){let P=v.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let d=Yt(),c=t.sessionPath||d;c||Zt();let{sessionPath:y,sessionTimestamp:h,sessionId:g}=qt({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${g}`);let I=await de.loadContext(t.specPath||"",r,u);Object.keys(I).length>0&&x.step(`Context loaded: ${Object.keys(I).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:y,sessionTimestamp:h,context:I,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),w=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:S}=await Promise.resolve().then(()=>(ae(),bt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(v=>v&&typeof v=="object"&&typeof v.id=="string"),k=v=>{for(let P of $)if(P.id===v)return P;return S(v)},M=new Set;for(let[,v]of this.nodes)for(let P of v.config?.skills||[])M.add(P);for(let v of M){let P=k(v);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&w.set(v,C)}catch{}}let b=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,to=0;try{for(;b&&b!=="END";){if(++to>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Z(y,Ae);if(Ge(P)){try{Ho(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:pe,stoppedExternally:!0};let C=this.nodes.get(b);if(!C)throw new Error(`Node '${b}' not found in graph`);let qe=JSON.stringify({sessionPath:y,sessionTimestamp:h,currentNode:b,createdAt:new Date().toISOString(),config:m.get("config")}),oo=Z(y,U);Ut(oo,qe,"utf-8");let Xe=m.get("config")?.paths?.output||se,no=Z(r,Xe,U);Ht(Z(r,Xe),{recursive:!0});try{Ut(no,qe,"utf-8")}catch{}let Qe=t.onPipelineProgress;if(typeof Qe=="function")try{Qe({cwd:r,sessionPath:y,sessionId:g,outputBase:m.get("config")?.paths?.output||se,currentNode:b})}catch{}let ro=(this.resolvedToolsMap||{})[b]||null;m.set("_currentNodeTools",ro);let so=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",so[b]||{}),x.nodeStart(b);let et=Date.now(),fe=this.nodePrompts.get(b);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),ce));this._invokeAgent=A.invokeAgent}let io=this._invokeAgent,Ee={},ao=C.config?.skills||[];for(let A of ao){let R=k(A);if(typeof R?.invokeAgentOptions=="function")try{let T=R.invokeAgentOptions(m.getAll(),{agentType:m.get("agentType"),nodeName:b});T&&typeof T=="object"&&(Ee={...Ee,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let tt=async(A,R,T={})=>{let j=io(A,R,{...Ee,...T,signal:i.signal});return j.catch(()=>{}),i.signal.aborted?j:Promise.race([j,new Promise((V,K)=>{let D=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);ee.name="AbortError",K(ee)},s)};i.signal.addEventListener("abort",D,{once:!0})})])},co=async(A={},R={})=>{let T=R.prompt||"";if(fe){let j=this._compiledPrompts.get(b);j||(j=zo.compile(fe,{noEscape:!0}),this._compiledPrompts.set(b,j));try{T=j(A)}catch(V){throw console.error(`\u274C Template rendering failed for node '${b}':`,V.message),new Error(`Template rendering failed: ${V.message}`,{cause:V})}}else if(!T)throw new Error(`No prompt template configured for node '${b}' and no prompt provided in options`);return tt(T,{state:m.getAll(),images:R.images||[]},{model:R.model||m.get("model"),workspace:m.get("workspace"),schema:R.schema,...R,signal:i.signal})},ot=m.getAll(),lo=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of lo)Object.prototype.hasOwnProperty.call(ot,A)&&console.warn(`[workflow] node "${b}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let nt={...ot,state:m,invokeAgent:co,_coreInvokeAgent:tt,agent:e,nodeId:b,promptTemplate:fe,getPromptTemplate:()=>fe};try{let A=(C.config?.skills||[]).map(D=>w.get(D)).filter(Boolean),R=[...this.middleware,...A],T;R.length>0?T=await this._composeMiddleware(R,b,async()=>C.execute(nt,m),m.getAll(),m):T=await C.execute(nt,m);let j=Date.now()-et;if(pe.push({node:b,success:T.success,duration:j,timestamp:new Date().toISOString()}),!T.success){if(i.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:pe,stoppedExternally:!0};m.append("errors",{node:b,error:T.error});let D=C.config?.retries||0,ee=`${b}_retries`,he=m.getAll()[ee]||0;if(he<D){x.stepInfo(`Retrying (attempt ${he+1}/${D})`),m.update({[ee]:he+1,[`${b}_raw`]:T.raw});continue}throw x.nodeFailed(b,T.error,{duration:j}),new Error(`Node '${b}' failed after ${he} attempts: ${T.error}`)}m.update({[b]:T.output});let V=this._summarizeNodeOutput(b,T.output);x.nodeComplete(b,{duration:j,details:V});let K=this.edges.get(b);if(!K)b="END";else if(K.conditional){let D=K.routes(m.getAll());x.route(b,D),b=D}else b=K}catch(A){throw x.isInsideNode&&x.nodeFailed(b,A.message,{duration:Date.now()-et}),m.set("failed",!0),m.set("failedAt",b),A}}x.graphComplete();let v={success:!0,state:m.getAll(),executionLog:pe};return e&&typeof e.onComplete=="function"&&await e.onComplete(v),v}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(v){console.warn(`[workflow] agent.cleanup() failed: ${v.message}`)}}}};var He=Symbol.for("@zibby/agent-workflow.nodes");globalThis[He]||(globalThis[He]=new Map);var ue=globalThis[He];function Xt(o,e){ue.set(o,e)}function Je(o){return ue.get(o)}function Se(o){return ue.has(o)}function Zo(){return Array.from(ue.keys())}function ze(o){let e=ue.get(o);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}Xt("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let n=t?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",s=Vo(i,t),r=await n(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:r,nodeId:o},raw:typeof r=="string"?r:r.raw}}})});function Vo(o,e){let t=/@([\w.]+)/g,n=new Set,i;for(;(i=t.exec(o))!==null;)n.add(i[1]);if(n.size===0)return o;let s=[],r=new Set;for(let a of n){let l=a.split(".")[0];if(r.has(l))continue;let u=a.split(".").reduce((c,y)=>c?.[y],e);if(u===void 0)continue;let f=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${d}
|
|
43
|
+
${f}`),a.includes(".")||r.add(l)}return s.length===0?o:`${o}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
48
|
${s.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}ae();
|
|
51
|
-
`)}function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
50
|
+
`)}`}ae();W();var _e={};function Ze(o,e){if(Array.isArray(e))return Ye(e);let t=_e[o];return!t||t.length===0?null:Ye(t)}function Ye(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},n=[];for(let i of o){let s=q(i);if(!s){E.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}n.push(i);for(let r of s.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let r=s.resolve();r&&(t[s.serverName]={...r,toolPrefix:i})}else{let r={};for(let a of s.envKeys||[]){let l=process.env[a];l&&(r[a]=l)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:r,toolPrefix:i}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:t}}W();function Ko(o,e={}){let{nodes:t,edges:n,nodeConfigs:i={}}=o;if(!Array.isArray(t)||t.length===0)throw new B("Graph must have at least one node");if(!Array.isArray(n))throw new B("Graph edges must be an array");let s=new Q(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let r=new Set,a=new Map,l={};for(let c of t){let y=be(c);a.set(c.id,{...c,resolvedType:y}),y==="decision"&&r.add(c.id)}for(let[c,y]of a){if(r.has(c))continue;let h=y.resolvedType,g=i[c]||{},I=Ze(h,g.tools);I&&(l[c]=I);let _={};g.prompt&&(_.prompt=g.prompt);let m=Se(h);if(E.debug(`[workflow] compiler: node "${c}" type="${h}" registered=${m}`),g.customCode&&!m)s.addNode(c,Qt(c,g.customCode,g),_),s.setNodeType(c,h);else if(m){let w=Je(h);w.factory?s.addNode(c,w.create(c,{...g,resolvedTools:I}),_):s.addNode(c,w,_),s.setNodeType(c,h)}else if(g.executeCode)s.addNode(c,Qt(c,g.executeCode,g),_),s.setNodeType(c,h);else throw new B(`Unknown node type "${h}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=l;let u=new Set;for(let c of n)r.has(c.target)||u.add(c.target);let f=t.find(c=>!r.has(c.id)&&!u.has(c.id));if(!f)throw new B("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(f.id);let d=Qo(n,"source");for(let c of n)if(!r.has(c.source))if(r.has(c.target)){let y=c.target,h=d.get(y)||[];if(h.length===0)throw new B(`Decision node "${y}" has no outgoing edges`);let g=en(y,h,r);s.addConditionalEdges(c.source,g)}else s.addEdge(c.source,c.target);return s}function qo(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=be(a);if(l==="decision"||Se(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 n=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let i=new Set(o.nodes.filter(a=>be(a)==="decision").map(a=>a.id)),s=new Set;for(let a of o.edges)i.has(a.target)||s.add(a.target);let r=o.nodes.filter(a=>!i.has(a.id)&&!s.has(a.id));r.length===0?e.push("No entry point found (every node has incoming edges)"):r.length>1&&e.push(`Multiple entry points found: ${r.map(a=>a.id).join(", ")}`);for(let a of i){let l=o.edges.filter(f=>f.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Xo(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>be(e)!=="decision").map(e=>e.id)}function be(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Qo(o,e){let t=new Map;for(let n of o){let i=n[e];t.has(i)||t.set(i,[]),t.get(i).push(n)}return t}function en(o,e,t){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new B(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let i=n.data?.conditionalCode||n.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let l=new Function(`return (${i})`)();r=u=>{let f=l(u);return s.has(f)||E.warn(`[workflow] conditional route from "${o}" returned "${f}" which is not in valid targets: ${[...s].join(", ")}`),f}}catch(a){throw new B(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function Qt(o,e,t={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new B(`Failed to compile customCode for node "${o}": ${r.message}`)}let i=n(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),ce));return a(...r)},typeof Ie<"u"?Ie:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async r=>{try{let a=await i(r);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"}};ae();var Ve=/^[a-z][a-z0-9_]{0,40}$/;function tn(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((n,i)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${i}] must be an object { name, description }`);return}let{name:s}=n;if(typeof s!="string"||s.length===0){e.push(`stores[${i}] is missing a string "name"`);return}Ve.test(s)||e.push(`stores[${i}] name "${s}" is invalid \u2014 must match ${Ve} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(s)?e.push(`stores[${i}] duplicate store name "${s}" (also at index ${t.get(s)}) \u2014 store names must be unique within a workflow`):t.set(s,i)}),e}Oe();X();function on(o,e={}){let{nodes:t,edges:n,nodeConfigs:i={}}=o,s=new Set,r=[],a=new Map;for(let I of t){let _=I.data?.nodeType||I.type;a.set(I.id,_),_==="decision"?s.add(I.id):r.push({id:I.id,nodeType:_,label:I.data?.label||I.id})}let l=r.some(I=>{let _=i[I.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=un(r,i),{simpleEdges:d,conditionalEdges:c}=pn(n,s),y=fn(r,n,s),h=[],g=e.workflowType||"workflow";return h.push(rn(e)),h.push(sn(g,{usesRegisteredNodes:l})),h.push(an(f)),h.push(cn(g)),h.push(ln(r,i)),h.push(dn(r,y,d,c,u,g)),h.filter(Boolean).join(`
|
|
51
|
+
`)}function nn(o){let e={};for(let[t,n]of Object.entries(o)){let{tools:i,...s}=n;Object.keys(s).length>0&&(e[t]=s)}return e}function rn(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
|
+
`)}function sn(o,{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 an(o){if(o.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,n]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
|
|
54
|
+
`)}function cn(o){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-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
55
|
+
`)}function ln(o,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 n of o){let i=eo(n.id),s=e[n.id]?.customCode;if(s)t.push(`// @custom \u2014 modified from default "${n.nodeType}" template`),t.push(`const ${i}_execute = ${s};`);else{let r=ze(n.nodeType);r?(t.push(`// Default "${n.nodeType}" implementation`),t.push(`const ${i}_execute = ${r};`)):(t.push(`// No template for "${n.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
56
|
+
`)}function dn(o,e,t,n,i,s){let r=["// \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"];r.push("export function buildGraph(options = {}) {"),r.push(" const graph = new WorkflowGraph(options);",""),r.push(" // Nodes");for(let l of o){let u=eo(l.id);r.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),r.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||n.length>0)&&r.push(" // Edges");for(let l of t)r.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of n){let u=l.code.split(`
|
|
57
57
|
`).map((f,d)=>d===0?f:` ${f}`).join(`
|
|
58
|
-
`);
|
|
59
|
-
`)}function
|
|
58
|
+
`);r.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of o){let u=i.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
|
|
59
|
+
`)}function un(o,e){let t=new Map,n=new Map;for(let i of o){let s=e[i.id]?.tools,r;if(Array.isArray(s)&&s.length>0)r=[...s].sort();else{let a=_e[i.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,a),n.has(a)||n.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:n}}function pn(o,e){let t=[],n=[],i=new Map,s=new Set;for(let r of o)i.has(r.source)||i.set(r.source,[]),i.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(s.has(r.target))continue;s.add(r.target);let l=(i.get(r.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&n.push({source:r.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:n}}function fn(o,e,t){let n=new Set;for(let s of e)t.has(s.target)||n.add(s.target);let i=o.find(s=>!n.has(s.id));return i?i.id:o[0]?.id}function eo(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}W();var hn=`## 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{Ne as AgentStrategy,xe as CI_ENV_VARS,
|
|
128
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Ne as AgentStrategy,xe as CI_ENV_VARS,hn as COMPOSE_KNOWLEDGE,B as CompilationError,de as ContextLoader,se as DEFAULT_OUTPUT_BASE,wo as EVENTS_FILE,Q as Graph,_e as NODE_DEFAULT_TOOLS,So as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,L as Node,oe as OutputParser,yo as RAW_OUTPUT_FILE,mo as RESULT_FILE,ke as SESSIONS_DIR,U as SESSION_INFO_FILE,Ae as STOP_REQUEST_FILE,Ve as STORE_NAME_REGEX,fo as SchemaTypes,me as Timeline,ht as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,Q as WorkflowGraph,te as WorkflowState,Zt as clearInheritedSessionEnvForFreshRun,_t as clearSkills,Ko as compileGraph,Fe as dispatchSubgraph,Xo as extractSteps,nn as generateNodeConfigsJson,on as generateWorkflowCode,Kt as generateWorkflowSessionId,je as getAgentStrategy,wt as getAllSkills,Je as getNodeImpl,ze as getNodeTemplate,Ye as getResolvedToolDefinitions,q as getSkill,yt as getSkillSource,Se as hasNode,mt as hasSkill,$t as invokeAgent,Zo as listNodeTypes,St as listSkillIds,It as listStrategies,Yt as readPinnedSessionPathFromEnv,Xt as registerNode,gt as registerSkill,Et as registerStrategy,Ze as resolveNodeTools,qt as resolveWorkflowSession,ho as setLogger,zt as shouldTrustInheritedSessionEnv,Vt as syncProcessEnvToSession,x as timeline,qo as validateGraphConfig,tn as validateStoreDefs};
|
package/dist/logger.d.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluggable logger interface.
|
|
3
|
+
*
|
|
4
|
+
* The framework is silent by default (debug/info are no-ops).
|
|
5
|
+
* Call setLogger() to route output to your own logger (pino, winston, etc.)
|
|
6
|
+
* or pass { debug, info, warn, error } backed by console.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* import { setLogger } from '@zibby/workflow';
|
|
10
|
+
* setLogger({ debug: () => {}, info: console.log, warn: console.warn, error: console.error });
|
|
11
|
+
*/
|
|
1
12
|
/**
|
|
2
13
|
* Replace the framework logger.
|
|
3
14
|
* @param {{ debug?, info?, warn?, error? }} impl
|
|
4
15
|
*/
|
|
5
|
-
export function setLogger(impl:
|
|
6
|
-
|
|
7
|
-
info?: any;
|
|
8
|
-
warn?: any;
|
|
9
|
-
error?: any;
|
|
10
|
-
}): void;
|
|
11
|
-
export namespace logger {
|
|
12
|
-
function debug(...args: any[]): void;
|
|
13
|
-
function info(...args: any[]): void;
|
|
14
|
-
function warn(...args: any[]): void;
|
|
15
|
-
function error(...args: any[]): void;
|
|
16
|
-
}
|
|
16
|
+
export declare function setLogger(impl: any): void;
|
|
17
|
+
export declare const logger: any;
|
package/dist/logger.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var n=()=>{},e={debug:n,info:n,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},r={impl:e};function l(o){r.impl={...e,...o}}var t={debug:(...o)=>r.impl.debug?.(...o),info:(...o)=>r.impl.info?.(...o),warn:(...o)=>r.impl.warn?.(...o),error:(...o)=>r.impl.error?.(...o)};export{t as logger,l as setLogger};
|
package/dist/node-registry.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export function registerNode(type: any, impl: any): void;
|
|
2
|
-
export function getNodeImpl(type: any): any;
|
|
3
|
-
export function hasNode(type: any): any;
|
|
4
|
-
export function listNodeTypes():
|
|
5
|
-
export function getNodeTemplate(type: any): any;
|
|
1
|
+
export declare function registerNode(type: any, impl: any): void;
|
|
2
|
+
export declare function getNodeImpl(type: any): any;
|
|
3
|
+
export declare function hasNode(type: any): any;
|
|
4
|
+
export declare function listNodeTypes(): unknown[];
|
|
5
|
+
export declare function getNodeTemplate(type: any): any;
|
package/dist/node-registry.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
var G=Object.defineProperty;var
|
|
1
|
+
var G=Object.defineProperty;var h=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var K=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})};var $=h(()=>{});var _,U,w,b,I=h(()=>{_=()=>{},U={debug:_,info:_,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},w={impl:U},b={debug:(...e)=>w.impl.debug?.(...e),info:(...e)=>w.impl.info?.(...e),warn:(...e)=>w.impl.warn?.(...e),error:(...e)=>w.impl.error?.(...e)}});function O(e){return V.get(e)||null}var S,E,V,X,R=h(()=>{S=Symbol.for("@zibby/agent-workflow.skills"),E=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[S]||(globalThis[S]=new Map);globalThis[E]||(globalThis[E]=new Map);V=globalThis[S],X=globalThis[E]});var C={};K(C,{getAgentStrategy:()=>j,invokeAgent:()=>q,listStrategies:()=>H,registerStrategy:()=>D,resolveInvocationModel:()=>M});function D(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=f.findIndex(n=>n.getName()===e.getName());t>=0?f[t]=e:f.push(e)}function H(){return f.map(e=>e.getName())}function M({config:e={},options:t={},strategyName:n,envModel:r}={}){let a=e.models||{},o=t.nodeName&&a[t.nodeName]||null,i=a.default||null,c=e.agent?.[n]?.model||null,g=(typeof r=="string"?r.trim():"")||null;return o||i||c||t.model||g||null}function j(e={}){let{state:t={},preferredAgent:n=null}=e,r=n||t.agentType||process.env.AGENT_TYPE;if(!r){let o=f.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${o}`)}b.debug(`[workflow] agent selection: requested=${r}`);let a=f.find(o=>o.getName()===r);if(!a){let o=f.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${o}`)}if(!a.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return b.debug(`[workflow] using agent: ${a.getName()}`),a}async function q(e,t={},n={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},a={...t,state:r},o=j(a),i=r.config||n.config||{},c=M({config:i,options:n,strategyName:o.name,envModel:process.env.MODEL}),g={...n,model:c,workspace:r.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],extraMcpServers:n.extraMcpServers||r.extraMcpServers||t.extraMcpServers||[],plugins:n.plugins||t.plugins||[],config:i},l=e,y=g.skills||[];if(y.length>0&&!n.skipPromptFragments){let d=y.map(k=>{let s=O(k)?.promptFragment;return typeof s=="function"?s():s}).filter(Boolean);d.length>0&&(l+=`
|
|
2
2
|
|
|
3
3
|
${d.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let u=
|
|
6
|
-
fields: ${A.join(", ")}`)}return
|
|
5
|
+
`)}`)}let u=r._currentNodeConfig?.stores;if(Array.isArray(u)&&u.length>0&&typeof u[0]=="object"){let d=u.length<=8,k=u.map(s=>{let T=s?.id??s?.storeId??"",L=(s?.name??"").toString().trim()||T,Y=s?.type?` \xB7 ${s.type}`:"",z=(s?.description||"").toString().replace(/\s+/g," ").trim(),N=`- ${L} \xB7 ${z||"(no description)"}${Y} (id: ${T})`;if(d&&s?.schema&&typeof s.schema=="object"){let A=s.schema.properties&&typeof s.schema.properties=="object"?Object.keys(s.schema.properties):Object.keys(s.schema);A.length&&(N+=`
|
|
6
|
+
fields: ${A.join(", ")}`)}return N});l+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${k.join(`
|
|
10
|
-
`)}`}let p=
|
|
10
|
+
`)}`}let p=r._currentNodeConfig?.extraPromptInstructions?.trim();return p&&(l+=`
|
|
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
16
|
${p}
|
|
17
|
-
`),b.debug(`[workflow] prompt length: ${
|
|
18
|
-
${
|
|
17
|
+
`),b.debug(`[workflow] prompt length: ${l.length} chars`),o.invoke(l,g)}var v,f,P=h(()=>{$();I();R();v=Symbol.for("@zibby/agent-workflow.strategies");globalThis[v]||(globalThis[v]=[]);f=globalThis[v]});var x=Symbol.for("@zibby/agent-workflow.nodes");globalThis[x]||(globalThis[x]=new Map);var m=globalThis[x];function F(e,t){m.set(e,t)}function oe(e){return m.get(e)}function ie(e){return m.has(e)}function se(){return Array.from(m.keys())}function ae(e){let t=m.get(e);return t?t.factory&&typeof t.create=="function"?t.create.toString():typeof t.execute=="function"?t.execute.toString():typeof t=="function"?t.toString():null:null}F("ai_agent",{name:"ai_agent",factory:!0,create:(e,t={})=>({name:e,_isCustomCode:!0,execute:async n=>{let r=n?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(P(),C))).invokeAgent);let a=t.extraPromptInstructions||"Execute the task based on the current state.",o=B(a,n),i=await r(o,{cwd:n.workspace||process.cwd(),model:n.model,tools:t.resolvedTools||null});return{success:!0,output:{raw:i,nodeId:e},raw:typeof i=="string"?i:i.raw}}})});function B(e,t){let n=/@([\w.]+)/g,r=new Set,a;for(;(a=n.exec(e))!==null;)r.add(a[1]);if(r.size===0)return e;let o=[],i=new Set;for(let c of r){let g=c.split(".")[0];if(i.has(g))continue;let l=c.split(".").reduce((p,d)=>p?.[d],t);if(l===void 0)continue;let y=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),u=c.replace(/_/g," ").replace(/\b\w/g,p=>p.toUpperCase());o.push(`## ${u}
|
|
18
|
+
${y}`),c.includes(".")||i.add(g)}return o.length===0?e:`${e}
|
|
19
19
|
|
|
20
20
|
---
|
|
21
21
|
# Referenced Context
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${o.join(`
|
|
24
24
|
|
|
25
|
-
`)}`}export{
|
|
25
|
+
`)}`}export{oe as getNodeImpl,ae as getNodeTemplate,ie as hasNode,se as listNodeTypes,F as registerNode};
|
package/dist/node.d.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Node — one agent execution step in a workflow graph.
|
|
3
|
+
*/
|
|
4
|
+
export declare class Node {
|
|
5
|
+
_compiledPrompt?: any;
|
|
6
|
+
config?: any;
|
|
7
|
+
customExecute?: any;
|
|
8
|
+
isZodSchema?: any;
|
|
9
|
+
name?: any;
|
|
10
|
+
onComplete?: any;
|
|
11
|
+
outputSchema?: any;
|
|
12
|
+
parser?: any;
|
|
13
|
+
prompt?: any;
|
|
14
|
+
retries?: any;
|
|
2
15
|
constructor(config: any);
|
|
3
|
-
config: any;
|
|
4
|
-
name: any;
|
|
5
|
-
prompt: any;
|
|
6
|
-
outputSchema: any;
|
|
7
|
-
isZodSchema: boolean;
|
|
8
|
-
parser: OutputParser;
|
|
9
|
-
retries: any;
|
|
10
|
-
onComplete: any;
|
|
11
|
-
customExecute: any;
|
|
12
16
|
execute(context: any, state: any): Promise<{
|
|
13
17
|
success: boolean;
|
|
14
18
|
error: any;
|
|
@@ -20,6 +24,4 @@ export class Node {
|
|
|
20
24
|
raw: any;
|
|
21
25
|
error?: undefined;
|
|
22
26
|
}>;
|
|
23
|
-
_compiledPrompt: HandlebarsTemplateDelegate<any>;
|
|
24
27
|
}
|
|
25
|
-
import { OutputParser } from './output-parser.js';
|