@zibby/agent-workflow 0.1.4 → 0.2.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 +5 -1
- package/dist/code-generator.js +10 -10
- package/dist/constants.d.ts +14 -1
- package/dist/constants.js +1 -1
- package/dist/graph-compiler.js +21 -21
- package/dist/graph.d.ts +49 -8
- package/dist/graph.js +24 -24
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -29
- package/dist/node-registry.js +5 -5
- package/dist/node.js +11 -11
- package/dist/output-parser.js +3 -3
- package/dist/skill-registry.js +1 -1
- package/dist/strategy-registry.js +5 -5
- package/dist/timeline.js +5 -5
- package/dist/tool-resolver.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Pt=Object.defineProperty;var fe=(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 ie=(o,e)=>()=>(o&&(e=o(o=0)),e);var je=(o,e)=>{for(var t in e)Pt(o,t,{get:e[t],enumerable:!0})};function Wt(o){K.impl={...Ze,...o}}var Ue,Ze,K,y,j=ie(()=>{Ue=()=>{},Ze={debug:Ue,info:Ue,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},K={impl:Ze};y={debug:(...o)=>K.impl.debug?.(...o),info:(...o)=>K.impl.info?.(...o),warn:(...o)=>K.impl.warn?.(...o),error:(...o)=>K.impl.error?.(...o)}});var Ee,Ie=ie(()=>{Ee=class{constructor(e,t,s=0){this.name=e,this.description=t,this.priority=s}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 rt={};je(rt,{clearSkills:()=>ot,getAllSkills:()=>et,getSkill:()=>Z,hasSkill:()=>Xe,listSkillIds:()=>tt,registerSkill:()=>Qe});function Qe(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");U.set(o.id,Object.freeze({...o}))}function Z(o){return U.get(o)||null}function Xe(o){return U.has(o)}function et(){return new Map(U)}function tt(){return Array.from(U.keys())}function ot(){U.clear()}var Ne,U,Q=ie(()=>{Ne=Symbol.for("@zibby/agent-workflow.skills");globalThis[Ne]||(globalThis[Ne]=new Map);U=globalThis[Ne]});var X={};je(X,{getAgentStrategy:()=>$e,invokeAgent:()=>it,listStrategies:()=>nt,registerStrategy:()=>st});function st(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=D.findIndex(t=>t.getName()===o.getName());e>=0?D[e]=o:D.push(o)}function nt(){return D.map(o=>o.getName())}function $e(o={}){let{state:e={},preferredAgent:t=null}=o,s=t||e.agentType||process.env.AGENT_TYPE;if(!s){let i=D.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}y.debug(`[workflow] agent selection: requested=${s}`);let n=D.find(i=>i.getName()===s);if(!n){let i=D.map(r=>r.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${s}'. Available: ${i}`)}if(!n.canHandle(o))throw new Error(`Agent '${s}' is not available in this environment. Check credentials/environment.`);return y.debug(`[workflow] using agent: ${n.getName()}`),n}async function it(o,e={},t={}){let s=$e(e),n=e.state?.config||t.config||{},i=n.models||{},r=t.nodeName&&i[t.nodeName]||null,a=i.default||null,c=n.agent?.[s.name]?.model||null,l=r||a||c||t.model||null,h={...t,model:l,workspace:e.state?.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:n},u=o,d=h.skills||[];if(d.length>0&&!t.skipPromptFragments){let g=d.map(S=>{let w=Z(S)?.promptFragment;return typeof w=="function"?w():w}).filter(Boolean);g.length>0&&(u+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${g.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let m=e.state?._currentNodeConfig?.extraPromptInstructions?.trim();return m&&(u+=`
|
|
6
6
|
|
|
7
7
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
8
8
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
9
9
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`),
|
|
11
|
+
${m}
|
|
12
|
+
`),y.debug(`[workflow] prompt length: ${u.length} chars`),s.invoke(u,h)}var Te,D,Y=ie(()=>{Ie();j();Q();Te=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Te]||(globalThis[Te]=[]);D=globalThis[Te]});var Rt=new Set(["__proto__","constructor","prototype"]);function he(o){if(Rt.has(o))throw new Error(`Invalid state key: "${o}"`)}var z=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){he(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let s of t)he(s);this._history.push({...this._state});for(let s of t)this._state[s]=e[s]}append(e,t){he(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())}};var J=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 s=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(n=>n[0]);for(let n of s)try{return this.validate(JSON.parse(n))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[s,n]of Object.entries(this.schema)){if(n.required&&!(s in e)&&t.push(`Missing required field: ${s}`),s in e&&n.type){let i=typeof e[s];i!==n.type&&t.push(`Field '${s}' expected ${n.type}, got ${i}`)}if(n.validate&&s in e){let i=n.validate(e[s]);i&&t.push(`Field '${s}': ${i}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
13
13
|
${t.join(`
|
|
14
|
-
`)}`);return e}},
|
|
15
|
-
`?(r+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,r+=c):e.inEsc?(r+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,r+=c,e.col>=
|
|
16
|
-
${
|
|
14
|
+
`)}`);return e}},Bt={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(", ")}`})};j();import{writeFileSync as ve,readFileSync as at,existsSync as ct,mkdirSync as Ut}from"node:fs";import{join as Oe,dirname as Zt}from"node:path";import T from"chalk";var qe="__WORKFLOW_GRAPH_LOG__",V=T.gray("\u2502"),Dt=T.gray("\u250C"),Ye=T.gray("\u2514"),ge=T.green("\u25C6"),Ge=T.hex("#c084fc")("\u25C6"),He=T.hex("#2dd4bf")("\u25C6"),me=T.red("\u25C6"),ze=`${V} `,Je=2;function Ke(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ve(o,e){return(t,s,n)=>{if(typeof t!="string")return o(t,s,n);let i=process.stdout.columns||120,r="";for(let a=0;a<t.length;a++){let c=t[a];e.lineStart&&(r+=ze,e.col=Je,e.lineStart=!1),c===`
|
|
15
|
+
`?(r+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,r+=c):e.inEsc?(r+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,r+=c,e.col>=i&&(r+=`
|
|
16
|
+
${ze}`,e.col=Je))}return o(r,s,n)}}var ae=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let e=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1",t=!e&&String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase()==="studio";t&&process.env.ZIBBY_NO_DEPRECATION_WARNINGS!=="1"&&console.warn("[zibby/agent-workflow] `ZIBBY_RUN_SOURCE=studio` env var is deprecated for graph-marker emission. Set `ZIBBY_EMIT_GRAPH_MARKERS=1` instead. The Studio-specific value will be ignored in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1."),this._emitWorkflowGraphMarkers=e||t}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
17
17
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
18
18
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
19
|
-
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${
|
|
19
|
+
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${qe}${JSON.stringify(e)}
|
|
20
20
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
21
21
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
22
22
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
23
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
24
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(
|
|
25
|
-
`)}stepMemory(e){let t=
|
|
26
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
27
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${
|
|
23
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(ge,e):process.stdout.write.bind(process.stdout)(`${V} ${ge} ${e}
|
|
24
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ge,e):process.stdout.write.bind(process.stdout)(`${V} ${Ge} ${e}
|
|
25
|
+
`)}stepMemory(e){let t=T.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(He,t):process.stdout.write.bind(process.stdout)(`${V} ${He} ${t}
|
|
26
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(me,T.red(e)):process.stdout.write.bind(process.stdout)(`${V} ${me} ${T.red(e)}
|
|
27
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Dt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:s,details:n}=t;if(n)for(let r of n)this._rawWrite(`${ge} ${r}`);let i=s?T.dim(` ${Ke(s)}`):"";this._rawWrite(`${Ye} ${T.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,s={}){this._stopIntercepting();let{duration:n}=s,i=n?T.dim(` ${Ke(n)}`):"";this._rawWrite(`${me} ${T.red(t)}`),this._rawWrite(`${Ye} ${T.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(T.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){this._rawWrite(T.green.bold("\u2713 Workflow completed"))}},I=new ae;var q=".zibby/output",Se="sessions",W=".session-info.json",we=".zibby-stop",_e=".zibby-studio-stop",Lt="result.json",Mt="raw_stream_output.txt",Ft="events.json",jt={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder"},ye=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];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)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 J(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let s=()=>t&&typeof t.getAll=="function"?t.getAll():e,n=u=>t&&typeof t.get=="function"?t.get(u):e?.[u];if(typeof this.customExecute=="function"){y.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let u=await this.customExecute(e);return typeof u=="object"&&u!==null&&u.success===!1?{success:!1,error:u.error||"Node execution failed",raw:u.raw||null}:this.isZodSchema?(y.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(u),raw:null}):{success:!0,output:u,raw:null}}catch(u){return y.error(`[workflow] node '${this.name}' failed: ${u.message}`),u.name==="ZodError"&&y.error(`Schema errors: ${JSON.stringify(u.issues||u.errors,null,2)}`),{success:!1,error:u.message,raw:null}}}let i=typeof this.prompt=="function"?this.prompt(s()):this.prompt,r=n("_skillHints");r&&(i=`${r}
|
|
28
28
|
|
|
29
|
-
${
|
|
29
|
+
${i}`);let a=s(),c=a.cwd||process.cwd(),l=a.sessionPath;try{if(l){let u=Oe(l,W);if(ct(u)){let m=JSON.parse(at(u,"utf-8"));m.currentNode=this.name,ve(u,JSON.stringify(m,null,2),"utf-8")}let d=Oe(l,"..",W);if(ct(d))try{let m=JSON.parse(at(d,"utf-8"));m.currentNode=this.name,ve(d,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(u){y.debug(`[workflow] could not update session info: ${u.message}`)}let h=null;for(let u=0;u<=this.retries;u++)try{y.debug(`[workflow] node '${this.name}' attempt ${u}`);let d=s().config||{},m=d.agents||{},g=this.config.agent??m[this.name]??null,S={state:s()};g&&(S.preferredAgent=g);let w={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:l,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},f=e?._coreInvokeAgent;f||(f=(await Promise.resolve().then(()=>(Y(),X))).invokeAgent);let $=await f(i,S,w),E,A;if(typeof $=="string"?(E=$,A=null):$.structured?(E=$.raw||JSON.stringify($.structured,null,2),A=$.structured):(E=$.raw||JSON.stringify($,null,2),A=$.extracted||null),l)try{let p=Oe(l,this.name,"raw_stream_output.txt");Ut(Zt(p),{recursive:!0}),ve(p,typeof E=="string"?E:JSON.stringify(E),"utf-8")}catch(p){y.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&A){y.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(A,null,2)}`);let p=A;if(typeof this.onComplete=="function")try{p=await this.onComplete(s(),A)}catch(R){y.warn(`[workflow] onComplete hook failed: ${R.message}`)}return{success:!0,output:p,raw:E}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(s(),{raw:E}),raw:E}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(E);return y.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),I.step("Output parsed"),{success:!0,output:p,raw:E}}return{success:!0,output:E,raw:E}}catch(d){h=d,u<this.retries&&y.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}},ee=class extends L{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let s=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(s)},raw:null}}};import{existsSync as lt,readFileSync as Yt}from"node:fs";import{join as ke,dirname as dt}from"node:path";var te=class{static async loadContext(e,t,s={}){let n={},i=s.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=dt(ke(t,e));for(let c of i){let l=await this.findAndMergeContextFiles(c,a,t);if(l){let h=c.replace(/\.[^.]+$/,"").toLowerCase();n[h]=l}}}let r=s.discovery||{};for(let[a,c]of Object.entries(r))try{let l=ke(t,c);lt(l)&&(n[a]=await this.loadFile(l))}catch(l){console.warn(`[workflow] could not load context '${a}' from '${c}': ${l.message}`)}return n}static async findAndMergeContextFiles(e,t,s){let n=[],i=t;for(;i.startsWith(s);){let r=ke(i,e);if(lt(r))try{n.unshift(await this.loadFile(r))}catch(c){console.warn(`[workflow] could not load ${e} from ${r}: ${c.message}`)}let a=dt(i);if(a===i)break;i=a}return n.length===0?null:n.every(r=>typeof r=="string")?n.join(`
|
|
30
30
|
|
|
31
31
|
---
|
|
32
32
|
|
|
33
|
-
`):
|
|
33
|
+
`):n.every(r=>typeof r=="object")?Object.assign({},...n):n[n.length-1]}static async loadFile(e){let t=Yt(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:s}=await import("url"),n=await import(s(e).href);return n.default||n}return t}};import{mkdirSync as gt,existsSync as ce,writeFileSync as ut,unlinkSync as pt}from"node:fs";import{join as P,resolve as mt}from"node:path";import{config as Gt}from"dotenv";import{zodToJsonSchema as ft}from"zod-to-json-schema";import Ht from"handlebars";var ht=new Set;function le(o,e){ht.has(o)||(ht.add(o),process.env.ZIBBY_NO_DEPRECATION_WARNINGS!=="1"&&console.warn(`[zibby/agent-workflow] ${e}`))}function zt({traceFrom:o,sessionId:e,sessionPath:t,idSource:s,mkdirFresh:n}){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=${s} mkdir=${n?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
|
|
34
34
|
`).slice(2,14).join(`
|
|
35
35
|
`);console.log(`[zibby:session] stack (${o}):
|
|
36
|
-
${h}`)}}function
|
|
37
|
-
\u{1F6D1}
|
|
38
|
-
${h}`),a.includes(".")||r.add(c)}return
|
|
36
|
+
${h}`)}}function St(){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"?!0:process.env.ZIBBY_RUN_SOURCE==="studio"?(le("legacy-zibby-run-source","`ZIBBY_RUN_SOURCE=studio` env var is deprecated. Set `ZIBBY_TRUST_SESSION_ENV=1` (and `ZIBBY_PIN_SESSION_PATH=1` / `ZIBBY_EMIT_GRAPH_MARKERS=1` if you need those gates) instead. The Studio-specific value will be ignored in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1."),!0):!1}function wt(){let o=process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true",e=!o&&process.env.ZIBBY_RUN_SOURCE==="studio";if(e&&le("legacy-zibby-run-source","`ZIBBY_RUN_SOURCE=studio` env var is deprecated. Set `ZIBBY_PIN_SESSION_PATH=1` (and `ZIBBY_TRUST_SESSION_ENV=1` / `ZIBBY_EMIT_GRAPH_MARKERS=1` if you need those gates) instead. The Studio-specific value will be ignored in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1."),!o&&!e)return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return mt(String(t).trim())}catch{return String(t).trim()}}var _t=wt;function yt(){St()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Et({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 It(o={}){let e=ye.map(i=>process.env[i]).find(Boolean),t=Math.random().toString(36).slice(2,6),s=e||`${Date.now()}_${t}`,n=o.paths?.sessionPrefix;return n?`${n}_${s}`:s}function Nt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:s="resolveWorkflowSession"}={}){let n=t.sessionPath,i=t.sessionTimestamp,r="initialState.sessionPath";if(!n&&process.env.ZIBBY_SESSION_PATH)try{let l=mt(String(process.env.ZIBBY_SESSION_PATH));l&&(n=l,r="ZIBBY_SESSION_PATH")}catch{}let a;if(n)a=String(n).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let l=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(l)a=l,r="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=It(e),r="generated")}i=i??Date.now();let h=e.paths?.output||q;n=P(o,h,Se,a)}let c=!ce(n);return c&>(n,{recursive:!0}),(c||r!=="initialState.sessionPath")&&zt({traceFrom:s,sessionId:a,sessionPath:n,idSource:r,mkdirFresh:c}),Et({sessionPath:n,sessionId:a}),{sessionPath:n,sessionId:a,sessionTimestamp:i}}var oe=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,s={}){let n=t instanceof L?t:new L(t);return n.name=e,this.nodes.set(e,n),s.prompt&&this.nodePrompts.set(e,s.prompt),Object.keys(s).length>0&&this.nodeOptions.set(e,s),this}addConditionalNode(e,t){return this.nodes.set(e,new ee({...t,name:e})),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:s}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:s}),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,s,n,i){let r=s;for(let a=e.length-1;a>=0;a--){let c=e[a],l=r;r=()=>c(t,l,n,i)}return r()}serialize(){let e=[],t={};for(let[i,r]of this.nodes){let a=this.nodeTypeMap.get(i)||i;e.push({id:i,type:a,data:{nodeType:a,label:i}});let c={};r._isCustomCode&&typeof r.execute=="function"&&(c.customCode=r.execute.toString());let l=this.nodePrompts.get(i);if(l&&(c.prompt=l),typeof r.customExecute=="function"&&(c.executeCode=r.customExecute.toString()),r.outputSchema)try{if(typeof r.outputSchema._def<"u"){let u=ft(r.outputSchema,{target:"openApi3"});c.outputSchema={jsonSchema:u,variables:this._flattenJsonSchemaToVariables(u)}}else c.outputSchema={schema:r.outputSchema}}catch(u){console.warn(`[workflow] failed to convert schema for ${i}:`,u.message)}let h=(this.resolvedToolsMap||{})[i];h?.toolIds&&(c.tools=h.toolIds),Object.keys(c).length>0&&(t[i]=c)}let s=[];for(let[i,r]of this.edges)if(typeof r=="string")s.push({source:i,target:r});else if(r.conditional){let a=this.conditionalCodeMap.get(i)||r.routes.toString(),c=this._inferConditionalTargets(r.routes),l=r.labels||{};for(let h of c){let u={source:i,target:h,data:{conditionalCode:a}};l[h]&&(u.label=l[h]),s.push(u)}}let n=null;if(this.stateSchema)try{n=ft(this.stateSchema,{target:"openApi3"})}catch{n=this.stateSchema}return{nodes:e,edges:s,nodeConfigs:t,stateSchema:n}}_inferConditionalTargets(e){let t=e.toString(),s=new Set,n=/return\s+['"]([^'"]+)['"]/g,i;for(;(i=n.exec(t))!==null;)s.add(i[1]);return[...s]}_flattenJsonSchemaToVariables(e,t=""){let s=e;if(e.$ref&&e.definitions){let n=e.$ref.replace("#/definitions/","");s=e.definitions[n]||e}return this._flattenSchema(s,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let s=[],n=e.properties||{},i=e.required||[];for(let[r,a]of Object.entries(n)){let c=t?`${t}.${r}`:r;s.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!i.includes(r)}),a.type==="object"&&a.properties&&s.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&s.push(...this._flattenSchema(a.items,`${c}[]`))}return s}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let s=[];t.success!==void 0&&s.push(`Result: ${t.success?"passed":"failed"}`);for(let[n,i]of Object.entries(t))if(!(n==="success"||n==="raw"||n==="nextNode")){if(typeof i=="string"&&i.length<=80)s.push(`${n}: ${i}`);else if(Array.isArray(i)){let r=i.length,a=i.filter(l=>l?.passed===!0).length,c=i.some(l=>l?.passed!==void 0);s.push(c?`${n}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${n}: ${r} items`)}if(s.length>=4)break}return s}async run(e,t={},s={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let n=new AbortController;s.signal&&(s.signal.aborted?n.abort():s.signal.addEventListener("abort",()=>n.abort(),{once:!0}));let i=s.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Gt({path:P(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let _=P(r,".zibby.config.js");ce(_)&&(a=(await import(_)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=t.agentType;if(!c){let _=a?.agent;_?.provider?c=_.provider:_?.gemini?c="gemini":_?.claude?c="claude":_?.cursor?c="cursor":_?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let l=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{};if(this.stateSchema){let _=this.stateSchema.safeParse(t);if(!_.success){let O=_.error.issues.map(b=>`${b.path.join(".")}: ${b.message}`);throw console.error("\u274C Initial state validation failed:"),O.forEach(b=>console.error(` - ${b}`)),new Error(`State validation failed: ${O.join(", ")}`)}I.step("State validated against schema")}let h=_t(),u=t.sessionPath||h;u||yt();let{sessionPath:d,sessionTimestamp:m,sessionId:g}=Nt({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:u,sessionTimestamp:t.sessionTimestamp}});I.step(`Session ${g}`);let S=await te.loadContext(t.specPath||"",r,l);Object.keys(S).length>0&&I.step(`Context loaded: ${Object.keys(S).join(", ")}`);let w=t.outputPath;!w&&t.specPath&&(e?.calculateOutputPath?w=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new z({...t,config:a,agentType:c,outputPath:w,sessionPath:d,sessionTimestamp:m,context:S,resolvedTools:this.resolvedToolsMap||{},_signal:n.signal}),$=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:E}=await Promise.resolve().then(()=>(Q(),rt)),A=new Set;for(let[,_]of this.nodes)for(let O of _.config?.skills||[])A.add(O);for(let _ of A){let O=E(_);if(typeof O?.middleware=="function")try{let b=await O.middleware();typeof b=="function"&&$.set(_,b)}catch{}}let p=this.entryPoint,R=[],Pe=a?.recursionLimit??100,Ot=0;try{for(;p&&p!=="END";){if(++Ot>Pe)throw new Error(`Workflow exceeded recursion limit (${Pe}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let O=P(d,we),b=P(d,_e);if(ce(O)){try{pt(O)}catch{}n.abort()}if(ce(b)){try{pt(b)}catch{}n.abort(),le("legacy-stop-file","Detected legacy `.zibby-studio-stop` file. Consumers should migrate to either `.zibby-stop` (renamed) or pass an AbortSignal to graph.run. The legacy filename will be removed in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1.")}if(n.signal.aborted)return console.warn(`
|
|
37
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),I.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:R,stoppedExternally:!0,stoppedByStudio:!0};let G=this.nodes.get(p);if(!G)throw new Error(`Node '${p}' not found in graph`);let Re=JSON.stringify({sessionPath:d,sessionTimestamp:m,currentNode:p,createdAt:new Date().toISOString(),config:f.get("config")}),kt=P(d,W);ut(kt,Re,"utf-8");let Be=f.get("config")?.paths?.output||q,At=P(r,Be,W);gt(P(r,Be),{recursive:!0});try{ut(At,Re,"utf-8")}catch{}let We=t.onPipelineProgress;if(typeof We=="function")try{We({cwd:r,sessionPath:d,sessionId:g,outputBase:f.get("config")?.paths?.output||q,currentNode:p})}catch{}let bt=(this.resolvedToolsMap||{})[p]||null;f.set("_currentNodeTools",bt);let xt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",xt[p]||{}),I.nodeStart(p);let De=Date.now(),se=this.nodePrompts.get(p);if(!this._invokeAgent){let x=await Promise.resolve().then(()=>(Y(),X));this._invokeAgent=x.invokeAgent}let Ct=this._invokeAgent,Le=async(x,C,N={})=>{let v=Ct(x,C,{...N,signal:n.signal});return v.catch(()=>{}),n.signal.aborted?v:Promise.race([v,new Promise((M,F)=>{let B=()=>{setTimeout(()=>{let H=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${i}ms`);H.name="AbortError",F(H)},i)};n.signal.addEventListener("abort",B,{once:!0})})])},Me={state:f,invokeAgent:async(x={},C={})=>{let N=C.prompt||"";if(se){let v=this._compiledPrompts.get(p);v||(v=Ht.compile(se,{noEscape:!0}),this._compiledPrompts.set(p,v));try{N=v(x)}catch(M){throw console.error(`\u274C Template rendering failed for node '${p}':`,M.message),new Error(`Template rendering failed: ${M.message}`,{cause:M})}}else if(!N)throw new Error(`No prompt template configured for node '${p}' and no prompt provided in options`);return Le(N,{state:f.getAll(),images:C.images||[]},{model:C.model||f.get("model"),workspace:f.get("workspace"),schema:C.schema,...C,signal:n.signal})},_coreInvokeAgent:Le,agent:e,nodeId:p,promptTemplate:se,getPromptTemplate:()=>se,...f.getAll()};try{let x=(G.config?.skills||[]).map(B=>$.get(B)).filter(Boolean),C=[...this.middleware,...x],N;C.length>0?N=await this._composeMiddleware(C,p,async()=>G.execute(Me,f),f.getAll(),f):N=await G.execute(Me,f);let v=Date.now()-De;if(R.push({node:p,success:N.success,duration:v,timestamp:new Date().toISOString()}),!N.success){if(String(N.error||"").includes("Stopped from Zibby Studio"))return le("legacy-error-string",'Strategy returned the legacy `Stopped from Zibby Studio` error string. Strategies should reject with `Error.name === "AbortError"` instead. The string-match fallback will be removed in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1.'),I.step("Workflow stopped externally"),f.set("stoppedExternally",!0),f.set("stoppedByStudio",!0),{success:!0,state:f.getAll(),executionLog:R,stoppedExternally:!0,stoppedByStudio:!0};if(n.signal.aborted)return I.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:R,stoppedExternally:!0,stoppedByStudio:!0};f.append("errors",{node:p,error:N.error});let H=G.config?.retries||0,Fe=`${p}_retries`,ne=f.getAll()[Fe]||0;if(ne<H){I.stepInfo(`Retrying (attempt ${ne+1}/${H})`),f.update({[Fe]:ne+1,[`${p}_raw`]:N.raw});continue}throw I.nodeFailed(p,N.error,{duration:v}),new Error(`Node '${p}' failed after ${ne} attempts: ${N.error}`)}f.update({[p]:N.output});let M=this._summarizeNodeOutput(p,N.output);I.nodeComplete(p,{duration:v,details:M});let F=this.edges.get(p);if(!F)p="END";else if(F.conditional){let B=F.routes(f.getAll());I.route(p,B),p=B}else p=F}catch(x){throw I.isInsideNode&&I.nodeFailed(p,x.message,{duration:Date.now()-De}),f.set("failed",!0),f.set("failedAt",p),x}}I.graphComplete();let _={success:!0,state:f.getAll(),executionLog:R};return e&&typeof e.onComplete=="function"&&await e.onComplete(_),_}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(_){console.warn(`[workflow] agent.cleanup() failed: ${_.message}`)}}}};var re=new Map;function Tt(o,e){re.set(o,e)}function Ae(o){return re.get(o)}function de(o){return re.has(o)}function Jt(){return Array.from(re.keys())}function be(o){let e=re.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}Tt("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let s=t?._coreInvokeAgent;s||(s=(await Promise.resolve().then(()=>(Y(),X))).invokeAgent);let n=e.extraPromptInstructions||"Execute the task based on the current state.",i=Kt(n,t),r=await s(i,{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 Kt(o,e){let t=/@([\w.]+)/g,s=new Set,n;for(;(n=t.exec(o))!==null;)s.add(n[1]);if(s.size===0)return o;let i=[],r=new Set;for(let a of s){let c=a.split(".")[0];if(r.has(c))continue;let l=a.split(".").reduce((d,m)=>d?.[m],e);if(l===void 0)continue;let h=typeof l=="string"?l:l?.raw??JSON.stringify(l,null,2),u=a.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());i.push(`## ${u}
|
|
38
|
+
${h}`),a.includes(".")||r.add(c)}return i.length===0?o:`${o}
|
|
39
39
|
|
|
40
40
|
---
|
|
41
41
|
# Referenced Context
|
|
42
42
|
|
|
43
|
-
${
|
|
43
|
+
${i.join(`
|
|
44
44
|
|
|
45
|
-
`)}`}
|
|
46
|
-
`)}function
|
|
47
|
-
`)}function
|
|
48
|
-
`)}function
|
|
49
|
-
`)}function
|
|
50
|
-
`)}function
|
|
51
|
-
`)}function
|
|
45
|
+
`)}`}Q();j();var ue={};function Ce(o,e){if(Array.isArray(e))return xe(e);let t=ue[o];return!t||t.length===0?null:xe(t)}function xe(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},s=[];for(let n of o){let i=Z(n);if(!i){y.warn(`[workflow] unknown skill "${n}" \u2014 skipping`);continue}s.push(n);for(let r of i.tools||[])e.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!t[i.serverName])if(typeof i.resolve=="function"){let r=i.resolve();r&&(t[i.serverName]={...r,toolPrefix:n})}else{let r={};for(let a of i.envKeys||[]){let c=process.env[a];c&&(r[a]=c)}t[i.serverName]={command:i.command,args:[...i.args||[]],env:r,toolPrefix:n}}}return s.length===0?null:{toolIds:s,claudeTools:e,mcpServers:t}}j();function Vt(o,e={}){let{nodes:t,edges:s,nodeConfigs:n={}}=o;if(!Array.isArray(t)||t.length===0)throw new k("Graph must have at least one node");if(!Array.isArray(s))throw new k("Graph edges must be an array");let i=new oe(e);e.stateSchema&&i.setStateSchema(e.stateSchema);let r=new Set,a=new Map,c={};for(let d of t){let m=pe(d);a.set(d.id,{...d,resolvedType:m}),m==="decision"&&r.add(d.id)}for(let[d,m]of a){if(r.has(d))continue;let g=m.resolvedType,S=n[d]||{},w=Ce(g,S.tools);w&&(c[d]=w);let f={};S.prompt&&(f.prompt=S.prompt);let $=de(g);if(y.debug(`[workflow] compiler: node "${d}" type="${g}" registered=${$}`),S.customCode&&!$)i.addNode(d,$t(d,S.customCode,S),f),i.setNodeType(d,g);else if($){let E=Ae(g);E.factory?i.addNode(d,E.create(d,{...S,resolvedTools:w}),f):i.addNode(d,E,f),i.setNodeType(d,g)}else if(S.executeCode)i.addNode(d,$t(d,S.executeCode,S),f),i.setNodeType(d,g);else throw new k(`Unknown node type "${g}" for node "${d}". Did you forget to register it?`)}i.resolvedToolsMap=c;let l=new Set;for(let d of s)r.has(d.target)||l.add(d.target);let h=t.find(d=>!r.has(d.id)&&!l.has(d.id));if(!h)throw new k("Could not determine entry point: no node without incoming edges found");i.setEntryPoint(h.id);let u=Xt(s,"source");for(let d of s)if(!r.has(d.source))if(r.has(d.target)){let m=d.target,g=u.get(m)||[];if(g.length===0)throw new k(`Decision node "${m}" has no outgoing edges`);let S=eo(m,g,r);i.addConditionalEdges(d.source,S)}else i.addEdge(d.source,d.target);return i}function qt(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 c=pe(a);if(c==="decision"||de(c))continue;let l=t[a.id]||{};l.customCode||l.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let s=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)s.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),s.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let n=new Set(o.nodes.filter(a=>pe(a)==="decision").map(a=>a.id)),i=new Set;for(let a of o.edges)n.has(a.target)||i.add(a.target);let r=o.nodes.filter(a=>!n.has(a.id)&&!i.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 n){let c=o.edges.filter(h=>h.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Qt(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>pe(e)!=="decision").map(e=>e.id)}function pe(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Xt(o,e){let t=new Map;for(let s of o){let n=s[e];t.has(n)||t.set(n,[]),t.get(n).push(s)}return t}function eo(o,e,t){let s=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!s)throw new k(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let n=s.data?.conditionalCode||s.conditionalCode,i=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),r;try{let c=new Function(`return (${n})`)();r=l=>{let h=c(l);return i.has(h)||y.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...i].join(", ")}`),h}}catch(a){throw new k(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return r}function $t(o,e,t={}){let s;try{s=new Function("invokeAgent","require","console",`return (${e})`)}catch(r){throw new k(`Failed to compile customCode for node "${o}": ${r.message}`)}let n=s(async(...r)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(Y(),X));return a(...r)},typeof fe<"u"?fe:void 0,console),i=null;return t.outputSchema&&(i=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:i,execute:async r=>{try{let a=await n(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 k=class extends Error{constructor(e){super(e),this.name="CompilationError"}};Q();Ie();Y();function to(o,e={}){let{nodes:t,edges:s,nodeConfigs:n={}}=o,i=new Set,r=[],a=new Map;for(let w of t){let f=w.data?.nodeType||w.type;a.set(w.id,f),f==="decision"?i.add(w.id):r.push({id:w.id,nodeType:f,label:w.data?.label||w.id})}let c=r.some(w=>{let f=n[w.id]||{};return!f.customCode&&!f.executeCode}),{toolsPerNode:l,toolIdsByVar:h}=lo(r,n),{simpleEdges:u,conditionalEdges:d}=uo(s,i),m=po(r,s,i),g=[],S=e.workflowType||"workflow";return g.push(ro(e)),g.push(so(S,{usesRegisteredNodes:c})),g.push(no(h)),g.push(io(S)),g.push(ao(r,n)),g.push(co(r,m,u,d,l,S)),g.filter(Boolean).join(`
|
|
46
|
+
`)}function oo(o){let e={};for(let[t,s]of Object.entries(o)){let{tools:n,...i}=s;Object.keys(i).length>0&&(e[t]=i)}return e}function ro(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(`
|
|
47
|
+
`)}function so(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(`
|
|
48
|
+
`)}function no(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,s]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(s)}); // ${s.join(", ")}`);return e.push(""),e.join(`
|
|
49
|
+
`)}function io(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(`
|
|
50
|
+
`)}function ao(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 s of o){let n=vt(s.id),i=e[s.id]?.customCode;if(i)t.push(`// @custom \u2014 modified from default "${s.nodeType}" template`),t.push(`const ${n}_execute = ${i};`);else{let r=be(s.nodeType);r?(t.push(`// Default "${s.nodeType}" implementation`),t.push(`const ${n}_execute = ${r};`)):(t.push(`// No template for "${s.nodeType}" \u2014 passthrough`),t.push(`const ${n}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
51
|
+
`)}function co(o,e,t,s,n,i){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 c of o){let l=vt(c.id);r.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${l}_execute });`),r.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}r.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||s.length>0)&&r.push(" // Edges");for(let c of t)r.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of s){let l=c.code.split(`
|
|
52
52
|
`).map((h,u)=>u===0?h:` ${h}`).join(`
|
|
53
|
-
`);r.push(` graph.addConditionalEdges('${c.source}', ${
|
|
54
|
-
`)}function
|
|
53
|
+
`);r.push(` graph.addConditionalEdges('${c.source}', ${l});`)}let a=[];for(let c of o){let l=n.get(c.id);l&&a.push(` '${c.id}': ${l},`)}return a.length>0&&r.push(""," graph.resolvedToolsMap = {",...a," };"),r.push(""," return graph;","}",""),r.push("export { nodeConfigs };",""),r.join(`
|
|
54
|
+
`)}function lo(o,e){let t=new Map,s=new Map;for(let n of o){let i=e[n.id]?.tools,r;if(Array.isArray(i)&&i.length>0)r=[...i].sort();else{let a=ue[n.nodeType];a?.length>0&&(r=[...a].sort())}if(r){let a=`${r.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(n.id,a),s.has(a)||s.set(a,r)}}return{toolsPerNode:t,toolIdsByVar:s}}function uo(o,e){let t=[],s=[],n=new Map,i=new Set;for(let r of o)n.has(r.source)||n.set(r.source,[]),n.get(r.source).push(r);for(let r of o)if(!e.has(r.source))if(e.has(r.target)){if(i.has(r.target))continue;i.add(r.target);let c=(n.get(r.target)||[]).find(l=>l.data?.conditionalCode||l.conditionalCode);c&&s.push({source:r.source,code:c.data?.conditionalCode||c.conditionalCode})}else t.push({source:r.source,target:r.target});return{simpleEdges:t,conditionalEdges:s}}function po(o,e,t){let s=new Set;for(let i of e)t.has(i.target)||s.add(i.target);let n=o.find(i=>!s.has(i.id));return n?n.id:o[0]?.id}function vt(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}j();export{Ee as AgentStrategy,ye as CI_ENV_VARS,k as CompilationError,ee as ConditionalNode,te as ContextLoader,q as DEFAULT_OUTPUT_BASE,Ft as EVENTS_FILE,ue as NODE_DEFAULT_TOOLS,L as Node,J as OutputParser,Mt as RAW_OUTPUT_FILE,Lt as RESULT_FILE,Se as SESSIONS_DIR,W as SESSION_INFO_FILE,jt as SKILLS,we as STOP_REQUEST_FILE,_e as STUDIO_STOP_REQUEST_FILE,Bt as SchemaTypes,ae as Timeline,qe as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,oe as WorkflowGraph,z as WorkflowState,yt as clearInheritedSessionEnvForFreshRun,ot as clearSkills,Vt as compileGraph,Qt as extractSteps,oo as generateNodeConfigsJson,to as generateWorkflowCode,It as generateWorkflowSessionId,$e as getAgentStrategy,et as getAllSkills,Ae as getNodeImpl,be as getNodeTemplate,xe as getResolvedToolDefinitions,Z as getSkill,de as hasNode,Xe as hasSkill,it as invokeAgent,Jt as listNodeTypes,tt as listSkillIds,nt as listStrategies,wt as readPinnedSessionPathFromEnv,_t as readStudioPinnedSessionPathFromEnv,Tt as registerNode,Qe as registerSkill,st as registerStrategy,Ce as resolveNodeTools,Nt as resolveWorkflowSession,Wt as setLogger,St as shouldTrustInheritedSessionEnv,Et as syncProcessEnvToSession,I as timeline,qt as validateGraphConfig};
|
package/dist/node-registry.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var C=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})};var x=w(()=>{});var S,P,h,k,T=w(()=>{S=()=>{},P={debug:S,info:S,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},h={impl:P},k={debug:(...e)=>h.impl.debug?.(...e),info:(...e)=>h.impl.info?.(...e),warn:(...e)=>h.impl.warn?.(...e),error:(...e)=>h.impl.error?.(...e)}});function v(e){return Y.get(e)||null}var b,Y,A=w(()=>{b=Symbol.for("@zibby/agent-workflow.skills");globalThis[b]||(globalThis[b]=new Map);Y=globalThis[b]});var I={};C(I,{getAgentStrategy:()=>_,invokeAgent:()=>G,listStrategies:()=>j,registerStrategy:()=>M});function M(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=c.findIndex(n=>n.getName()===e.getName());t>=0?c[t]=e:c.push(e)}function j(){return c.map(e=>e.getName())}function _(e={}){let{state:t={},preferredAgent:n=null}=e,r=n||t.agentType||process.env.AGENT_TYPE;if(!r){let o=c.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${o}`)}k.debug(`[workflow] agent selection: requested=${r}`);let i=c.find(o=>o.getName()===r);if(!i){let o=c.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${o}`)}if(!i.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return k.debug(`[workflow] using agent: ${i.getName()}`),i}async function G(e,t={},n={}){let r=_(t),i=t.state?.config||n.config||{},o=i.models||{},s=n.nodeName&&o[n.nodeName]||null,l=o.default||null,m=i.agent?.[r.name]?.model||null,a=s||l||m||n.model||null,p={...n,model:a,workspace:t.state?.workspace||n.workspace,schema:n.schema||t.schema,images:n.images||t.images||[],skills:n.skills||t.skills||[],config:i},u=e,g=p.skills||[];if(g.length>0&&!n.skipPromptFragments){let E=g.map(R=>{let y=v(R)?.promptFragment;return typeof y=="function"?y():y}).filter(Boolean);E.length>0&&(u+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${E.join(`
|
|
4
4
|
|
|
5
5
|
`)}`)}let d=t.state?._currentNodeConfig?.extraPromptInstructions?.trim();return d&&(u+=`
|
|
6
6
|
|
|
@@ -9,12 +9,12 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
9
9
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
10
10
|
|
|
11
11
|
${d}
|
|
12
|
-
`),k.debug(`[workflow] prompt length: ${u.length} chars`),r.invoke(u,
|
|
13
|
-
${
|
|
12
|
+
`),k.debug(`[workflow] prompt length: ${u.length} chars`),r.invoke(u,p)}var N,c,$=w(()=>{x();T();A();N=Symbol.for("@zibby/agent-workflow.strategies");globalThis[N]||(globalThis[N]=[]);c=globalThis[N]});var f=new Map;function L(e,t){f.set(e,t)}function J(e){return f.get(e)}function W(e){return f.has(e)}function Q(){return Array.from(f.keys())}function X(e){let t=f.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}L("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(()=>($(),I))).invokeAgent);let i=t.extraPromptInstructions||"Execute the task based on the current state.",o=z(i,n),s=await r(o,{cwd:n.workspace||process.cwd(),model:n.model,tools:t.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:e},raw:typeof s=="string"?s:s.raw}}})});function z(e,t){let n=/@([\w.]+)/g,r=new Set,i;for(;(i=n.exec(e))!==null;)r.add(i[1]);if(r.size===0)return e;let o=[],s=new Set;for(let l of r){let m=l.split(".")[0];if(s.has(m))continue;let a=l.split(".").reduce((g,d)=>g?.[d],t);if(a===void 0)continue;let p=typeof a=="string"?a:a?.raw??JSON.stringify(a,null,2),u=l.replace(/_/g," ").replace(/\b\w/g,g=>g.toUpperCase());o.push(`## ${u}
|
|
13
|
+
${p}`),l.includes(".")||s.add(m)}return o.length===0?e:`${e}
|
|
14
14
|
|
|
15
15
|
---
|
|
16
16
|
# Referenced Context
|
|
17
17
|
|
|
18
18
|
${o.join(`
|
|
19
19
|
|
|
20
|
-
`)}`}export{
|
|
20
|
+
`)}`}export{J as getNodeImpl,X as getNodeTemplate,W as hasNode,Q as listNodeTypes,L as registerNode};
|
package/dist/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var st=Object.defineProperty;var b=(r,t)=>()=>(r&&(t=r(r=0)),t);var it=(r,t)=>{for(var e in t)st(r,e,{get:t[e],enumerable:!0})};var D,nt,k,c,W=b(()=>{D=()=>{},nt={debug:D,info:D,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},k={impl:nt},c={debug:(...r)=>k.impl.debug?.(...r),info:(...r)=>k.impl.info?.(...r),warn:(...r)=>k.impl.warn?.(...r),error:(...r)=>k.impl.error?.(...r)}});var Z=b(()=>{});function z(r){return ct.get(r)||null}var L,ct,V=b(()=>{L=Symbol.for("@zibby/agent-workflow.skills");globalThis[L]||(globalThis[L]=new Map);ct=globalThis[L]});var Q={};it(Q,{getAgentStrategy:()=>q,invokeAgent:()=>dt,listStrategies:()=>pt,registerStrategy:()=>ut});function ut(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=w.findIndex(e=>e.getName()===r.getName());t>=0?w[t]=r:w.push(r)}function pt(){return w.map(r=>r.getName())}function q(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let n=w.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}c.debug(`[workflow] agent selection: requested=${o}`);let i=w.find(n=>n.getName()===o);if(!i){let n=w.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${n}`)}if(!i.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return c.debug(`[workflow] using agent: ${i.getName()}`),i}async function dt(r,t={},e={}){let o=q(t),i=t.state?.config||e.config||{},n=i.models||{},a=e.nodeName&&n[e.nodeName]||null,g=n.default||null,p=i.agent?.[o.name]?.model||null,_=a||g||p||e.model||null,E={...e,model:_,workspace:t.state?.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:i},s=r,h=E.skills||[];if(h.length>0&&!e.skipPromptFragments){let y=h.map(O=>{let $=z(O)?.promptFragment;return typeof $=="function"?$():$}).filter(Boolean);y.length>0&&(s+=`
|
|
2
2
|
|
|
3
3
|
${y.join(`
|
|
4
4
|
|
|
@@ -9,21 +9,21 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
|
|
|
9
9
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
10
10
|
|
|
11
11
|
${f}
|
|
12
|
-
`),c.debug(`[workflow] prompt length: ${s.length} chars`),o.invoke(s
|
|
12
|
+
`),c.debug(`[workflow] prompt length: ${s.length} chars`),o.invoke(s,E)}var P,w,X=b(()=>{Z();W();V();P=Symbol.for("@zibby/agent-workflow.strategies");globalThis[P]||(globalThis[P]=[]);w=globalThis[P]});var N=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(n){if(!(n instanceof SyntaxError))throw n}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 n=typeof t[o];n!==i.type&&e.push(`Field '${o}' expected ${i.type}, got ${n}`)}if(i.validate&&o in t){let n=i.validate(t[o]);n&&e.push(`Field '${o}': ${n}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
13
13
|
${e.join(`
|
|
14
|
-
`)}`);return t}};
|
|
14
|
+
`)}`);return t}};W();import{writeFileSync as C,readFileSync as tt,existsSync as et,mkdirSync as ht}from"node:fs";import{join as F,dirname as ft}from"node:path";import l from"chalk";var at="__WORKFLOW_GRAPH_LOG__",I=l.gray("\u2502"),lt=l.gray("\u250C"),B=l.gray("\u2514"),T=l.green("\u25C6"),G=l.hex("#c084fc")("\u25C6"),U=l.hex("#2dd4bf")("\u25C6"),A=l.red("\u25C6"),Y=`${I} `,j=2;function J(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function H(r,t){return(e,o,i)=>{if(typeof e!="string")return r(e,o,i);let n=process.stdout.columns||120,a="";for(let g=0;g<e.length;g++){let p=e[g];t.lineStart&&(a+=Y,t.col=j,t.lineStart=!1),p===`
|
|
15
15
|
`?(a+=p,t.lineStart=!0,t.col=0,t.inEsc=!1):p==="\x1B"?(t.inEsc=!0,a+=p):t.inEsc?(a+=p,(p>="A"&&p<="Z"||p>="a"&&p<="z")&&(t.inEsc=!1)):(t.col++,a+=p,t.col>=n&&(a+=`
|
|
16
|
-
${
|
|
16
|
+
${Y}`,t.col=j))}return r(a,o,i)}}var x=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1",e=!t&&String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase()==="studio";e&&process.env.ZIBBY_NO_DEPRECATION_WARNINGS!=="1"&&console.warn("[zibby/agent-workflow] `ZIBBY_RUN_SOURCE=studio` env var is deprecated for graph-marker emission. Set `ZIBBY_EMIT_GRAPH_MARKERS=1` instead. The Studio-specific value will be ignored in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1."),this._emitWorkflowGraphMarkers=t||e}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=H(this._origStdoutWrite,t),process.stderr.write=H(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
17
17
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
18
18
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
19
|
-
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${
|
|
19
|
+
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let e=`${at}${JSON.stringify(t)}
|
|
20
20
|
`;this._origStdoutWrite?this._origStdoutWrite(e):process.stdout.write(e)}_writeDot(t,e){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
21
21
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${t} ${e}
|
|
22
22
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
23
|
-
`)}step(t){this._origStdoutWrite?this._writeDot(
|
|
24
|
-
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(
|
|
25
|
-
`)}stepMemory(t){let e=
|
|
26
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(A,
|
|
27
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
23
|
+
`)}step(t){this._origStdoutWrite?this._writeDot(T,t):process.stdout.write.bind(process.stdout)(`${I} ${T} ${t}
|
|
24
|
+
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(G,t):process.stdout.write.bind(process.stdout)(`${I} ${G} ${t}
|
|
25
|
+
`)}stepMemory(t){let e=l.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(U,e):process.stdout.write.bind(process.stdout)(`${I} ${U} ${e}
|
|
26
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(A,l.red(t)):process.stdout.write.bind(process.stdout)(`${I} ${A} ${l.red(t)}
|
|
27
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${lt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:i}=e;if(i)for(let a of i)this._rawWrite(`${T} ${a}`);let n=o?l.dim(` ${J(o)}`):"";this._rawWrite(`${B} ${l.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:i}=o,n=i?l.dim(` ${J(i)}`):"";this._rawWrite(`${A} ${l.red(e)}`),this._rawWrite(`${B} ${l.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(l.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){this._rawWrite(l.green.bold("\u2713 Workflow completed"))}},K=new x;var v=".session-info.json";var M=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new N(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,i=s=>e&&typeof e.get=="function"?e.get(s):t?.[s];if(typeof this.customExecute=="function"){c.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let s=await this.customExecute(t);return typeof s=="object"&&s!==null&&s.success===!1?{success:!1,error:s.error||"Node execution failed",raw:s.raw||null}:this.isZodSchema?(c.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){return c.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&c.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),{success:!1,error:s.message,raw:null}}}let n=typeof this.prompt=="function"?this.prompt(o()):this.prompt,a=i("_skillHints");a&&(n=`${a}
|
|
28
28
|
|
|
29
|
-
${n}`);let g=o(),p=g.cwd||process.cwd(),
|
|
29
|
+
${n}`);let g=o(),p=g.cwd||process.cwd(),_=g.sessionPath;try{if(_){let s=F(_,v);if(et(s)){let f=JSON.parse(tt(s,"utf-8"));f.currentNode=this.name,C(s,JSON.stringify(f,null,2),"utf-8")}let h=F(_,"..",v);if(et(h))try{let f=JSON.parse(tt(h,"utf-8"));f.currentNode=this.name,C(h,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(s){c.debug(`[workflow] could not update session info: ${s.message}`)}let E=null;for(let s=0;s<=this.retries;s++)try{c.debug(`[workflow] node '${this.name}' attempt ${s}`);let h=o().config||{},f=h.agents||{},y=this.config.agent??f[this.name]??null,O={state:o()};y&&(O.preferredAgent=y);let $={workspace:p,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:_,config:h,nodeName:this.name,timeout:this.config?.timeout||3e5},R=t?._coreInvokeAgent;R||(R=(await Promise.resolve().then(()=>(X(),Q))).invokeAgent);let m=await R(n,O,$),d,S;if(typeof m=="string"?(d=m,S=null):m.structured?(d=m.raw||JSON.stringify(m.structured,null,2),S=m.structured):(d=m.raw||JSON.stringify(m,null,2),S=m.extracted||null),_)try{let u=F(_,this.name,"raw_stream_output.txt");ht(ft(u),{recursive:!0}),C(u,typeof d=="string"?d:JSON.stringify(d),"utf-8")}catch(u){c.debug(`[workflow] could not save raw output: ${u.message}`)}if(this.isZodSchema&&S){c.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(S,null,2)}`);let u=S;if(typeof this.onComplete=="function")try{u=await this.onComplete(o(),S)}catch(ot){c.warn(`[workflow] onComplete hook failed: ${ot.message}`)}return{success:!0,output:u,raw:d}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:d}),raw:d}}catch(u){throw new Error(`onComplete failed: ${u.message}`,{cause:u})}if(this.parser){let u=this.parser.parse(d);return c.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(u,null,2)}`),K.step("Output parsed"),{success:!0,output:u,raw:d}}return{success:!0,output:d,raw:d}}catch(h){E=h,s<this.retries&&c.info(`[workflow] node '${this.name}' failed, retrying (${s+1}/${this.retries})\u2026`)}return{success:!1,error:E.message,raw:null}}},rt=class extends M{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};export{rt as ConditionalNode,M as Node};
|
package/dist/output-parser.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
3
|
-
`)}`);return e}},
|
|
1
|
+
var a=class{constructor(e){this.schema=e}parse(e){let r=e.match(/```json\s*([\s\S]*?)\s*```/);if(r)return this.validate(JSON.parse(r[1]));let i=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(n=>n[0]);for(let n of i)try{return this.validate(JSON.parse(n))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let r=[];for(let[i,n]of Object.entries(this.schema)){if(n.required&&!(i in e)&&r.push(`Missing required field: ${i}`),i in e&&n.type){let s=typeof e[i];s!==n.type&&r.push(`Field '${i}' expected ${n.type}, got ${s}`)}if(n.validate&&i in e){let s=n.validate(e[i]);s&&r.push(`Field '${i}': ${s}`)}}if(r.length>0)throw new Error(`Output validation failed:
|
|
2
|
+
${r.join(`
|
|
3
|
+
`)}`);return e}},o={string:(t=!0)=>({type:"string",required:t}),number:(t=!0)=>({type:"number",required:t}),boolean:(t=!0)=>({type:"boolean",required:t}),array:(t=!0)=>({type:"object",required:t,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(t,e=!0)=>({type:"string",required:e,validate:r=>t.includes(r)?null:`must be one of: ${t.join(", ")}`})};export{a as OutputParser,o as SchemaTypes};
|
package/dist/skill-registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=new Map;function
|
|
1
|
+
var e=Symbol.for("@zibby/agent-workflow.skills");globalThis[e]||(globalThis[e]=new Map);var r=globalThis[e];function i(t){if(!t||typeof t.id!="string")throw new Error("Skill definition must include a string id");r.set(t.id,Object.freeze({...t}))}function n(t){return r.get(t)||null}function l(t){return r.has(t)}function o(){return new Map(r)}function s(){return Array.from(r.keys())}function f(){r.clear()}export{f as clearSkills,o as getAllSkills,n as getSkill,l as hasSkill,s as listSkillIds,i as registerSkill};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=()=>{},y={debug:k,info:k,warn:(...e)=>console.warn("[workflow]",...e),error:(...e)=>console.error("[workflow]",...e)},g={impl:y};var c={debug:(...e)=>g.impl.debug?.(...e),info:(...e)=>g.impl.info?.(...e),warn:(...e)=>g.impl.warn?.(...e),error:(...e)=>g.impl.error?.(...e)};var f=Symbol.for("@zibby/agent-workflow.skills");globalThis[f]||(globalThis[f]=new Map);var v=globalThis[f];function b(e){return v.get(e)||null}var u=Symbol.for("@zibby/agent-workflow.strategies");globalThis[u]||(globalThis[u]=[]);var s=globalThis[u];function C(e){if(!e||typeof e.getName!="function"||typeof e.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let n=s.findIndex(t=>t.getName()===e.getName());n>=0?s[n]=e:s.push(e)}function Y(){return s.map(e=>e.getName())}function A(e={}){let{state:n={},preferredAgent:t=null}=e,r=t||n.agentType||process.env.AGENT_TYPE;if(!r){let i=s.map(l=>l.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}c.debug(`[workflow] agent selection: requested=${r}`);let o=s.find(i=>i.getName()===r);if(!o){let i=s.map(l=>l.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${i}`)}if(!o.canHandle(e))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return c.debug(`[workflow] using agent: ${o.getName()}`),o}async function G(e,n={},t={}){let r=A(n),o=n.state?.config||t.config||{},i=o.models||{},l=t.nodeName&&i[t.nodeName]||null,E=i.default||null,N=o.agent?.[r.name]?.model||null,T=l||E||N||t.model||null,p={...t,model:T,workspace:n.state?.workspace||t.workspace,schema:t.schema||n.schema,images:t.images||n.images||[],skills:t.skills||n.skills||[],config:o},a=e,d=p.skills||[];if(d.length>0&&!t.skipPromptFragments){let h=d.map(S=>{let m=b(S)?.promptFragment;return typeof m=="function"?m():m}).filter(Boolean);h.length>0&&(a+=`
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${h.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
5
|
+
`)}`)}let w=n.state?._currentNodeConfig?.extraPromptInstructions?.trim();return w&&(a+=`
|
|
6
6
|
|
|
7
7
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
8
8
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
9
9
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`),c.debug(`[workflow] prompt length: ${a.length} chars`),r.invoke(a,
|
|
11
|
+
${w}
|
|
12
|
+
`),c.debug(`[workflow] prompt length: ${a.length} chars`),r.invoke(a,p)}export{A as getAgentStrategy,G as invokeAgent,Y as listStrategies,C as registerStrategy};
|
package/dist/timeline.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import e from"chalk";var I="__WORKFLOW_GRAPH_LOG__",c=e.gray("\u2502"),
|
|
2
|
-
`?(s+=i,t.lineStart=!0,t.col=0,t.inEsc=!1):i==="\x1B"?(t.inEsc=!0,s+=i):t.inEsc?(s+=i,(i>="A"&&i<="Z"||i>="a"&&i<="z")&&(t.inEsc=!1)):(t.col++,s+=i,t.col>=
|
|
3
|
-
${
|
|
1
|
+
import e from"chalk";var I="__WORKFLOW_GRAPH_LOG__",c=e.gray("\u2502"),R=e.gray("\u250C"),p=e.gray("\u2514"),h=e.green("\u25C6"),S=e.hex("#c084fc")("\u25C6"),w=e.hex("#2dd4bf")("\u25C6"),l=e.red("\u25C6"),W=`${c} `,f=2;function g(_){return _<1e3?`${_}ms`:`${(_/1e3).toFixed(1)}s`}function $(_,t){return(r,o,n)=>{if(typeof r!="string")return _(r,o,n);let d=process.stdout.columns||120,s="";for(let u=0;u<r.length;u++){let i=r[u];t.lineStart&&(s+=W,t.col=f,t.lineStart=!1),i===`
|
|
2
|
+
`?(s+=i,t.lineStart=!0,t.col=0,t.inEsc=!1):i==="\x1B"?(t.inEsc=!0,s+=i):t.inEsc?(s+=i,(i>="A"&&i<="Z"||i>="a"&&i<="z")&&(t.inEsc=!1)):(t.col++,s+=i,t.col>=d&&(s+=`
|
|
3
|
+
${W}`,t.col=f))}return _(s,o,n)}}var a=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null;let t=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1",r=!t&&String(process.env.ZIBBY_RUN_SOURCE||"").trim().toLowerCase()==="studio";r&&process.env.ZIBBY_NO_DEPRECATION_WARNINGS!=="1"&&console.warn("[zibby/agent-workflow] `ZIBBY_RUN_SOURCE=studio` env var is deprecated for graph-marker emission. Set `ZIBBY_EMIT_GRAPH_MARKERS=1` instead. The Studio-specific value will be ignored in v2. Suppress with ZIBBY_NO_DEPRECATION_WARNINGS=1."),this._emitWorkflowGraphMarkers=t||r}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},r={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=r,process.stdout.write=$(this._origStdoutWrite,t),process.stderr.write=$(this._origStderrWrite,r)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
4
4
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
5
5
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(t){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${t}
|
|
6
6
|
`)}_emitGraphLogMarker(t){if(!this._emitWorkflowGraphMarkers)return;let r=`${I}${JSON.stringify(t)}
|
|
@@ -9,6 +9,6 @@ ${w}`,t.col=f))}return d(s,o,n)}}var a=class{constructor(){this._currentNode=nul
|
|
|
9
9
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${r}
|
|
10
10
|
`)}step(t){this._origStdoutWrite?this._writeDot(h,t):process.stdout.write.bind(process.stdout)(`${c} ${h} ${t}
|
|
11
11
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(S,t):process.stdout.write.bind(process.stdout)(`${c} ${S} ${t}
|
|
12
|
-
`)}stepMemory(t){let r=e.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(
|
|
12
|
+
`)}stepMemory(t){let r=e.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(w,r):process.stdout.write.bind(process.stdout)(`${c} ${w} ${r}
|
|
13
13
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(l,e.red(t)):process.stdout.write.bind(process.stdout)(`${c} ${l} ${e.red(t)}
|
|
14
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${
|
|
14
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${R} ${t}`),this._startIntercepting()}nodeComplete(t,r={}){this._stopIntercepting();let{duration:o,details:n}=r;if(n)for(let s of n)this._rawWrite(`${h} ${s}`);let d=o?e.dim(` ${g(o)}`):"";this._rawWrite(`${p} ${e.green("done")}${d}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,r,o={}){this._stopIntercepting();let{duration:n}=o,d=n?e.dim(` ${g(n)}`):"";this._rawWrite(`${l} ${e.red(r)}`),this._rawWrite(`${p} ${e.red("failed")}${d}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,r){this._rawWrite(e.dim(` ${t} \u2192 ${r}`)),this._rawWrite("")}graphComplete(){this._rawWrite(e.green.bold("\u2713 Workflow completed"))}},E=new a;var P=E;export{a as Timeline,I as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,P as default,E as timeline};
|
package/dist/tool-resolver.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Symbol.for("@zibby/agent-workflow.skills");globalThis[f]||(globalThis[f]=new Map);var d=globalThis[f];function u(o){return d.get(o)||null}var p=()=>{},w={debug:p,info:p,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},l={impl:w};var g={debug:(...o)=>l.impl.debug?.(...o),info:(...o)=>l.impl.info?.(...o),warn:(...o)=>l.impl.warn?.(...o),error:(...o)=>l.impl.error?.(...o)};var k={};function S(o,t){if(Array.isArray(t))return m(t);let n=k[o];return!n||n.length===0?null:m(n)}function m(o){if(!Array.isArray(o)||o.length===0)return null;let t=[],n={},s=[];for(let i of o){let e=u(i);if(!e){g.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}s.push(i);for(let r of e.tools||[])t.push({name:r.name,description:r.description,input_schema:r.input_schema||{type:"object",properties:{}}});if(!n[e.serverName])if(typeof e.resolve=="function"){let r=e.resolve();r&&(n[e.serverName]={...r,toolPrefix:i})}else{let r={};for(let c of e.envKeys||[]){let a=process.env[c];a&&(r[c]=a)}n[e.serverName]={command:e.command,args:[...e.args||[]],env:r,toolPrefix:i}}}return s.length===0?null:{toolIds:s,claudeTools:t,mcpServers:n}}export{k as NODE_DEFAULT_TOOLS,m as getResolvedToolDefinitions,S as resolveNodeTools};
|