@zibby/agent-workflow 2.0.3 → 2.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/code-generator.js +15 -15
- package/dist/fetch-deadline.d.ts +78 -0
- package/dist/fetch-deadline.js +1 -0
- package/dist/graph-compiler.js +24 -24
- package/dist/graph.js +22 -22
- package/dist/in-process-subgraph.d.ts +1 -1
- package/dist/in-process-subgraph.js +1 -1
- package/dist/index.js +33 -33
- package/dist/logger.d.ts +26 -0
- package/dist/logger.js +1 -1
- package/dist/node-registry.js +8 -8
- package/dist/node.d.ts +1 -11
- package/dist/node.js +16 -16
- package/dist/strategy-registry.js +8 -8
- package/dist/sub-graph-executor.d.ts +2 -0
- package/dist/sub-graph-executor.js +1 -1
- package/dist/tool-resolver.js +1 -1
- package/package.json +1 -1
package/dist/node.d.ts
CHANGED
|
@@ -13,15 +13,5 @@ export declare class Node {
|
|
|
13
13
|
prompt?: any;
|
|
14
14
|
retries?: any;
|
|
15
15
|
constructor(config: any);
|
|
16
|
-
execute(context: any, state: any): Promise<
|
|
17
|
-
success: boolean;
|
|
18
|
-
error: any;
|
|
19
|
-
raw: any;
|
|
20
|
-
output?: undefined;
|
|
21
|
-
} | {
|
|
22
|
-
success: boolean;
|
|
23
|
-
output: any;
|
|
24
|
-
raw: any;
|
|
25
|
-
error?: undefined;
|
|
26
|
-
}>;
|
|
16
|
+
execute(context: any, state: any): Promise<any>;
|
|
27
17
|
}
|
package/dist/node.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ut=Object.defineProperty;var W=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(o){throw e=[o],o}};var pt=(r,t)=>{for(var e in t)ut(r,e,{get:t[e],enumerable:!0})};var U,dt,R,x,f,P=W(()=>{U=()=>{},dt={debug:U,info:U,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},R=Symbol.for("@zibby/agent-workflow.logger");globalThis[R]||(globalThis[R]={impl:dt});x=globalThis[R],f={debug:(...r)=>x.impl.debug?.(...r),info:(...r)=>x.impl.info?.(...r),warn:(...r)=>x.impl.warn?.(...r),error:(...r)=>x.impl.error?.(...r)}});var Q=W(()=>{});function tt(r){return mt.get(r)||null}var j,D,mt,At,et=W(()=>{j=Symbol.for("@zibby/agent-workflow.skills"),D=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[j]||(globalThis[j]=new Map);globalThis[D]||(globalThis[D]=new Map);mt=globalThis[j],At=globalThis[D]});var it={};pt(it,{getAgentStrategy:()=>st,invokeAgent:()=>yt,listStrategies:()=>St,registerStrategy:()=>gt,resolveInvocationExtras:()=>ot,resolveInvocationModel:()=>rt});function gt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=O.findIndex(e=>e.getName()===r.getName());t>=0?O[t]=r:O.push(r)}function St(){return O.map(r=>r.getName())}function rt({config:r={},options:t={},strategyName:e,envModel:o,nodeConfigModel:i}={}){let s=r.models||{},c=typeof i=="string"&&i.trim()?i.trim():null,S=t.nodeName&&s[t.nodeName]||null,h=s.default||null,_=r.agent?.[e]?.model||null,I=(typeof o=="string"?o.trim():"")||null;return c||S||h||_||t.model||I||null}function ot({options:r={},stateView:t={},context:e={}}={}){return{workspace:t.workspace||r.workspace,schema:r.schema||e.schema,images:r.images||e.images||[],skills:r.skills||e.skills||[],extraMcpServers:r.extraMcpServers||t.extraMcpServers||e.extraMcpServers||[],plugins:r.plugins||e.plugins||[]}}function st(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let s=O.map(c=>c.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}f.debug(`[workflow] agent selection: requested=${o}`);let i=O.find(s=>s.getName()===o);if(!i){let s=O.map(c=>c.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${s}`)}if(!i.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return f.debug(`[workflow] using agent: ${i.getName()}`),i}async function yt(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},i={...t,state:o},s=st(i),c=o.config||e.config||{},S=o._currentNodeConfig||{},h=typeof S.agent=="string"?S.agent.trim():"",_=!h||h===s.name?S.model:null,I=rt({config:c,options:e,strategyName:s.name,envModel:process.env.MODEL,nodeConfigModel:_}),u={...e,model:I,...ot({options:e,stateView:o,context:t}),config:c},p=r,a=u.skills||[];if(a.length>0&&!e.skipPromptFragments){let $=e.connectedIntegrations;if(!$){let n=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof n=="string"&&n.trim()!==""){$={};for(let g of n.split(",").map(b=>b.trim()).filter(Boolean))$[g]=!0}}let E=n=>{let g=n&&n.requiresIntegration;return!g||!$?!0:(Array.isArray(g)?g:[g]).some(A=>$[A]===!0)},l=s.name==="assistant",d=n=>n?.inProcessOnly!==!0||l,y=a.map(n=>{let g=tt(n);if(!E(g)||!d(g))return null;let b=g?.promptFragment;return typeof b=="function"?b():b}).filter(Boolean);y.length>0&&(p+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${y.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${A.join(", ")}`)}return
|
|
5
|
+
`)}`)}let w=o._currentNodeConfig?.stores;if(Array.isArray(w)&&w.length>0&&typeof w[0]=="object"){let $=w.length<=8,E=w.map(l=>{let d=l?.id??l?.storeId??"",y=(l?.name??"").toString().trim()||d,n=l?.type?` \xB7 ${l.type}`:"",g=(l?.description||"").toString().replace(/\s+/g," ").trim(),b=`- ${y} \xB7 ${g||"(no description)"}${n} (id: ${d})`;if($&&l?.schema&&typeof l.schema=="object"){let A=l.schema.properties&&typeof l.schema.properties=="object"?Object.keys(l.schema.properties):Object.keys(l.schema);A.length&&(b+=`
|
|
6
|
+
fields: ${A.join(", ")}`)}return b});p+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let N=o._currentNodeConfig?.extraPromptInstructions?.trim();return N&&(
|
|
9
|
+
${E.join(`
|
|
10
|
+
`)}`}let N=o._currentNodeConfig?.extraPromptInstructions?.trim();return N&&(p+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
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
|
${N}
|
|
17
|
-
`),
|
|
17
|
+
`),f.debug(`[workflow] prompt length: ${p.length} chars`),s.invoke(p,u)}var G,O,nt=W(()=>{Q();P();et();G=Symbol.for("@zibby/agent-workflow.strategies");globalThis[G]||(globalThis[G]=[]);O=globalThis[G]});import k from"handlebars";var v=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(i=>i[0]);for(let i of o)try{return this.validate(JSON.parse(i))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,i]of Object.entries(this.schema)){if(i.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&i.type){let s=typeof t[o];s!==i.type&&e.push(`Field '${o}' expected ${i.type}, got ${s}`)}if(i.validate&&o in t){let s=i.validate(t[o]);s&&e.push(`Field '${o}': ${s}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};
|
|
20
|
-
`?(c+=
|
|
21
|
-
${
|
|
19
|
+
`)}`);return t}};P();import{writeFileSync as H,readFileSync as at,existsSync as lt,mkdirSync as _t}from"node:fs";import{join as J,dirname as wt}from"node:path";import m from"chalk";var ft="__WORKFLOW_GRAPH_LOG__",T=m.gray("\u2502"),ht=m.gray("\u250C"),K=m.gray("\u2514"),L=m.green("\u25C6"),B=m.hex("#c084fc")("\u25C6"),Y=m.hex("#2dd4bf")("\u25C6"),M=m.red("\u25C6"),Z=`${T} `,z=2;function q(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function V(r,t){return(e,o,i)=>{if(typeof e!="string")return r(e,o,i);let s=process.stdout.columns||120,c="";for(let S=0;S<e.length;S++){let h=e[S];t.lineStart&&(c+=Z,t.col=z,t.lineStart=!1),h===`
|
|
20
|
+
`?(c+=h,t.lineStart=!0,t.col=0,t.inEsc=!1):h==="\x1B"?(t.inEsc=!0,c+=h):t.inEsc?(c+=h,(h>="A"&&h<="Z"||h>="a"&&h<="z")&&(t.inEsc=!1)):(t.col++,c+=h,t.col>=s&&(c+=`
|
|
21
|
+
${Z}`,t.col=z))}return r(c,o,i)}}var C=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=V(this._origStdoutWrite,t),process.stderr.write=V(this._origStderrWrite,e)}_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(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
24
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
24
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${ft}${JSON.stringify(t)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(
|
|
28
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(L,t):process.stdout.write.bind(process.stdout)(`${T} ${L} ${t}
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(B,t):process.stdout.write.bind(process.stdout)(`${T} ${B} ${t}
|
|
30
|
-
`)}stepMemory(t){let e=
|
|
31
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
30
|
+
`)}stepMemory(t){let e=m.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Y,e):process.stdout.write.bind(process.stdout)(`${T} ${Y} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(M,m.red(t)):process.stdout.write.bind(process.stdout)(`${T} ${M} ${m.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${ht} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:i}=e;if(i)for(let c of i)this._rawWrite(`${L} ${c}`);let s=o?m.dim(` ${q(o)}`):"";this._rawWrite(`${K} ${m.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:i}=o,s=i?m.dim(` ${q(i)}`):"";this._rawWrite(`${M} ${m.red(e)}`),this._rawWrite(`${K} ${m.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(m.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},X=new C;var F=".session-info.json";var It=Object.freeze(["codebase-memory","code-scan","artifact"]);k.helpers.inc||k.registerHelper("inc",r=>Number(r)+1);k.helpers.json||k.registerHelper("json",r=>JSON.stringify(r,null,2));k.helpers.eq||k.registerHelper("eq",(r,t)=>r===t);var ct=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode&&!t._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=t.outputSchema&&!this.isZodSchema?new v(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){if(this.config._isRouter)return f.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,i=u=>e&&typeof e.get=="function"?e.get(u):t?.[u];if(typeof this.customExecute=="function"){f.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);let u=null;for(let p=0;p<=this.retries;p++){try{let a=await this.customExecute(t);if(typeof a=="object"&&a!==null&&a.success===!1)u={success:!1,error:a.error||"Node execution failed",raw:a.raw||null};else return this.isZodSchema?(f.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(a),raw:null}):{success:!0,output:a,raw:null}}catch(a){f.error(`[workflow] node '${this.name}' failed: ${a.message}`),a.name==="ZodError"&&f.error(`Schema errors: ${JSON.stringify(a.issues||a.errors,null,2)}`),u={success:!1,error:a.message,raw:null}}p<this.retries&&f.info(`[workflow] node '${this.name}' failed, retrying (${p+1}/${this.retries})\u2026`)}return u}let s;typeof this.prompt=="function"?s=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=k.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(o())):s=this.prompt;let c=i("_skillHints");c&&(s=`${c}
|
|
33
33
|
|
|
34
|
-
${s}`);let
|
|
34
|
+
${s}`);let S=o(),h=S.cwd||process.cwd(),_=S.sessionPath;try{if(_){let u=J(_,F);if(lt(u)){let a=JSON.parse(at(u,"utf-8"));a.currentNode=this.name,H(u,JSON.stringify(a,null,2),"utf-8")}let p=J(_,"..",F);if(lt(p))try{let a=JSON.parse(at(p,"utf-8"));a.currentNode=this.name,H(p,JSON.stringify(a,null,2),"utf-8")}catch{}}}catch(u){f.debug(`[workflow] could not update session info: ${u.message}`)}let I=null;for(let u=0;u<=this.retries;u++)try{f.debug(`[workflow] node '${this.name}' attempt ${u}`);let p=o().config||{},a=p.agents||{},w=this.config.agent??a[this.name]??null,N={state:o()};w&&(N.preferredAgent=w);let $={workspace:h,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],disallowedTools:this.config.disallowedTools||[],plugins:this.config.plugins||[],sessionPath:_,config:p,nodeName:this.name,timeout:this.config?.timeout||3e5},E=t?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(nt(),it))).invokeAgent);let l=await E(s,N,$),d,y;if(typeof l=="string"?(d=l,y=null):l.structured?(d=l.raw||JSON.stringify(l.structured,null,2),y=l.structured):(d=l.raw||JSON.stringify(l,null,2),y=l.extracted||null),_)try{let n=J(_,this.name,"raw_stream_output.txt");_t(wt(n),{recursive:!0}),H(n,typeof d=="string"?d:JSON.stringify(d),"utf-8")}catch(n){f.debug(`[workflow] could not save raw output: ${n.message}`)}if(this.isZodSchema&&y){f.debug(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let n=y;if(typeof this.onComplete=="function")try{n=await this.onComplete(o(),y)}catch(g){f.warn(`[workflow] onComplete hook failed: ${g.message}`)}return{success:!0,output:n,raw:d}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:d}),raw:d}}catch(n){throw new Error(`onComplete failed: ${n.message}`,{cause:n})}if(this.parser){let n=this.parser.parse(d);return f.debug(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(n,null,2)}`),X.step("Output parsed"),{success:!0,output:n,raw:d}}return{success:!0,output:d,raw:d}}catch(p){I=p,u<this.retries&&f.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:I.message,raw:null}}};export{ct as Node};
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=()=>{},P={debug:R,info:R,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},N=Symbol.for("@zibby/agent-workflow.logger");globalThis[N]||(globalThis[N]={impl:P});var k=globalThis[N];var S={debug:(...e)=>k.impl.debug?.(...e),info:(...e)=>k.impl.info?.(...e),warn:(...e)=>k.impl.warn?.(...e),error:(...e)=>k.impl.error?.(...e)};var A=Symbol.for("@zibby/agent-workflow.skills"),I=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[A]||(globalThis[A]=new Map);globalThis[I]||(globalThis[I]=new Map);var j=globalThis[A],z=globalThis[I];function M(e){return j.get(e)||null}var O=Symbol.for("@zibby/agent-workflow.strategies");globalThis[O]||(globalThis[O]=[]);var p=globalThis[O];function V(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=p.findIndex(n=>n.getName()===e.getName());t>=0?p[t]=e:p.push(e)}function B(){return p.map(e=>e.getName())}function C({config:e={},options:t={},strategyName:n,envModel:r,nodeConfigModel:l}={}){let i=e.models||{},g=typeof l=="string"&&l.trim()?l.trim():null,m=t.nodeName&&i[t.nodeName]||null,y=i.default||null,E=e.agent?.[n]?.model||null,T=(typeof r=="string"?r.trim():"")||null;return g||m||y||E||t.model||T||null}function L({options:e={},stateView:t={},context:n={}}={}){return{workspace:t.workspace||e.workspace,schema:e.schema||n.schema,images:e.images||n.images||[],skills:e.skills||n.skills||[],extraMcpServers:e.extraMcpServers||t.extraMcpServers||n.extraMcpServers||[],plugins:e.plugins||n.plugins||[]}}function Y(e={}){let{state:t={},preferredAgent:n=null}=e,r=n||t.agentType||process.env.AGENT_TYPE;if(!r){let i=p.map(g=>g.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}S.debug(`[workflow] agent selection: requested=${r}`);let l=p.find(i=>i.getName()===r);if(!l){let i=p.map(g=>g.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!l.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return S.debug(`[workflow] using agent: ${l.getName()}`),l}async function W(e,t={},n={}){let r=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},l={...t,state:r},i=Y(l),g=r.config||n.config||{},m=r._currentNodeConfig||{},y=typeof m.agent=="string"?m.agent.trim():"",E=!y||y===i.name?m.model:null,T=C({config:g,options:n,strategyName:i.name,envModel:process.env.MODEL,nodeConfigModel:E}),$={...n,model:T,...L({options:n,stateView:r,context:t}),config:g},u=e,x=$.skills||[];if(x.length>0&&!n.skipPromptFragments){let f=n.connectedIntegrations;if(!f){let s=process.env.WORKFLOW_CONNECTED_INTEGRATIONS;if(typeof s=="string"&&s.trim()!==""){f={};for(let a of s.split(",").map(c=>c.trim()).filter(Boolean))f[a]=!0}}let v=s=>{let a=s&&s.requiresIntegration;return!a||!f?!0:(Array.isArray(a)?a:[a]).some(w=>f[w]===!0)},o=i.name==="assistant",h=s=>s?.inProcessOnly!==!0||o,b=x.map(s=>{let a=M(s);if(!v(a)||!h(a))return null;let c=a?.promptFragment;return typeof c=="function"?c():c}).filter(Boolean);b.length>0&&(u+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${b.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let d=r._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let d=r._currentNodeConfig?.stores;if(Array.isArray(d)&&d.length>0&&typeof d[0]=="object"){let f=d.length<=8,v=d.map(o=>{let h=o?.id??o?.storeId??"",b=(o?.name??"").toString().trim()||h,s=o?.type?` \xB7 ${o.type}`:"",a=(o?.description||"").toString().replace(/\s+/g," ").trim(),c=`- ${b} \xB7 ${a||"(no description)"}${s} (id: ${h})`;if(f&&o?.schema&&typeof o.schema=="object"){let w=o.schema.properties&&typeof o.schema.properties=="object"?Object.keys(o.schema.properties):Object.keys(o.schema);w.length&&(c+=`
|
|
6
|
+
fields: ${w.join(", ")}`)}return c});u+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
|
-
${
|
|
10
|
-
`)}`}let
|
|
9
|
+
${v.join(`
|
|
10
|
+
`)}`}let _=r._currentNodeConfig?.extraPromptInstructions?.trim();return _&&(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
|
-
${
|
|
17
|
-
`),S.debug(`[workflow] prompt length: ${u.length} chars`),i.invoke(u
|
|
16
|
+
${_}
|
|
17
|
+
`),S.debug(`[workflow] prompt length: ${u.length} chars`),i.invoke(u,$)}export{Y as getAgentStrategy,W as invokeAgent,B as listStrategies,V as registerStrategy,L as resolveInvocationExtras,C as resolveInvocationModel};
|
|
@@ -33,6 +33,8 @@
|
|
|
33
33
|
* error. In-process is never attempted without PROJECT_API_TOKEN — we
|
|
34
34
|
* keep the "no cloud creds = no sub-graphs" invariant from v1.
|
|
35
35
|
*/
|
|
36
|
+
import { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS } from './fetch-deadline.js';
|
|
37
|
+
export { SUBGRAPH_TRIGGER_TIMEOUT_MS, SUBGRAPH_POLL_TIMEOUT_MS };
|
|
36
38
|
/**
|
|
37
39
|
* Dispatch `workflowName` as a child of the currently-running execution.
|
|
38
40
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var D=()=>{},Z={debug:D,info:D,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},R={impl:Z};var g={debug:(...e)=>R.impl.debug?.(...e),info:(...e)=>R.impl.info?.(...e),warn:(...e)=>R.impl.warn?.(...e),error:(...e)=>R.impl.error?.(...e)};import{mkdirSync as Q,existsSync as A,statSync as N,readdirSync as X,rmSync as ee}from"node:fs";import{spawn as z}from"node:child_process";import{join as T}from"node:path";import{pathToFileURL as te}from"node:url";import{AsyncLocalStorage as ne}from"node:async_hooks";import{AsyncLocalStorage as K}from"node:async_hooks";var U=new K;function x(){let e=U.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function j(e,t){let r=U.getStore()||x(),n=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??r.executionId??null,depth:(r.depth||0)+(e.executionId!==r.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:r.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:r.agent??null,signal:e.signal!==void 0?e.signal:r.signal??null});return U.run(n,t)}var M=new Map,k=new Map,L=new Map;function G(e,t,r={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");M.set(e,t),k.set(e,"ready"),L.set(e,{...r,cachedAt:Date.now()})}function H(e,t){k.set(e,"failed"),L.set(e,{error:t?.message||String(t),failedAt:Date.now()}),M.delete(e)}function F(e){return k.get(e)==="ready"?M.get(e):null}var O=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function re(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var b=class extends Error{constructor(t,r){super(`in-process sub-graph fallback: ${t}${r?` (${r})`:""}`),this.fallback=!0,this.reason=t,this.detail=r||null,this.name="SubgraphFallback"}};function P(e,t,r,n="timeout"){let o=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(r/1e3)}s (last status: ${n})`);return o.code="SUBGRAPH_TIMEOUT",o.subgraphJobId=t,o.subgraphStatus=n,o}function oe(e,t=process.env,r=process.uptime()){let n=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),s=Number.isFinite(r)&&r>0?r*1e3:0,a=Number.isFinite(o)&&o>0?o-s:null;if(n===null&&a===null)return null;let i=n===null?a:a===null?n:Math.min(n,a);return Math.max(1,i)}function se(e,t){let r=new AbortController,n=!1,o=null,s=()=>{r.abort(e?.reason)};return e&&(e.aborted?s():e.addEventListener("abort",s,{once:!0})),t!=null&&!r.signal.aborted&&(o=setTimeout(()=>{n=!0,r.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:r.signal,timedOut:()=>n,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",s)}}}var J=new ne,q=Promise.resolve();async function ae(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([a,i])=>typeof a=="string"&&a&&typeof i=="string"):[];if(r.length===0)return t();let n=J.getStore()===!0,o=null;if(!n){let a=q;q=new Promise(i=>{o=i}),await a}let s=new Map;try{for(let[a,i]of r)s.set(a,Object.prototype.hasOwnProperty.call(process.env,a)?process.env[a]:void 0),process.env[a]=i;return g.debug(`[in-process subgraph] scoped ${r.length} child env var(s)${n?" (nested)":""}`),await J.run(!0,t)}finally{for(let[a,i]of s)i===void 0?delete process.env[a]:process.env[a]=i;o&&o()}}function ie(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),r=e||t,n=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!r||!n||!o)throw new b("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:r,projectId:n,authToken:o}}async function ce({apiBase:e,authToken:t,body:r}){let n;try{n=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)})}catch(s){throw new b("network",`begin fetch failed: ${s.message}`)}let o=null;try{o=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${r.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=o?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=s,a}if(n.status===400&&o?.validationErrors){let s=new Error(`Sub-graph rejected input: ${o?.error||o?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=o.validationErrors,s.missing=o.missing,s}throw new b("begin-status",`begin returned ${n.status}`)}return o?.data||o}async function _({apiBase:e,authToken:t,payload:r}){try{let n=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});n.ok||g.warn(`[in-process subgraph] finalize returned ${n.status} for ${r.childExecutionId}`)}catch(n){g.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function ue(e,t){let r=T(t,".ready"),n=T(t,"graph.mjs");if(A(r)&&A(n))return;Q(t,{recursive:!0});let o=T(t,".lock"),s=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),f=a(o,"wx");i(f),s=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!s){let a=Date.now()+3e4;for(;Date.now()<a;){if(A(r)&&A(n))return;await new Promise(i=>setTimeout(i,100))}throw new b("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((f,I)=>{let v=z("curl",["-fsSL",e],{stdio:["ignore","pipe","inherit"]}),m=z("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});v.stdout.pipe(m.stdin);let w,p,E=()=>{if(w!==void 0&&p!==void 0){if(w!==0)return I(new Error(`curl exited ${w}`));if(p!==0)return I(new Error(`tar exited ${p}`));f()}};v.on("close",S=>{w=S,E()}),m.on("close",S=>{p=S,E()}),v.on("error",I),m.on("error",I)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(r,"");try{i(o)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new b("bundle-extract-failed",a.message)}}async function le(e){let t=T(e,"graph.mjs");if(!A(t))throw new b("entry-missing",`graph.mjs missing under ${e}`);let r;try{r=await import(te(t).href)}catch(o){throw new b("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let n=r.default||Object.values(r).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!n)throw new b("entry-class-missing","no buildGraph() class export found");return n}async function Y(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let r=x(),n;try{n=ie()}catch(l){throw l}g.debug(`[in-process subgraph] begin '${e}' parent=${r.executionId||"<root>"}`);let o=await ce({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:r.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:s,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:f,workflowVersion:I,workflowUuid:v,bundleReady:m,nodeConfigs:w}=o,p=re();if(a&&a!==p)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new b("runtime-mismatch",`${p} vs ${a}`);if(!m||!i)throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,discard:!0}}),new b("no-bundle","workflow bundle not built yet");let E=F(e);if(!E){let l=T(O,`${v}@${I||"0"}`);try{await ue(i,l);try{pe()}catch{}}catch(c){throw c.fallback&&await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{E=await le(l),G(e,E,{workflowUuid:v,version:I,runtimeTag:a,cacheDir:l})}catch(c){throw H(e,c),await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new b("import-failed",c.message)}}let S=Date.now(),C=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=w&&typeof w=="object"&&!Array.isArray(w)&&Object.keys(w).length>0,B={...t.input||{},...$?{nodeConfigs:w}:{}},u=oe(t.timeoutMs),y=se(t.signal,u),h,d;try{h=await ae(C,async()=>{let c=await(typeof E=="function"&&E.prototype?.buildGraph?new E:E).buildGraph();return j({executionId:s,parentExecutionId:r.executionId,conversationId:t.conversationId!==void 0?t.conversationId:r.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,B,{signal:y.signal}))}),d=h&&typeof h=="object"&&"state"in h?h.state:h}catch(l){let c=y.timedOut();throw await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(u/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:l.message,code:l.code||"CHILD_THREW",stack:l.stack},durationMs:Date.now()-S}}),c?P(e,s,u):l}finally{y.dispose()}if(h&&typeof h=="object"&&h.stoppedExternally){let l=y.timedOut();if(await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:l?"timeout":"canceled",finalState:d,durationMs:Date.now()-S}}),l)throw P(e,s,u);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=s,c}return await _({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:d,durationMs:Date.now()-S}}),{finalState:d,executionId:s}}function de(e){let t=0,r=[e];for(;r.length;){let n=r.pop(),o;try{o=N(n)}catch{continue}if(o.isDirectory()){let s;try{s=X(n)}catch{continue}for(let a of s)r.push(T(n,a))}else t+=o.size}return t}function pe({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!A(O))return{evicted:0,freedBytes:0};let t=X(O),r=[],n=0;for(let i of t){let f=T(O,i),I;try{I=N(f)}catch{continue}let v=I.isDirectory()?de(f):I.size;n+=v,r.push({name:i,full:f,size:v,mtimeMs:I.mtimeMs})}if(n<=e)return{evicted:0,freedBytes:0,totalBytes:n};r.sort((i,f)=>i.mtimeMs-f.mtimeMs);let o=Math.floor(e*.7),s=0,a=0;for(let i of r){if(n-s<=o)break;if(!A(T(i.full,".lock")))try{ee(i.full,{recursive:!0,force:!0}),s+=i.size,a+=1}catch(f){g.debug(`[sub-graph cache] evict skip ${i.name}: ${f.message}`)}}return a>0&&g.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:s,totalBytes:n-s}}catch(t){return g.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var he=2e3,fe=600*1e3,ge=new Set(["completed","failed","canceled","timeout"]);function ye(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function be(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function Ie(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function me(){return process.env.EXECUTION_ID||null}function V(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((r,n)=>r==null?r:r[n],e):e}async function Ue(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let r=x();t.parentAgent==null&&r.agent&&(t.parentAgent=r.agent),t.signal==null&&r.signal&&(t.signal=r.signal);let n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((r.depth||0)>=n)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${r.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:fe;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{g.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await Y(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),y=V(u,t.output);return g.info(`[sub-graph] '${e}' completed in-process`),y}catch(u){if(u instanceof b||u?.fallback)g.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let s=ye(),a=be(),i=Ie(),f=me(),I=`${s}/projects/${encodeURIComponent(a)}/workflows/${encodeURIComponent(e)}/trigger`,v={input:t.input||{},...f?{parentExecutionId:f}:{},...t.conversationId?{conversationId:t.conversationId}:{}};g.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${f||"<none>"}`);let m=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(v)});if(!m.ok){let u=null,y="";try{u=await m.json(),y=u?.error||u?.message||JSON.stringify(u)}catch{y=await m.text().catch(()=>"")}if(m.status===429){let d=u?.quotaInfo||{},l=new Error(`Sub-graph '${e}' blocked by execution quota (${d.used??"?"}/${d.limit??"?"} on plan ${d.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw l.code="SUBGRAPH_QUOTA_EXCEEDED",l.status=429,l.subgraph=e,l.quotaInfo=d,l}if(m.status===400){let d=new Error(`Sub-graph '${e}' rejected input: ${y}`);throw d.code="SUBGRAPH_INVALID_INPUT",d.status=400,d.subgraph=e,d.validationErrors=u?.validationErrors||null,d.missing=u?.missing||null,d}let h=new Error(`Sub-graph '${e}' trigger rejected (${m.status}): ${y}`);throw h.code="SUBGRAPH_TRIGGER_FAILED",h.status=m.status,h.subgraph=e,h}let w=await m.json(),p=w?.data?.jobId||w?.jobId;if(!p)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(w).slice(0,200)}`);if(t.async)return g.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:e};let E=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:he,S=`${s}/executions/${encodeURIComponent(p)}`,C=Date.now()+o,$="accepted",B=0;for(;Date.now()<C;){await new Promise(d=>setTimeout(d,E)),B+=1;let u=await fetch(S,{headers:{Authorization:`Bearer ${i}`}});if(!u.ok){if(u.status>=500){g.warn(`[sub-graph] status poll for ${p} returned ${u.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${u.status}`)}let y=await u.json(),h=y?.data||y?.execution||y;if($=h?.status||$,ge.has($)){if($!=="completed"){let c=new Error(`Sub-graph '${e}' (${p}) ended in status '${$}'`);throw c.subgraphJobId=p,c.subgraphStatus=$,c}let d=h?.finalState||h?.state||{},l=V(d,t.output);return g.info(`[sub-graph] '${e}' (${p}) completed after ${B} polls`),l}}throw P(e,p,o,$)}export{Ue as dispatchSubgraph};
|
|
1
|
+
var J=()=>{},ae={debug:J,info:J,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},k=Symbol.for("@zibby/agent-workflow.logger");globalThis[k]||(globalThis[k]={impl:ae});var G=globalThis[k];var g={debug:(...e)=>G.impl.debug?.(...e),info:(...e)=>G.impl.info?.(...e),warn:(...e)=>G.impl.warn?.(...e),error:(...e)=>G.impl.error?.(...e)};import{mkdirSync as de,existsSync as U,statSync as te,readdirSync as ne,rmSync as pe}from"node:fs";import{spawn as W}from"node:child_process";import{join as O}from"node:path";import{pathToFileURL as he}from"node:url";import{AsyncLocalStorage as ge}from"node:async_hooks";import{AsyncLocalStorage as ie}from"node:async_hooks";var j=new ie;function x(){let e=j.getStore();return e||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null,agent:null,signal:null})}function q(e,t){let n=j.getStore()||x(),r=Object.freeze({executionId:e.executionId,parentExecutionId:e.parentExecutionId??n.executionId??null,depth:(n.depth||0)+(e.executionId!==n.executionId?1:0),conversationId:e.conversationId!==void 0?e.conversationId:n.conversationId??null,dispatchMode:e.dispatchMode??null,agent:e.agent!==void 0?e.agent:n.agent??null,signal:e.signal!==void 0?e.signal:n.signal??null});return j.run(r,t)}var F=new Map,z=new Map,X=new Map;function Y(e,t,n={}){if(!e||typeof e!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");F.set(e,t),z.set(e,"ready"),X.set(e,{...n,cachedAt:Date.now()})}function K(e,t){z.set(e,"failed"),X.set(e,{error:t?.message||String(t),failedAt:Date.now()}),F.delete(e)}function V(e){return z.get(e)==="ready"?F.get(e):null}var P=3e4,Z=15e3;function B(e,t,n=process.env){let r=Number(n[e]);return Number.isFinite(r)&&r>0?Math.min(12e4,Math.max(1e3,Math.floor(r))):t}function N(e,t){return{signal:AbortSignal.timeout(e),label:`after ${e}ms (${t})`}}function C(e,t){return N(B(e,t),e)}function _(e){return e?.name==="TimeoutError"||e?.name==="AbortError"}var D=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function fe(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var b=class extends Error{constructor(t,n){super(`in-process sub-graph fallback: ${t}${n?` (${n})`:""}`),this.fallback=!0,this.reason=t,this.detail=n||null,this.name="SubgraphFallback"}};function L(e,t,n,r="timeout",o=null){let a=new Error(`Sub-graph '${e}' (${t}) timed out after ${Math.round(n/1e3)}s (last status: ${r})`+(o?`; the status API was unreachable on the last attempt (${o})`:""));return a.code="SUBGRAPH_TIMEOUT",a.subgraphJobId=t,a.subgraphStatus=r,o&&(a.subgraphTransportError=o),a}function ye(e,t=process.env,n=process.uptime()){let r=Number.isFinite(e)?Number(e):null,o=Number(t&&t.MAX_WORKFLOW_DURATION_MS),a=Number.isFinite(n)&&n>0?n*1e3:0,s=Number.isFinite(o)&&o>0?o-a:null;if(r===null&&s===null)return null;let i=r===null?s:s===null?r:Math.min(r,s);return Math.max(1,i)}function be(e,t){let n=new AbortController,r=!1,o=null,a=()=>{n.abort(e?.reason)};return e&&(e.aborted?a():e.addEventListener("abort",a,{once:!0})),t!=null&&!n.signal.aborted&&(o=setTimeout(()=>{r=!0,n.abort(new Error("sub-graph deadline exceeded"))},t),typeof o.unref=="function"&&o.unref()),{signal:n.signal,timedOut:()=>r,dispose(){o&&(clearTimeout(o),o=null),e&&e.removeEventListener("abort",a)}}}var Q=new ge,ee=Promise.resolve();async function Ie(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(([s,i])=>typeof s=="string"&&s&&typeof i=="string"):[];if(n.length===0)return t();let r=Q.getStore()===!0,o=null;if(!r){let s=ee;ee=new Promise(i=>{o=i}),await s}let a=new Map;try{for(let[s,i]of n)a.set(s,Object.prototype.hasOwnProperty.call(process.env,s)?process.env[s]:void 0),process.env[s]=i;return g.debug(`[in-process subgraph] scoped ${n.length} child env var(s)${r?" (nested)":""}`),await Q.run(!0,t)}finally{for(let[s,i]of a)i===void 0?delete process.env[s]:process.env[s]=i;o&&o()}}function Ee(){let e=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),n=e||t,r=process.env.PROJECT_ID,o=process.env.PROJECT_API_TOKEN;if(!n||!r||!o)throw new b("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:n,projectId:r,authToken:o}}async function me({apiBase:e,authToken:t,body:n}){let r=C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4),o;try{o=await fetch(`${e}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal})}catch(s){throw new b(_(s)?"begin-timeout":"network",_(s)?`begin TIMED OUT ${r.label}`:`begin fetch failed: ${s.message}`)}let a=null;try{a=await o.json()}catch(s){if(_(s))throw new b("begin-timeout",`begin body read TIMED OUT ${r.label}`)}if(!o.ok){if(o.status===404){let s=new Error(`Sub-graph child '${n.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(o.status===429){let s=a?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=s,i}if(o.status===400&&a?.validationErrors){let s=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=a.validationErrors,s.missing=a.missing,s}throw new b("begin-status",`begin returned ${o.status}`)}return a?.data||a}async function M({apiBase:e,authToken:t,payload:n}){let r=C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);try{let o=await fetch(`${e}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n),signal:r.signal});o.ok||g.warn(`[in-process subgraph] finalize returned ${o.status} for ${n.childExecutionId}`)}catch(o){g.warn(`[in-process subgraph] finalize ${_(o)?`TIMED OUT ${r.label}`:`failed: ${o.message}`}`)}}async function Te(e,t){let n=O(t,".ready"),r=O(t,"graph.mjs");if(U(n)&&U(r))return;de(t,{recursive:!0});let o=O(t,".lock"),a=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),y=s(o,"wx");i(y),a=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!a){let s=Date.now()+3e4;for(;Date.now()<s;){if(U(n)&&U(r))return;await new Promise(i=>setTimeout(i,100))}throw new b("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((y,I)=>{let S=Math.ceil(1e4/1e3),R=Math.ceil(B("SUBGRAPH_BUNDLE_TIMEOUT_MS",6e4)/1e3),h=W("curl",["-fsSL","--connect-timeout",String(S),"--max-time",String(R),e],{stdio:["ignore","pipe","inherit"]}),E=W("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(E.stdin);let d,m,v=()=>{if(d!==void 0&&m!==void 0){if(d!==0)return I(new Error(`curl exited ${d}`));if(m!==0)return I(new Error(`tar exited ${m}`));y()}};h.on("close",$=>{d=$,v()}),E.on("close",$=>{m=$,v()}),h.on("error",I),E.on("error",I)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(n,"");try{i(o)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(o)}catch{}throw new b("bundle-extract-failed",s.message)}}async function _e(e){let t=O(e,"graph.mjs");if(!U(t))throw new b("entry-missing",`graph.mjs missing under ${e}`);let n;try{n=await import(he(t).href)}catch(o){throw new b("import-failed",`${o?.code||o?.name||"unknown"}: ${o.message}`)}let r=n.default||Object.values(n).find(o=>typeof o=="function"&&o.prototype?.buildGraph);if(!r)throw new b("entry-class-missing","no buildGraph() class export found");return r}async function re(e,t={}){if(!e||typeof e!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let n=x(),r;try{r=Ee()}catch(p){throw p}g.debug(`[in-process subgraph] begin '${e}' parent=${n.executionId||"<root>"}`);let o=await me({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:n.executionId,childWorkflowType:e,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:a,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:y,workflowVersion:I,workflowUuid:S,bundleReady:R,nodeConfigs:h}=o,E=fe();if(s&&s!==E)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("runtime-mismatch",`${E} vs ${s}`);if(!R||!i)throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,discard:!0}}),new b("no-bundle","workflow bundle not built yet");let d=V(e);if(!d){let p=O(D,`${S}@${I||"0"}`);try{await Te(i,p);try{we()}catch{}}catch(c){throw c.fallback&&await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason}}}),c}try{d=await _e(p),Y(e,d,{workflowUuid:S,version:I,runtimeTag:s,cacheDir:p})}catch(c){throw K(e,c),await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"failed",error:{message:c.message,code:c.reason||"IMPORT_FAILED"}}}),c.fallback?c:new b("import-failed",c.message)}}let m=Date.now(),v=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:null,$=h&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,w={...t.input||{},...$?{nodeConfigs:h}:{}},A=ye(t.timeoutMs),T=be(t.signal,A),u,l;try{u=await Ie(v,async()=>{let c=await(typeof d=="function"&&d.prototype?.buildGraph?new d:d).buildGraph();return q({executionId:a,parentExecutionId:n.executionId,conversationId:t.conversationId!==void 0?t.conversationId:n.conversationId,dispatchMode:"inprocess"},()=>c.run(t.parentAgent,w,{signal:T.signal}))}),l=u&&typeof u=="object"&&"state"in u?u.state:u}catch(p){let c=T.timedOut();throw await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:c?"timeout":"failed",error:c?{message:`aborted at the declared ${Math.round(A/1e3)}s sub-graph budget`,code:"SUBGRAPH_TIMEOUT"}:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-m}}),c?L(e,a,A):p}finally{T.dispose()}if(u&&typeof u=="object"&&u.stoppedExternally){let p=T.timedOut();if(await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:p?"timeout":"canceled",finalState:l,durationMs:Date.now()-m}}),p)throw L(e,a,A);let c=new Error(`Sub-graph '${e}' canceled by parent abort`);throw c.code="SUBGRAPH_CANCELED",c.subgraphJobId=a,c}return await M({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:a,status:"completed",finalState:l,durationMs:Date.now()-m}}),{finalState:l,executionId:a}}function Se(e){let t=0,n=[e];for(;n.length;){let r=n.pop(),o;try{o=te(r)}catch{continue}if(o.isDirectory()){let a;try{a=ne(r)}catch{continue}for(let s of a)n.push(O(r,s))}else t+=o.size}return t}function we({cap:e=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!U(D))return{evicted:0,freedBytes:0};let t=ne(D),n=[],r=0;for(let i of t){let y=O(D,i),I;try{I=te(y)}catch{continue}let S=I.isDirectory()?Se(y):I.size;r+=S,n.push({name:i,full:y,size:S,mtimeMs:I.mtimeMs})}if(r<=e)return{evicted:0,freedBytes:0,totalBytes:r};n.sort((i,y)=>i.mtimeMs-y.mtimeMs);let o=Math.floor(e*.7),a=0,s=0;for(let i of n){if(r-a<=o)break;if(!U(O(i.full,".lock")))try{pe(i.full,{recursive:!0,force:!0}),a+=i.size,s+=1}catch(y){g.debug(`[sub-graph cache] evict skip ${i.name}: ${y.message}`)}}return s>0&&g.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(a/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:a,totalBytes:r-a}}catch(t){return g.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var $e=2e3,Oe=600*1e3,Re=new Set(["completed","failed","canceled","timeout"]);var Ae=()=>C("SUBGRAPH_TRIGGER_TIMEOUT_MS",3e4);function Me(e){let t=B("SUBGRAPH_POLL_TIMEOUT_MS",15e3),n=Math.max(1,Math.min(t,e-Date.now()));return N(n,"SUBGRAPH_POLL_TIMEOUT_MS")}function Ue(){let e=process.env.PROGRESS_API_URL;if(!e)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 e.replace(/\/executions\/?$/,"")}function ve(){let e=process.env.PROJECT_ID;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return e}function xe(){let e=process.env.PROJECT_API_TOKEN;if(!e)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return e}function Pe(){return process.env.EXECUTION_ID||null}function oe(e,t){return t==null?e:typeof t=="function"?t(e):typeof t=="string"?t.split(".").reduce((n,r)=>n==null?n:n[r],e):e}async function Ze(e,t={}){if(!e||typeof e!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let n=x();t.parentAgent==null&&n.agent&&(t.parentAgent=n.agent),t.signal==null&&n.signal&&(t.signal=n.signal);let r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((n.depth||0)>=r)throw new Error(`dispatchSubgraph('${e}'): sub-graph depth ${n.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);let o=Number.isFinite(t.timeoutMs)?t.timeoutMs:Oe;if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{g.debug(`[sub-graph] trying in-process for '${e}'`);let{finalState:u}=await re(e,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent,timeoutMs:o}),l=oe(u,t.output);return g.info(`[sub-graph] '${e}' completed in-process`),l}catch(u){if(u instanceof b||u?.fallback)g.info(`[sub-graph] in-process fallback for '${e}': ${u.reason||"unknown"} \u2014 using HTTP`);else throw u}let a=Ue(),s=ve(),i=xe(),y=Pe(),I=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(e)}/trigger`,S={input:t.input||{},...y?{parentExecutionId:y}:{},...t.conversationId?{conversationId:t.conversationId}:{}};g.info(`[sub-graph] dispatching '${e}' (${t.async?"async":"sync"}) from parent ${y||"<none>"}`);let R=Ae(),h;try{h=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(S),signal:R.signal})}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger TIMED OUT ${R.label} \u2014 the platform never answered, so no child was dispatched and nothing needs reconciling.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}if(!h.ok){let u=null,l="";try{u=await h.json(),l=u?.error||u?.message||JSON.stringify(u)}catch{l=await h.text().catch(()=>"")}if(h.status===429){let c=u?.quotaInfo||{},f=new Error(`Sub-graph '${e}' blocked by execution quota (${c.used??"?"}/${c.limit??"?"} on plan ${c.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw f.code="SUBGRAPH_QUOTA_EXCEEDED",f.status=429,f.subgraph=e,f.quotaInfo=c,f}if(h.status===400){let c=new Error(`Sub-graph '${e}' rejected input: ${l}`);throw c.code="SUBGRAPH_INVALID_INPUT",c.status=400,c.subgraph=e,c.validationErrors=u?.validationErrors||null,c.missing=u?.missing||null,c}let p=new Error(`Sub-graph '${e}' trigger rejected (${h.status}): ${l}`);throw p.code="SUBGRAPH_TRIGGER_FAILED",p.status=h.status,p.subgraph=e,p}let E;try{E=await h.json()}catch(u){if(!_(u))throw u;let l=new Error(`Sub-graph '${e}' trigger body read TIMED OUT ${R.label} \u2014 the platform accepted the dispatch but never finished answering, so its jobId is unknown and nothing can reconcile it.`);throw l.code="SUBGRAPH_TRIGGER_TIMEOUT",l.subgraph=e,l.timedOut=!0,l.cause=u,l}let d=E?.data?.jobId||E?.jobId;if(!d)throw new Error(`Sub-graph '${e}' trigger returned no jobId: ${JSON.stringify(E).slice(0,200)}`);if(t.async)return g.info(`[sub-graph] async dispatch of '${e}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:e};let m=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:$e,v=`${a}/executions/${encodeURIComponent(d)}`,$=Date.now()+o,w="accepted",A=0,T=null;for(;Date.now()<$;){await new Promise(f=>setTimeout(f,m)),A+=1;let u=Me($),l;try{l=await fetch(v,{headers:{Authorization:`Bearer ${i}`},signal:u.signal})}catch(f){T=_(f)?`poll TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} could not reach the API (${T}), will retry`);continue}if(!l.ok){if(l.status>=500){g.warn(`[sub-graph] status poll for ${d} returned ${l.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${l.status}`)}let p;try{p=await l.json()}catch(f){T=_(f)?`poll body read TIMED OUT ${u.label}`:f?.message||String(f),g.warn(`[sub-graph] status poll for ${d} returned an unreadable body (${T}), will retry`);continue}let c=p?.data||p?.execution||p;if(w=c?.status||w,Re.has(w)){if(w!=="completed"){let H=new Error(`Sub-graph '${e}' (${d}) ended in status '${w}'`);throw H.subgraphJobId=d,H.subgraphStatus=w,H}let f=c?.finalState||c?.state||{},se=oe(f,t.output);return g.info(`[sub-graph] '${e}' (${d}) completed after ${A} polls`),se}}throw L(e,d,o,w,T)}export{Z as SUBGRAPH_POLL_TIMEOUT_MS,P as SUBGRAPH_TRIGGER_TIMEOUT_MS,Ze as dispatchSubgraph};
|
package/dist/tool-resolver.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Symbol.for("@zibby/agent-workflow.skills"),c=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[a]||(globalThis[a]=new Map);globalThis[c]||(globalThis[c]=new Map);var
|
|
1
|
+
var a=Symbol.for("@zibby/agent-workflow.skills"),c=Symbol.for("@zibby/agent-workflow.skills.sources");globalThis[a]||(globalThis[a]=new Map);globalThis[c]||(globalThis[c]=new Map);var w=globalThis[a],k=globalThis[c];function g(e){return w.get(e)||null}var d=()=>{},b={debug:d,info:d,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},f=Symbol.for("@zibby/agent-workflow.logger");globalThis[f]||(globalThis[f]={impl:b});var s=globalThis[f];var y={debug:(...e)=>s.impl.debug?.(...e),info:(...e)=>s.impl.info?.(...e),warn:(...e)=>s.impl.warn?.(...e),error:(...e)=>s.impl.error?.(...e)};var h={};function _(e,t){if(Array.isArray(t))return m(t);let n=h[e];return!n||n.length===0?null:m(n)}function m(e){if(!Array.isArray(e)||e.length===0)return null;let t=[],n={},l=[];for(let i of e){let o=g(i);if(!o){y.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}l.push(i);for(let r of o.tools||[])t.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!n[o.serverName])if(typeof o.resolve=="function"){let r=o.resolve();r&&(n[o.serverName]={...r,toolPrefix:i})}else{let r={};for(let u of o.envKeys||[]){let p=process.env[u];p&&(r[u]=p)}n[o.serverName]={command:o.command,args:[...o.args||[]],env:r,toolPrefix:i}}}return l.length===0?null:{toolIds:l,claudeTools:t,mcpServers:n}}export{h as NODE_DEFAULT_TOOLS,m as getResolvedToolDefinitions,_ as resolveNodeTools};
|