@zibby/agent-workflow 0.4.31 → 0.4.33

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.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * compose-knowledge.js — the CANONICAL, single-source COMPOSE knowledge.
3
+ *
4
+ * "Compose" = chaining independently-deployed marketplace agents (bricks) with
5
+ * a small project-private WRAPPER workflow, via this engine's sub-workflow
6
+ * primitives (`workflow:` nodes / dispatchSubgraph). The rules below are
7
+ * platform truths that every composing surface must agree on, so they live
8
+ * HERE — next to the primitives they describe — and are IMPORTED by all three
9
+ * consumers instead of being hand-copied:
10
+ *
11
+ * 1. the Copilot chat-ops skill (@zibby/skills-internal zibby-control-plane
12
+ * promptFragment — the COMPOSE bullet),
13
+ * 2. the agent-builder marketplace template (generate node's authoring
14
+ * knowledge block),
15
+ * 3. the `zibby init` CLAUDE.md §10 (stamped between managed markers by
16
+ * packages/scripts/sync-compose-knowledge.mjs).
17
+ *
18
+ * Each consumer may ADD its own surface-specific glue (delegation mechanics,
19
+ * CLI commands, self-host caveats) but must not restate these rules. Editing
20
+ * policy: change the text here, bump this package, let the consumers re-sync
21
+ * — never edit a consumer's copy in place.
22
+ *
23
+ * The text is audience-neutral markdown addressed to "the wrapper author" —
24
+ * an AI builder agent, a local Claude/Codex session, or a human.
25
+ */
26
+ export const COMPOSE_KNOWLEDGE: "## Composing deployed agents (wrapper over marketplace bricks)\n\n**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER\nmodify a brick template's source and never rebuild its logic from scratch.\nThe composition is a small project-private WRAPPER workflow that dispatches\nalready-DEPLOYED bricks as sub-workflows. A forked/edited brick falls off the\nupgrade path.\n\n**Reuse policy \u2014 ask, never silently choose.** If a needed brick is already\ndeployed in the project, the user decides: reuse that instance (runs + config\nare shared with its standalone use) or deploy a dedicated instance under a\ncustom name (config isolation).\n\n**Sub-workflow node.** Declare a child dispatch by giving addNode a config\nwith a `workflow:` field \u2014 the DEPLOYED slug in the SAME project (the row's\nworkflowType, not the marketplace slug, when they differ):\n\n graph.addNode('review', {\n workflow: 'gitlab-code-review', // deployed slug\n input: (state) => ({ projectId: state.projectId, mrIid: state.mrIid }),\n timeoutMs: 15 * 60 * 1000,\n });\n\nThe engine runs the child in-process (same worker) when possible and the\nchild's FINAL state \u2014 whichever End it exited \u2014 lands at `state[nodeName]`.\nOptions: `workflow` (required), `input` (object or `(state) => object`),\n`output` (dot-path or `(finalState) => any` to extract just what's needed),\n`async: true` (fire-and-forget \u2192 `{ jobId }`), `timeoutMs`, `retries`.\nFor PARALLEL fan-out call `dispatchSubgraph(slug, { input })` (exported by\n@zibby/agent-workflow) inside one custom execute node with\n`Promise.allSettled` \u2014 one brick failing must not kill its siblings.\n\n**Chain conditions are EXPLICIT decision nodes.** Bricks are full multi-exit\ngraphs, so branch on the child's RETURNED state between dispatches \u2014 and model\nthe branch so the graph SHOWS it: a router node\n(`graph.addNode('<id>', { description })` \u2014 no execute/prompt/outputSchema;\nrenders as the Condition diamond) routed with\n`graph.addConditionalEdges('<id>', routeFn, { labels })`. Never an unlabeled\ndispatch\u2192End edge. Note the child's own node outputs are NESTED\n(`state.review.review.posted` = the child's `review` node output), e.g. only\nmeter when `state.review?.review?.posted === true && state.review?.trigger\n!== 'comment_reply'`.\n\n**Input mapping is the wrapper's job \u2014 use the brick's CANONICAL structured\nfields.** In-process children run the brick's graph directly and SKIP any\nconvenience normalization its class run() does on cold starts (e.g.\ngitlab-code-review parses mrUrl \u2192 projectId+mrIid only on cold runs \u2014 pass\nprojectId/mrIid yourself).\n\n**Credentials/config: children use their OWN row's env** (engine \u22650.4.32 +\nmatching backend). A brick's per-workflow env (Env tab / envSecret) applies to\nits in-process wrapped runs too \u2014 the child's value wins, the wrapper's env is\nonly the fallback for keys the brick doesn't define. So the wrapper needs ZERO\ncredential duplication: leave each brick's creds (e.g.\nCLAUDE_CODE_OAUTH_TOKEN) on the brick itself and give the wrapper none.\n(Env-carrying children serialize when dispatched in parallel; env-less ones\nkeep full parallelism. On older engines children inherit only the wrapper env\n\u2014 symptom: authentication_failed inside the child.) A brick's saved per-node\ncustom prompts (nodeConfigOverrides.<node>.extraPromptInstructions) apply\nin-process since \u22650.4.30, and its stores bindings ride along since \u22650.4.32.\n\n**Triggers \u2014 INHERIT the entry brick's events, read not invent.** The\nwrapper's trigger is AGENT-DRIVEN, never hardcoded: for webhook compositions\nthe wrapper's workflow.json `triggers.events` is a verbatim COPY of whatever\nthe ENTRY brick declares \u2014 read it from the brick's deployed row (or its\ntemplate workflow.json) and paste the exact array. The platform then\nautomatically SUPPRESSES the wrapped members' own subscriptions (any workflow\nlisted in a deployed wrapper's composedOf stops receiving standalone webhook\nevents), so the same event never double-fires a brick inside AND outside the\nwrapper. Cron / manual / chat-triggered compositions need nothing special.";
27
+ export default COMPOSE_KNOWLEDGE;
@@ -0,0 +1,70 @@
1
+ var e=`## Composing deployed agents (wrapper over marketplace bricks)
2
+
3
+ **Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
4
+ modify a brick template's source and never rebuild its logic from scratch.
5
+ The composition is a small project-private WRAPPER workflow that dispatches
6
+ already-DEPLOYED bricks as sub-workflows. A forked/edited brick falls off the
7
+ upgrade path.
8
+
9
+ **Reuse policy \u2014 ask, never silently choose.** If a needed brick is already
10
+ deployed in the project, the user decides: reuse that instance (runs + config
11
+ are shared with its standalone use) or deploy a dedicated instance under a
12
+ custom name (config isolation).
13
+
14
+ **Sub-workflow node.** Declare a child dispatch by giving addNode a config
15
+ with a \`workflow:\` field \u2014 the DEPLOYED slug in the SAME project (the row's
16
+ workflowType, not the marketplace slug, when they differ):
17
+
18
+ graph.addNode('review', {
19
+ workflow: 'gitlab-code-review', // deployed slug
20
+ input: (state) => ({ projectId: state.projectId, mrIid: state.mrIid }),
21
+ timeoutMs: 15 * 60 * 1000,
22
+ });
23
+
24
+ The engine runs the child in-process (same worker) when possible and the
25
+ child's FINAL state \u2014 whichever End it exited \u2014 lands at \`state[nodeName]\`.
26
+ Options: \`workflow\` (required), \`input\` (object or \`(state) => object\`),
27
+ \`output\` (dot-path or \`(finalState) => any\` to extract just what's needed),
28
+ \`async: true\` (fire-and-forget \u2192 \`{ jobId }\`), \`timeoutMs\`, \`retries\`.
29
+ For PARALLEL fan-out call \`dispatchSubgraph(slug, { input })\` (exported by
30
+ @zibby/agent-workflow) inside one custom execute node with
31
+ \`Promise.allSettled\` \u2014 one brick failing must not kill its siblings.
32
+
33
+ **Chain conditions are EXPLICIT decision nodes.** Bricks are full multi-exit
34
+ graphs, so branch on the child's RETURNED state between dispatches \u2014 and model
35
+ the branch so the graph SHOWS it: a router node
36
+ (\`graph.addNode('<id>', { description })\` \u2014 no execute/prompt/outputSchema;
37
+ renders as the Condition diamond) routed with
38
+ \`graph.addConditionalEdges('<id>', routeFn, { labels })\`. Never an unlabeled
39
+ dispatch\u2192End edge. Note the child's own node outputs are NESTED
40
+ (\`state.review.review.posted\` = the child's \`review\` node output), e.g. only
41
+ meter when \`state.review?.review?.posted === true && state.review?.trigger
42
+ !== 'comment_reply'\`.
43
+
44
+ **Input mapping is the wrapper's job \u2014 use the brick's CANONICAL structured
45
+ fields.** In-process children run the brick's graph directly and SKIP any
46
+ convenience normalization its class run() does on cold starts (e.g.
47
+ gitlab-code-review parses mrUrl \u2192 projectId+mrIid only on cold runs \u2014 pass
48
+ projectId/mrIid yourself).
49
+
50
+ **Credentials/config: children use their OWN row's env** (engine \u22650.4.32 +
51
+ matching backend). A brick's per-workflow env (Env tab / envSecret) applies to
52
+ its in-process wrapped runs too \u2014 the child's value wins, the wrapper's env is
53
+ only the fallback for keys the brick doesn't define. So the wrapper needs ZERO
54
+ credential duplication: leave each brick's creds (e.g.
55
+ CLAUDE_CODE_OAUTH_TOKEN) on the brick itself and give the wrapper none.
56
+ (Env-carrying children serialize when dispatched in parallel; env-less ones
57
+ keep full parallelism. On older engines children inherit only the wrapper env
58
+ \u2014 symptom: authentication_failed inside the child.) A brick's saved per-node
59
+ custom prompts (nodeConfigOverrides.<node>.extraPromptInstructions) apply
60
+ in-process since \u22650.4.30, and its stores bindings ride along since \u22650.4.32.
61
+
62
+ **Triggers \u2014 INHERIT the entry brick's events, read not invent.** The
63
+ wrapper's trigger is AGENT-DRIVEN, never hardcoded: for webhook compositions
64
+ the wrapper's workflow.json \`triggers.events\` is a verbatim COPY of whatever
65
+ the ENTRY brick declares \u2014 read it from the brick's deployed row (or its
66
+ template workflow.json) and paste the exact array. The platform then
67
+ automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
68
+ listed in a deployed wrapper's composedOf stops receiving standalone webhook
69
+ events), so the same event never double-fires a brick inside AND outside the
70
+ wrapper. Cron / manual / chat-triggered compositions need nothing special.`,t=e;export{e as COMPOSE_KNOWLEDGE,t as default};
@@ -1,12 +1,12 @@
1
- var Mt=Object.defineProperty;var ye=(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 Fe=(o,e)=>{for(var t in e)Mt(o,t,{get:e[t],enumerable:!0})};var He,jt,le,I,W=ie(()=>{He=()=>{},jt={debug:He,info:He,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:jt},I={debug:(...o)=>le.impl.debug?.(...o),info:(...o)=>le.impl.info?.(...o),warn:(...o)=>le.impl.warn?.(...o),error:(...o)=>le.impl.error?.(...o)}});var tt=ie(()=>{});var ot={};Fe(ot,{clearSkills:()=>Yt,getAllSkills:()=>Ht,getSkill:()=>Q,hasSkill:()=>Ft,listSkillIds:()=>Jt,registerSkill:()=>Gt});function Gt(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");q.set(o.id,Object.freeze({...o}))}function Q(o){return q.get(o)||null}function Ft(o){return q.has(o)}function Ht(){return new Map(q)}function Jt(){return Array.from(q.keys())}function Yt(){q.clear()}var be,q,de=ie(()=>{be=Symbol.for("@zibby/agent-workflow.skills");globalThis[be]||(globalThis[be]=new Map);q=globalThis[be]});var ee={};Fe(ee,{getAgentStrategy:()=>rt,invokeAgent:()=>Kt,listStrategies:()=>zt,registerStrategy:()=>Zt});function Zt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function zt(){return G.map(o=>o.getName())}function rt(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let n=G.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}I.debug(`[workflow] agent selection: requested=${r}`);let a=G.find(n=>n.getName()===r);if(!a){let n=G.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${n}`)}if(!a.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${a.getName()}`),a}async function Kt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},a={...e,state:r},n=rt(a),s=r.config||t.config||{},i=s.models||{},u=t.nodeName&&i[t.nodeName]||null,d=i.default||null,p=s.agent?.[n.name]?.model||null,l=u||d||p||t.model||null,c={...t,model:l,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:s},m=o,S=c.skills||[];if(S.length>0&&!t.skipPromptFragments){let E=S.map(f=>{let h=Q(f)?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);E.length>0&&(m+=`
1
+ var jt=Object.defineProperty;var ye=(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 Fe=(o,e)=>{for(var t in e)jt(o,t,{get:e[t],enumerable:!0})};var He,Ut,le,I,W=ie(()=>{He=()=>{},Ut={debug:He,info:He,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},le={impl:Ut},I={debug:(...o)=>le.impl.debug?.(...o),info:(...o)=>le.impl.info?.(...o),warn:(...o)=>le.impl.warn?.(...o),error:(...o)=>le.impl.error?.(...o)}});var tt=ie(()=>{});var ot={};Fe(ot,{clearSkills:()=>zt,getAllSkills:()=>Yt,getSkill:()=>Q,hasSkill:()=>Jt,listSkillIds:()=>Zt,registerSkill:()=>Ht});function Ht(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");q.set(o.id,Object.freeze({...o}))}function Q(o){return q.get(o)||null}function Jt(o){return q.has(o)}function Yt(){return new Map(q)}function Zt(){return Array.from(q.keys())}function zt(){q.clear()}var be,q,de=ie(()=>{be=Symbol.for("@zibby/agent-workflow.skills");globalThis[be]||(globalThis[be]=new Map);q=globalThis[be]});var ee={};Fe(ee,{getAgentStrategy:()=>rt,invokeAgent:()=>Vt,listStrategies:()=>qt,registerStrategy:()=>Kt});function Kt(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=G.findIndex(t=>t.getName()===o.getName());e>=0?G[e]=o:G.push(o)}function qt(){return G.map(o=>o.getName())}function rt(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}I.debug(`[workflow] agent selection: requested=${r}`);let a=G.find(s=>s.getName()===r);if(!a){let s=G.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!a.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${a.getName()}`),a}async function Vt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},a={...e,state:r},s=rt(a),n=r.config||t.config||{},i=n.models||{},u=t.nodeName&&i[t.nodeName]||null,d=i.default||null,h=n.agent?.[s.name]?.model||null,l=u||d||h||t.model||null,c={...t,model:l,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},m=o,S=c.skills||[];if(S.length>0&&!t.skipPromptFragments){let E=S.map(g=>{let f=Q(g)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);E.length>0&&(m+=`
2
2
 
3
3
  ${E.join(`
4
4
 
5
- `)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let E=_.length<=8,f=_.map(h=>{let y=h?.id??h?.storeId??"",g=(h?.name??"").toString().trim()||y,$=h?.type?` \xB7 ${h.type}`:"",b=(h?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${g} \xB7 ${b||"(no description)"}${$} (id: ${y})`;if(E&&h?.schema&&typeof h.schema=="object"){let w=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);w.length&&(R+=`
5
+ `)}`)}let _=r._currentNodeConfig?.stores;if(Array.isArray(_)&&_.length>0&&typeof _[0]=="object"){let E=_.length<=8,g=_.map(f=>{let y=f?.id??f?.storeId??"",p=(f?.name??"").toString().trim()||y,b=f?.type?` \xB7 ${f.type}`:"",A=(f?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${A||"(no description)"}${b} (id: ${y})`;if(E&&f?.schema&&typeof f.schema=="object"){let w=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);w.length&&(R+=`
6
6
  fields: ${w.join(", ")}`)}return R});m+=`
7
7
 
8
8
  AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
9
- ${f.join(`
9
+ ${g.join(`
10
10
  `)}`}let v=r._currentNodeConfig?.extraPromptInstructions?.trim();return v&&(m+=`
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
@@ -14,14 +14,14 @@ PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PRE
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
  ${v}
17
- `),I.debug(`[workflow] prompt length: ${m.length} chars`),n.invoke(m,c)}var $e,G,te=ie(()=>{tt();W();de();$e=Symbol.for("@zibby/agent-workflow.strategies");globalThis[$e]||(globalThis[$e]=[]);G=globalThis[$e]});var Dt=new Set(["__proto__","constructor","prototype"]);function we(o){if(Dt.has(o))throw new Error(`Invalid state key: "${o}"`)}var ae=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){we(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)we(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){we(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import F from"handlebars";var ce=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(a=>a[0]);for(let a of r)try{return this.validate(JSON.parse(a))}catch(n){if(!(n instanceof SyntaxError))throw n}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,a]of Object.entries(this.schema)){if(a.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&a.type){let n=typeof e[r];n!==a.type&&t.push(`Field '${r}' expected ${a.type}, got ${n}`)}if(a.validate&&r in e){let n=a.validate(e[r]);n&&t.push(`Field '${r}': ${n}`)}}if(t.length>0)throw new Error(`Output validation failed:
17
+ `),I.debug(`[workflow] prompt length: ${m.length} chars`),s.invoke(m,c)}var $e,G,te=ie(()=>{tt();W();de();$e=Symbol.for("@zibby/agent-workflow.strategies");globalThis[$e]||(globalThis[$e]=[]);G=globalThis[$e]});var Lt=new Set(["__proto__","constructor","prototype"]);function we(o){if(Lt.has(o))throw new Error(`Invalid state key: "${o}"`)}var ae=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){we(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)we(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){we(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(t)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import F from"handlebars";var ce=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(a=>a[0]);for(let a of r)try{return this.validate(JSON.parse(a))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,a]of Object.entries(this.schema)){if(a.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&a.type){let s=typeof e[r];s!==a.type&&t.push(`Field '${r}' expected ${a.type}, got ${s}`)}if(a.validate&&r in e){let s=a.validate(e[r]);s&&t.push(`Field '${r}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
18
18
  ${t.join(`
19
- `)}`);return e}};W();import{writeFileSync as Te,readFileSync as nt,existsSync as st,mkdirSync as qt}from"node:fs";import{join as Ae,dirname as Vt}from"node:path";import x from"chalk";var Lt="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Ut=x.gray("\u250C"),Je=x.gray("\u2514"),_e=x.green("\u25C6"),Ye=x.hex("#c084fc")("\u25C6"),Ze=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),ze=`${X} `,Ke=2;function qe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ve(o,e){return(t,r,a)=>{if(typeof t!="string")return o(t,r,a);let n=process.stdout.columns||120,s="";for(let i=0;i<t.length;i++){let u=t[i];e.lineStart&&(s+=ze,e.col=Ke,e.lineStart=!1),u===`
20
- `?(s+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,s+=u):e.inEsc?(s+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,s+=u,e.col>=n&&(s+=`
21
- ${ze}`,e.col=Ke))}return o(s,r,a)}}var Ee=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
19
+ `)}`);return e}};W();import{writeFileSync as ve,readFileSync as nt,existsSync as st,mkdirSync as Xt}from"node:fs";import{join as Te,dirname as Qt}from"node:path";import x from"chalk";var Wt="__WORKFLOW_GRAPH_LOG__",X=x.gray("\u2502"),Gt=x.gray("\u250C"),Je=x.gray("\u2514"),_e=x.green("\u25C6"),Ye=x.hex("#c084fc")("\u25C6"),Ze=x.hex("#2dd4bf")("\u25C6"),Ie=x.red("\u25C6"),ze=`${X} `,Ke=2;function qe(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Ve(o,e){return(t,r,a)=>{if(typeof t!="string")return o(t,r,a);let s=process.stdout.columns||120,n="";for(let i=0;i<t.length;i++){let u=t[i];e.lineStart&&(n+=ze,e.col=Ke,e.lineStart=!1),u===`
20
+ `?(n+=u,e.lineStart=!0,e.col=0,e.inEsc=!1):u==="\x1B"?(e.inEsc=!0,n+=u):e.inEsc?(n+=u,(u>="A"&&u<="Z"||u>="a"&&u<="z")&&(e.inEsc=!1)):(e.col++,n+=u,e.col>=s&&(n+=`
21
+ ${ze}`,e.col=Ke))}return o(n,r,a)}}var Ee=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=Ve(this._origStdoutWrite,e),process.stderr.write=Ve(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
22
22
  `),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
23
23
  `),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
24
- `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Lt}${JSON.stringify(e)}
24
+ `)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${Wt}${JSON.stringify(e)}
25
25
  `;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
26
26
  `),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
27
27
  `)):process.stdout.write.bind(process.stdout)(`${e} ${t}
@@ -29,22 +29,22 @@ ${ze}`,e.col=Ke))}return o(s,r,a)}}var Ee=class{constructor(){this._currentNode=
29
29
  `)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ye,e):process.stdout.write.bind(process.stdout)(`${X} ${Ye} ${e}
30
30
  `)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(Ze,t):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${t}
31
31
  `)}stepFail(e){this._origStdoutWrite?this._writeDot(Ie,x.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ie} ${x.red(e)}
32
- `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Ut} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:a}=t;if(a)for(let s of a)this._rawWrite(`${_e} ${s}`);let n=r?x.dim(` ${qe(r)}`):"";this._rawWrite(`${Je} ${x.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:a}=r,n=a?x.dim(` ${qe(a)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${Je} ${x.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var ue=".zibby/output",Xe="sessions",K=".session-info.json",Qe=".zibby-stop";var Wt={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Uo=Object.freeze([Wt.CODEBASE_MEMORY]),et=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",o=>Number(o)+1);F.helpers.json||F.registerHelper("json",o=>JSON.stringify(o,null,2));F.helpers.eq||F.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ce(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,a=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return I.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let n;typeof this.prompt=="function"?n=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(r())):n=this.prompt;let s=a("_skillHints");s&&(n=`${s}
32
+ `)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${Gt} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:a}=t;if(a)for(let n of a)this._rawWrite(`${_e} ${n}`);let s=r?x.dim(` ${qe(r)}`):"";this._rawWrite(`${Je} ${x.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:a}=r,s=a?x.dim(` ${qe(a)}`):"";this._rawWrite(`${Ie} ${x.red(t)}`),this._rawWrite(`${Je} ${x.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},O=new Ee;var ue=".zibby/output",Xe="sessions",K=".session-info.json",Qe=".zibby-stop";var Ft={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",DISCORD:"discord",CHAT_NOTIFY:"chat_notify",SENTRY:"sentry",MEMORY:"memory",CHAT_MEMORY:"chat-memory",KV_MEMORY:"kv-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools",WORKFLOW_BUILDER:"workflow-builder",SESSION:"session",OPENAI_BILLING:"openai_billing",ANTHROPIC_BILLING:"anthropic_billing",CURSOR_ADMIN:"cursor_admin",NOTION:"notion",GOOGLE_DOCS:"google-docs",LARK_DOCS:"lark-docs",DOC_SOURCE:"doc_source",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Ho=Object.freeze([Ft.CODEBASE_MEMORY]),et=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];F.helpers.inc||F.registerHelper("inc",o=>Number(o)+1);F.helpers.json||F.registerHelper("json",o=>JSON.stringify(o,null,2));F.helpers.eq||F.registerHelper("eq",(o,e)=>o===e);var L=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ce(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,a=l=>t&&typeof t.get=="function"?t.get(l):e?.[l];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let l=await this.customExecute(e);return typeof l=="object"&&l!==null&&l.success===!1?{success:!1,error:l.error||"Node execution failed",raw:l.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(l),raw:null}):{success:!0,output:l,raw:null}}catch(l){return I.error(`[workflow] node '${this.name}' failed: ${l.message}`),l.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(l.issues||l.errors,null,2)}`),{success:!1,error:l.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=F.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=a("_skillHints");n&&(s=`${n}
33
33
 
34
- ${n}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Ae(d,K);if(st(l)){let m=JSON.parse(nt(l,"utf-8"));m.currentNode=this.name,Te(l,JSON.stringify(m,null,2),"utf-8")}let c=Ae(d,"..",K);if(st(c))try{let m=JSON.parse(nt(c,"utf-8"));m.currentNode=this.name,Te(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let p=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},S=this.config.agent??m[this.name]??null,_={state:r()};S&&(_.preferredAgent=S);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let f=await E(n,_,v),h,y;if(typeof f=="string"?(h=f,y=null):f.structured?(h=f.raw||JSON.stringify(f.structured,null,2),y=f.structured):(h=f.raw||JSON.stringify(f,null,2),y=f.extracted||null),d)try{let g=Ae(d,this.name,"raw_stream_output.txt");qt(Vt(g),{recursive:!0}),Te(g,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(g){I.debug(`[workflow] could not save raw output: ${g.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let g=y;if(typeof this.onComplete=="function")try{g=await this.onComplete(r(),y)}catch($){I.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:g,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:h}),raw:h}}catch(g){throw new Error(`onComplete failed: ${g.message}`,{cause:g})}if(this.parser){let g=this.parser.parse(h);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(g,null,2)}`),O.step("Output parsed"),{success:!0,output:g,raw:h}}return{success:!0,output:h,raw:h}}catch(c){p=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}};W();W();import{mkdirSync as eo,existsSync as J,statSync as pt,readdirSync as ft,rmSync as to}from"node:fs";import{spawn as dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as oo}from"node:url";import{AsyncLocalStorage as Xt}from"node:async_hooks";var ve=new Xt;function oe(){let o=ve.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function it(o,e){let t=ve.getStore()||oe(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return ve.run(r,e)}var ke=new Map,xe=new Map,at=new Map;function ct(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ke.set(o,e),xe.set(o,"ready"),at.set(o,{...t,cachedAt:Date.now()})}function lt(o,e){xe.set(o,"failed"),at.set(o,{error:e?.message||String(e),failedAt:Date.now()}),ke.delete(o)}function ut(o){return xe.get(o)==="ready"?ke.get(o):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ro(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function no(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!t||!r||!a)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:a}}async function so({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(n){throw new N("network",`begin fetch failed: ${n.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let n=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(r.status===429){let n=a?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=n,s}if(r.status===400&&a?.validationErrors){let n=new Error(`Sub-graph rejected input: ${a?.error||a?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=a.validationErrors,n.missing=a.missing,n}throw new N("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function H({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function io(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;eo(e,{recursive:!0});let a=U(e,".lock"),n=!1;try{let{openSync:s,closeSync:i}=await import("node:fs"),u=s(a,"wx");i(u),n=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!n){let s=Date.now()+3e4;for(;Date.now()<s;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let p=dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(l.stdin);let c,m,S=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};p.on("close",_=>{c=_,S()}),l.on("close",_=>{m=_,S()}),p.on("error",d),l.on("error",d)});let{writeFileSync:s,unlinkSync:i}=await import("node:fs");s(t,"");try{i(a)}catch{}}catch(s){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new N("bundle-extract-failed",s.message)}}async function ao(o){let e=U(o,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(oo(e).href)}catch(a){throw new N("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=t.default||Object.values(t).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new N("entry-class-missing","no buildGraph() class export found");return r}async function ht(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=no()}catch($){throw $}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let a=await so({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:n,runtimeTag:s,bundlePresignedUrl:i,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:p,bundleReady:l,nodeConfigs:c}=a,m=ro();if(s&&s!==m)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${m} vs ${s}`);if(!l||!i)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new N("no-bundle","workflow bundle not built yet");let S=ut(o);if(!S){let $=U(pe,`${p}@${d||"0"}`);try{await io(i,$);try{lo()}catch{}}catch(b){throw b.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{S=await ao($),ct(o,S,{workflowUuid:p,version:d,runtimeTag:s,cacheDir:$})}catch(b){throw lt(o,b),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let _=Date.now(),E=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph(),f=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,h={...e.input||{},...f?{nodeConfigs:c}:{}},y,g;try{y=await it({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>E.run(e.parentAgent,h,{signal:e.signal})),g=y&&typeof y=="object"&&"state"in y?y.state:y}catch($){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:$.message,code:$.code||"CHILD_THREW",stack:$.stack},durationMs:Date.now()-_}}),$}if(y&&typeof y=="object"&&y.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-_}});let $=new Error(`Sub-graph '${o}' canceled by parent abort`);throw $.code="SUBGRAPH_CANCELED",$.subgraphJobId=n,$}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-_}}),{finalState:g,executionId:n}}function co(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),a;try{a=pt(r)}catch{continue}if(a.isDirectory()){let n;try{n=ft(r)}catch{continue}for(let s of n)t.push(U(r,s))}else e+=a.size}return e}function lo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=ft(pe),t=[],r=0;for(let i of e){let u=U(pe,i),d;try{d=pt(u)}catch{continue}let p=d.isDirectory()?co(u):d.size;r+=p,t.push({name:i,full:u,size:p,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,u)=>i.mtimeMs-u.mtimeMs);let a=Math.floor(o*.7),n=0,s=0;for(let i of t){if(r-n<=a)break;if(!J(U(i.full,".lock")))try{to(i.full,{recursive:!0,force:!0}),n+=i.size,s+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:n,totalBytes:r-n}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var uo=2e3,po=600*1e3,fo=new Set(["completed","failed","canceled","timeout"]);function ho(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function go(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function mo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function So(){return process.env.EXECUTION_ID||null}function gt(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function mt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await ht(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),g=gt(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),g}catch(y){if(y instanceof N||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let a=ho(),n=go(),s=mo(),i=So(),u=`${a}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(d)});if(!p.ok){let y=null,g="";try{y=await p.json(),g=y?.error||y?.message||JSON.stringify(y)}catch{g=await p.text().catch(()=>"")}if(p.status===429){let b=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${b.used??"?"}/${b.limit??"?"} on plan ${b.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=b,R}if(p.status===400){let b=new Error(`Sub-graph '${o}' rejected input: ${g}`);throw b.code="SUBGRAPH_INVALID_INPUT",b.status=400,b.subgraph=o,b.validationErrors=y?.validationErrors||null,b.missing=y?.missing||null,b}let $=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${g}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=p.status,$.subgraph=o,$}let l=await p.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:po,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:uo,_=`${a}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,E="accepted",f=0;for(;Date.now()<v;){await new Promise(b=>setTimeout(b,S)),f+=1;let y=await fetch(_,{headers:{Authorization:`Bearer ${s}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let g=await y.json(),$=g?.data||g?.execution||g;if(E=$?.status||E,fo.has(E)){if(E!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${E}'`);throw w.subgraphJobId=c,w.subgraphStatus=E,w}let b=$?.finalState||$?.state||{},R=gt(b,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${f} polls`),R}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${E})`);throw h.subgraphJobId=c,h.subgraphStatus=E,h}import{existsSync as St,readFileSync as yo}from"node:fs";import{join as Oe,dirname as yt}from"node:path";var fe=class{static async loadContext(e,t,r={}){let a={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=yt(Oe(t,e));for(let u of n){let d=await this.findAndMergeContextFiles(u,i,t);if(d){let p=u.replace(/\.[^.]+$/,"").toLowerCase();a[p]=d}}}let s=r.discovery||{};for(let[i,u]of Object.entries(s))try{let d=Oe(t,u);St(d)&&(a[i]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${i}' from '${u}': ${d.message}`)}return a}static async findAndMergeContextFiles(e,t,r){let a=[],n=t;for(;n.startsWith(r);){let s=Oe(n,e);if(St(s))try{a.unshift(await this.loadFile(s))}catch(u){console.warn(`[workflow] could not load ${e} from ${s}: ${u.message}`)}let i=yt(n);if(i===n)break;n=i}return a.length===0?null:a.every(s=>typeof s=="string")?a.join(`
34
+ ${s}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Te(d,K);if(st(l)){let m=JSON.parse(nt(l,"utf-8"));m.currentNode=this.name,ve(l,JSON.stringify(m,null,2),"utf-8")}let c=Te(d,"..",K);if(st(c))try{let m=JSON.parse(nt(c,"utf-8"));m.currentNode=this.name,ve(c,JSON.stringify(m,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let h=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let c=r().config||{},m=c.agents||{},S=this.config.agent??m[this.name]??null,_={state:r()};S&&(_.preferredAgent=S);let v={workspace:u,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let g=await E(s,_,v),f,y;if(typeof g=="string"?(f=g,y=null):g.structured?(f=g.raw||JSON.stringify(g.structured,null,2),y=g.structured):(f=g.raw||JSON.stringify(g,null,2),y=g.extracted||null),d)try{let p=Te(d,this.name,"raw_stream_output.txt");Xt(Qt(p),{recursive:!0}),ve(p,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),y)}catch(b){I.warn(`[workflow] onComplete hook failed: ${b.message}`)}return{success:!0,output:p,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:f}),raw:f}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(f);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),O.step("Output parsed"),{success:!0,output:p,raw:f}}return{success:!0,output:f,raw:f}}catch(c){h=c,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:h.message,raw:null}}};W();W();import{mkdirSync as oo,existsSync as J,statSync as ht,readdirSync as gt,rmSync as ro}from"node:fs";import{spawn as dt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as no}from"node:url";import{AsyncLocalStorage as so}from"node:async_hooks";import{AsyncLocalStorage as eo}from"node:async_hooks";var Ae=new eo;function oe(){let o=Ae.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function it(o,e){let t=Ae.getStore()||oe(),r=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Ae.run(r,e)}var ke=new Map,xe=new Map,at=new Map;function ct(o,e,t={}){if(!o||typeof o!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");ke.set(o,e),xe.set(o,"ready"),at.set(o,{...t,cachedAt:Date.now()})}function lt(o,e){xe.set(o,"failed"),at.set(o,{error:e?.message||String(e),failedAt:Date.now()}),ke.delete(o)}function ut(o){return xe.get(o)==="ready"?ke.get(o):null}var pe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function io(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}},pt=new so,ft=Promise.resolve();async function ao(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,i])=>typeof n=="string"&&n&&typeof i=="string"):[];if(t.length===0)return e();let r=pt.getStore()===!0,a=null;if(!r){let n=ft;ft=new Promise(i=>{a=i}),await n}let s=new Map;try{for(let[n,i]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=i;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await pt.run(!0,e)}finally{for(let[n,i]of s)i===void 0?delete process.env[n]:process.env[n]=i;a&&a()}}function co(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,a=process.env.PROJECT_API_TOKEN;if(!t||!r||!a)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:a}}async function lo({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new N("network",`begin fetch failed: ${s.message}`)}let a=null;try{a=await r.json()}catch{}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=a?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&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 N("begin-status",`begin returned ${r.status}`)}return a?.data||a}async function H({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function uo(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;oo(e,{recursive:!0});let a=U(e,".lock"),s=!1;try{let{openSync:n,closeSync:i}=await import("node:fs"),u=n(a,"wx");i(u),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((u,d)=>{let h=dt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),l=dt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});h.stdout.pipe(l.stdin);let c,m,S=()=>{if(c!==void 0&&m!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(m!==0)return d(new Error(`tar exited ${m}`));u()}};h.on("close",_=>{c=_,S()}),l.on("close",_=>{m=_,S()}),h.on("error",d),l.on("error",d)});let{writeFileSync:n,unlinkSync:i}=await import("node:fs");n(t,"");try{i(a)}catch{}}catch(n){try{let{unlinkSync:i}=await import("node:fs");i(a)}catch{}throw new N("bundle-extract-failed",n.message)}}async function po(o){let e=U(o,"graph.mjs");if(!J(e))throw new N("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(no(e).href)}catch(a){throw new N("import-failed",`${a?.code||a?.name||"unknown"}: ${a.message}`)}let r=t.default||Object.values(t).find(a=>typeof a=="function"&&a.prototype?.buildGraph);if(!r)throw new N("entry-class-missing","no buildGraph() class export found");return r}async function mt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=oe(),r;try{r=co()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let a=await lo({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:i,sourcesPresignedUrl:u,workflowVersion:d,workflowUuid:h,bundleReady:l,nodeConfigs:c}=a,m=io();if(n&&n!==m)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${m} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${m} vs ${n}`);if(!l||!i)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new N("no-bundle","workflow bundle not built yet");let S=ut(o);if(!S){let p=U(pe,`${h}@${d||"0"}`);try{await uo(i,p);try{ho()}catch{}}catch(b){throw b.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason}}}),b}try{S=await po(p),ct(o,S,{workflowUuid:h,version:d,runtimeTag:n,cacheDir:p})}catch(b){throw lt(o,b),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:b.message,code:b.reason||"IMPORT_FAILED"}}}),b.fallback?b:new N("import-failed",b.message)}}let _=Date.now(),v=a.env&&typeof a.env=="object"&&!Array.isArray(a.env)?a.env:null,E=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,g={...e.input||{},...E?{nodeConfigs:c}:{}},f,y;try{f=await ao(v,async()=>{let b=await(typeof S=="function"&&S.prototype?.buildGraph?new S:S).buildGraph();return it({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>b.run(e.parentAgent,g,{signal:e.signal}))}),y=f&&typeof f=="object"&&"state"in f?f.state:f}catch(p){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-_}}),p}if(f&&typeof f=="object"&&f.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:y,durationMs:Date.now()-_}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-_}}),{finalState:y,executionId:s}}function fo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),a;try{a=ht(r)}catch{continue}if(a.isDirectory()){let s;try{s=gt(r)}catch{continue}for(let n of s)t.push(U(r,n))}else e+=a.size}return e}function ho({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(pe))return{evicted:0,freedBytes:0};let e=gt(pe),t=[],r=0;for(let i of e){let u=U(pe,i),d;try{d=ht(u)}catch{continue}let h=d.isDirectory()?fo(u):d.size;r+=h,t.push({name:i,full:u,size:h,mtimeMs:d.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,u)=>i.mtimeMs-u.mtimeMs);let a=Math.floor(o*.7),s=0,n=0;for(let i of t){if(r-s<=a)break;if(!J(U(i.full,".lock")))try{ro(i.full,{recursive:!0,force:!0}),s+=i.size,n+=1}catch(u){I.debug(`[sub-graph cache] evict skip ${i.name}: ${u.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var go=2e3,mo=600*1e3,So=new Set(["completed","failed","canceled","timeout"]);function yo(){let o=process.env.PROGRESS_API_URL;if(!o)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return o.replace(/\/executions\/?$/,"")}function wo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function _o(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Io(){return process.env.EXECUTION_ID||null}function St(o,e){return e==null?o:typeof e=="function"?e(o):typeof e=="string"?e.split(".").reduce((t,r)=>t==null?t:t[r],o):o}async function yt(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=oe(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await mt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=St(y,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),p}catch(y){if(y instanceof N||y?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let a=yo(),s=wo(),n=_o(),i=Io(),u=`${a}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let h=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(d)});if(!h.ok){let y=null,p="";try{y=await h.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await h.text().catch(()=>"")}if(h.status===429){let A=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=A,R}if(h.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=y?.validationErrors||null,A.missing=y?.missing||null,A}let b=new Error(`Sub-graph '${o}' trigger rejected (${h.status}): ${p}`);throw b.code="SUBGRAPH_TRIGGER_FAILED",b.status=h.status,b.subgraph=o,b}let l=await h.json(),c=l?.data?.jobId||l?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let m=Number.isFinite(e.timeoutMs)?e.timeoutMs:mo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:go,_=`${a}/executions/${encodeURIComponent(c)}`,v=Date.now()+m,E="accepted",g=0;for(;Date.now()<v;){await new Promise(A=>setTimeout(A,S)),g+=1;let y=await fetch(_,{headers:{Authorization:`Bearer ${n}`}});if(!y.ok){if(y.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),b=p?.data||p?.execution||p;if(E=b?.status||E,So.has(E)){if(E!=="completed"){let w=new Error(`Sub-graph '${o}' (${c}) ended in status '${E}'`);throw w.subgraphJobId=c,w.subgraphStatus=E,w}let A=b?.finalState||b?.state||{},R=St(A,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${g} polls`),R}}let f=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(m/1e3)}s (last status: ${E})`);throw f.subgraphJobId=c,f.subgraphStatus=E,f}import{existsSync as wt,readFileSync as Eo}from"node:fs";import{join as Oe,dirname as _t}from"node:path";var fe=class{static async loadContext(e,t,r={}){let a={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=_t(Oe(t,e));for(let u of s){let d=await this.findAndMergeContextFiles(u,i,t);if(d){let h=u.replace(/\.[^.]+$/,"").toLowerCase();a[h]=d}}}let n=r.discovery||{};for(let[i,u]of Object.entries(n))try{let d=Oe(t,u);wt(d)&&(a[i]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${i}' from '${u}': ${d.message}`)}return a}static async findAndMergeContextFiles(e,t,r){let a=[],s=t;for(;s.startsWith(r);){let n=Oe(s,e);if(wt(n))try{a.unshift(await this.loadFile(n))}catch(u){console.warn(`[workflow] could not load ${e} from ${n}: ${u.message}`)}let i=_t(s);if(i===s)break;s=i}return a.length===0?null:a.every(n=>typeof n=="string")?a.join(`
35
35
 
36
36
  ---
37
37
 
38
- `):a.every(s=>typeof s=="object")?Object.assign({},...a):a[a.length-1]}static async loadFile(e){let t=yo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),a=await import(r(e).href);return a.default||a}return t}};import{mkdirSync as It,existsSync as Ne,writeFileSync as wt,unlinkSync as wo}from"node:fs";import{join as Y,resolve as Et}from"node:path";import{config as _o}from"dotenv";import{zodToJsonSchema as _t}from"zod-to-json-schema";import{z as he}from"zod";import Io from"handlebars";function Eo({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:a}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${s} sessionId=${e} source=${r} mkdir=${a?"yes":"no"} path=${t}`;if(console.log(i),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let p=(new Error("session trace").stack||"").split(`
38
+ `):a.every(n=>typeof n=="object")?Object.assign({},...a):a[a.length-1]}static async loadFile(e){let t=Eo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),a=await import(r(e).href);return a.default||a}return t}};import{mkdirSync as bt,existsSync as Ne,writeFileSync as It,unlinkSync as bo}from"node:fs";import{join as Y,resolve as $t}from"node:path";import{config as $o}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import vo from"handlebars";function To({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:a}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${a?"yes":"no"} path=${t}`;if(console.log(i),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
39
39
  `).slice(2,14).join(`
40
40
  `);console.log(`[zibby:session] stack (${o}):
41
- ${p}`)}}function bo(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function $o(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return Et(String(e).trim())}catch{return String(e).trim()}}function To(){bo()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Ao({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 vo(o={}){let e=et.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function ko({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,n=t.sessionTimestamp,s="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=Et(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,s="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,s="config.sessionId"):(i=vo(e),s="generated")}n=n??Date.now();let p=e.paths?.output||ue;a=Y(o,p,Xe,i)}let u=!Ne(a);return u&&It(a,{recursive:!0}),(u||s!=="initialState.sessionPath")&&Eo({traceFrom:r,sessionId:i,sessionPath:a,idSource:s,mkdirFresh:u}),Ao({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:n}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let s=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:s.workflow,retries:s.retries,onComplete:s.onComplete,execute:async d=>{let p=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof s.input=="function"?l=s.input(p):s.input&&typeof s.input=="object"?l=s.input:l={},mt(s.workflow,{input:l,async:s.async===!0,conversationId:typeof s.conversationId=="function"?s.conversationId(p):s.conversationId,output:s.output,timeoutMs:s.timeoutMs,pollIntervalMs:s.pollIntervalMs,signal:p?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,n=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return n.name=e,this.nodes.set(e,n),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,n){let s=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=s;s=()=>u(t,d,a,n)}return s()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let g=c.prompt({});typeof g=="string"&&g.trim()&&(S.prompt=g,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let g=null;if(typeof he?.toJSONSchema=="function")try{g=he.toJSONSchema(c.outputSchema)}catch{}if(!g)try{g=_t(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let f=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;f&&f.length>0&&(S.skills=[...f]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(S.plugins=h.map(g=>g&&typeof g=="object"?{...g}:g));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,f=l;if(!E){let h=`${l}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),r.push({source:l,target:h}),f=h}for(let h of S){let y={source:f,target:h,data:{conditionalCode:m}};_[h]&&(y.label=_[h]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return _t(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let n=0;for(let l of r)if(l.target==="END"){n+=1;let c=`END__${n}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){n+=1;let c=`END__${n}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let s=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),p=a(this.contextSchema);return{nodes:s,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:p}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),n=new Map(e.map(l=>[l.id,0])),s=new Map(e.map(l=>[l.id,[]]));for(let l of t)s.has(l.source)&&n.has(l.target)&&(s.get(l.source).push(l.target),n.set(l.target,n.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>n.get(l)===0),p=[];for(;p.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),p.push(a.get(l));for(let c of s.get(l)||[])n.set(c,n.get(c)-1),n.get(c)<=0&&!i.has(c)&&d.push(c)}return p}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=n.exec(r))!==null;){let d=s[2]!==void 0?s[2]:s[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=d.exec(r))!==null;)u.add(p[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},n=e.required||[];for(let[s,i]of Object.entries(a)){let u=t?`${t}.${s}`:s;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(s),optional:!n.includes(s)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,n]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${a}: ${n}`);else if(Array.isArray(n)){let s=n.length,i=n.filter(d=>d?.passed===!0).length,u=n.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${s} passed${s-i?`, ${s-i} failed`:""}`:`${a}: ${s} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let n=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,s=t.cwd||process.cwd();_o({path:Y(s,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let T=Y(s,".zibby.config.js");Ne(T)&&(i=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let T=i?.agent;T?.provider?u=T.provider:T?.gemini?u="gemini":T?.claude?u="claude":T?.cursor?u="cursor":T?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},p=this._runtimeSchema();if(p){let T=p.safeParse(t);if(!T.success){let P=T.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=$o(),c=t.sessionPath||l;c||To();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=ko({cwd:s,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",s,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let f=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),g=i.skills&&typeof i.skills=="object"?i.skills:{},$=Object.values(g).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),b=T=>{for(let P of $)if(P.id===T)return P;return y(T)},R=new Set;for(let[,T]of this.nodes)for(let P of T.config?.skills||[])R.add(P);for(let T of R){let P=b(T);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&h.set(T,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,vt=0;try{for(;w&&w!=="END";){if(++vt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{wo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
42
- \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let Me=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:w,createdAt:new Date().toISOString(),config:f.get("config")}),kt=Y(m,K);wt(kt,Me,"utf-8");let De=f.get("config")?.paths?.output||ue,xt=Y(s,De,K);It(Y(s,De),{recursive:!0});try{wt(xt,Me,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:s,sessionPath:m,sessionId:_,outputBase:f.get("config")?.paths?.output||ue,currentNode:w})}catch{}let Ot=(this.resolvedToolsMap||{})[w]||null;f.set("_currentNodeTools",Ot);let Nt=f.get("nodeConfigs")||{};f.set("_currentNodeConfig",Nt[w]||{}),O.nodeStart(w);let Le=Date.now(),ne=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=k.invokeAgent}let Pt=this._invokeAgent,Se={},Ct=C.config?.skills||[];for(let k of Ct){let B=b(k);if(typeof B?.invokeAgentOptions=="function")try{let A=B.invokeAgentOptions(f.getAll(),{agentType:f.get("agentType"),nodeName:w});A&&typeof A=="object"&&(Se={...Se,...A})}catch(A){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${A.message}`)}}let Ue=async(k,B,A={})=>{let M=Pt(k,B,{...Se,...A,signal:a.signal});return M.catch(()=>{}),a.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let j=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${n}ms`);V.name="AbortError",z(V)},n)};a.signal.addEventListener("abort",j,{once:!0})})])},Rt=async(k={},B={})=>{let A=B.prompt||"";if(ne){let M=this._compiledPrompts.get(w);M||(M=Io.compile(ne,{noEscape:!0}),this._compiledPrompts.set(w,M));try{A=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!A)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Ue(A,{state:f.getAll(),images:B.images||[]},{model:B.model||f.get("model"),workspace:f.get("workspace"),schema:B.schema,...B,signal:a.signal})},We=f.getAll(),Bt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Bt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ge={...We,state:f,invokeAgent:Rt,_coreInvokeAgent:Ue,agent:e,nodeId:w,promptTemplate:ne,getPromptTemplate:()=>ne};try{let k=(C.config?.skills||[]).map(j=>h.get(j)).filter(Boolean),B=[...this.middleware,...k],A;B.length>0?A=await this._composeMiddleware(B,w,async()=>C.execute(Ge,f),f.getAll(),f):A=await C.execute(Ge,f);let M=Date.now()-Le;if(re.push({node:w,success:A.success,duration:M,timestamp:new Date().toISOString()}),!A.success){if(a.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:f.getAll(),executionLog:re,stoppedExternally:!0};f.append("errors",{node:w,error:A.error});let j=C.config?.retries||0,V=`${w}_retries`,se=f.getAll()[V]||0;if(se<j){O.stepInfo(`Retrying (attempt ${se+1}/${j})`),f.update({[V]:se+1,[`${w}_raw`]:A.raw});continue}throw O.nodeFailed(w,A.error,{duration:M}),new Error(`Node '${w}' failed after ${se} attempts: ${A.error}`)}f.update({[w]:A.output});let Z=this._summarizeNodeOutput(w,A.output);O.nodeComplete(w,{duration:M,details:Z});let z=this.edges.get(w);if(!z)w="END";else if(z.conditional){let j=z.routes(f.getAll());O.route(w,j),w=j}else w=z}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Le}),f.set("failed",!0),f.set("failedAt",w),k}}O.graphComplete();let T={success:!0,state:f.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete(T),T}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(T){console.warn(`[workflow] agent.cleanup() failed: ${T.message}`)}}}};var Pe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Pe]||(globalThis[Pe]=new Map);var Ce=globalThis[Pe];function xo(o,e){Ce.set(o,e)}function bt(o){return Ce.get(o)}function Re(o){return Ce.has(o)}xo("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let a=e.extraPromptInstructions||"Execute the task based on the current state.",n=Oo(a,t),s=await r(n,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:o},raw:typeof s=="string"?s:s.raw}}})});function Oo(o,e){let t=/@([\w.]+)/g,r=new Set,a;for(;(a=t.exec(o))!==null;)r.add(a[1]);if(r.size===0)return o;let n=[],s=new Set;for(let i of r){let u=i.split(".")[0];if(s.has(u))continue;let d=i.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let p=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=i.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());n.push(`## ${l}
43
- ${p}`),i.includes(".")||s.add(u)}return n.length===0?o:`${o}
41
+ ${h}`)}}function Ao(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function ko(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return $t(String(e).trim())}catch{return String(e).trim()}}function xo(){Ao()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Oo({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 No(o={}){let e=et.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function Po({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=$t(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,n="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,n="config.sessionId"):(i=No(e),n="generated")}s=s??Date.now();let h=e.paths?.output||ue;a=Y(o,h,Xe,i)}let u=!Ne(a);return u&&bt(a,{recursive:!0}),(u||n!=="initialState.sessionPath")&&To({traceFrom:r,sessionId:i,sessionPath:a,idSource:n,mkdirFresh:u}),Oo({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:s}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},yt(n.workflow,{input:l,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,s){let n=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=n;n=()=>u(t,d,a,s)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Et(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(S.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(S.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!E){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of S){let y={source:g,target:f,data:{conditionalCode:m}};_[f]&&(y.label=_[f]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return Et(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of r)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),h=a(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&s.has(l.target)&&(n.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>s.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),h.push(a.get(l));for(let c of n.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!i.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},s=e.required||[];for(let[n,i]of Object.entries(a)){let u=t?`${t}.${n}`:n;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(n),optional:!s.includes(n)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,s]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${a}: ${s}`);else if(Array.isArray(s)){let n=s.length,i=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${n} passed${n-i?`, ${n-i} failed`:""}`:`${a}: ${n} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();$o({path:Y(n,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let $=Y(n,".zibby.config.js");Ne($)&&(i=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let $=i?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let P=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=ko(),c=t.sessionPath||l;c||xo();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=Po({cwd:n,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),p=i.skills&&typeof i.skills=="object"?i.skills:{},b=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),A=$=>{for(let P of b)if(P.id===$)return P;return y($)},R=new Set;for(let[,$]of this.nodes)for(let P of $.config?.skills||[])R.add(P);for(let $ of R){let P=A($);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,xt=0;try{for(;w&&w!=="END";){if(++xt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{bo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
42
+ \u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let Me=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:w,createdAt:new Date().toISOString(),config:g.get("config")}),Ot=Y(m,K);It(Ot,Me,"utf-8");let De=g.get("config")?.paths?.output||ue,Nt=Y(n,De,K);bt(Y(n,De),{recursive:!0});try{It(Nt,Me,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:n,sessionPath:m,sessionId:_,outputBase:g.get("config")?.paths?.output||ue,currentNode:w})}catch{}let Pt=(this.resolvedToolsMap||{})[w]||null;g.set("_currentNodeTools",Pt);let Ct=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",Ct[w]||{}),O.nodeStart(w);let Le=Date.now(),ne=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,Se={},Bt=C.config?.skills||[];for(let k of Bt){let B=A(k);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Ue=async(k,B,T={})=>{let M=Rt(k,B,{...Se,...T,signal:a.signal});return M.catch(()=>{}),a.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let j=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);V.name="AbortError",z(V)},s)};a.signal.addEventListener("abort",j,{once:!0})})])},Mt=async(k={},B={})=>{let T=B.prompt||"";if(ne){let M=this._compiledPrompts.get(w);M||(M=vo.compile(ne,{noEscape:!0}),this._compiledPrompts.set(w,M));try{T=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Ue(T,{state:g.getAll(),images:B.images||[]},{model:B.model||g.get("model"),workspace:g.get("workspace"),schema:B.schema,...B,signal:a.signal})},We=g.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Dt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ge={...We,state:g,invokeAgent:Mt,_coreInvokeAgent:Ue,agent:e,nodeId:w,promptTemplate:ne,getPromptTemplate:()=>ne};try{let k=(C.config?.skills||[]).map(j=>f.get(j)).filter(Boolean),B=[...this.middleware,...k],T;B.length>0?T=await this._composeMiddleware(B,w,async()=>C.execute(Ge,g),g.getAll(),g):T=await C.execute(Ge,g);let M=Date.now()-Le;if(re.push({node:w,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(a.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};g.append("errors",{node:w,error:T.error});let j=C.config?.retries||0,V=`${w}_retries`,se=g.getAll()[V]||0;if(se<j){O.stepInfo(`Retrying (attempt ${se+1}/${j})`),g.update({[V]:se+1,[`${w}_raw`]:T.raw});continue}throw O.nodeFailed(w,T.error,{duration:M}),new Error(`Node '${w}' failed after ${se} attempts: ${T.error}`)}g.update({[w]:T.output});let Z=this._summarizeNodeOutput(w,T.output);O.nodeComplete(w,{duration:M,details:Z});let z=this.edges.get(w);if(!z)w="END";else if(z.conditional){let j=z.routes(g.getAll());O.route(w,j),w=j}else w=z}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Le}),g.set("failed",!0),g.set("failedAt",w),k}}O.graphComplete();let $={success:!0,state:g.getAll(),executionLog:re};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 Pe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Pe]||(globalThis[Pe]=new Map);var Ce=globalThis[Pe];function Co(o,e){Ce.set(o,e)}function vt(o){return Ce.get(o)}function Re(o){return Ce.has(o)}Co("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let a=e.extraPromptInstructions||"Execute the task based on the current state.",s=Ro(a,t),n=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Ro(o,e){let t=/@([\w.]+)/g,r=new Set,a;for(;(a=t.exec(o))!==null;)r.add(a[1]);if(r.size===0)return o;let s=[],n=new Set;for(let i of r){let u=i.split(".")[0];if(n.has(u))continue;let d=i.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=i.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
43
+ ${h}`),i.includes(".")||n.add(u)}return s.length===0?o:`${o}
44
44
 
45
45
  ---
46
46
  # Referenced Context
47
47
 
48
- ${n.join(`
48
+ ${s.join(`
49
49
 
50
- `)}`}de();W();var No={};function Tt(o,e){if(Array.isArray(e))return $t(e);let t=No[o];return!t||t.length===0?null:$t(t)}function $t(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let a of o){let n=Q(a);if(!n){I.warn(`[workflow] unknown skill "${a}" \u2014 skipping`);continue}r.push(a);for(let s of n.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!t[n.serverName])if(typeof n.resolve=="function"){let s=n.resolve();s&&(t[n.serverName]={...s,toolPrefix:a})}else{let s={};for(let i of n.envKeys||[]){let u=process.env[i];u&&(s[i]=u)}t[n.serverName]={command:n.command,args:[...n.args||[]],env:s,toolPrefix:a}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}W();function jr(o,e={}){let{nodes:t,edges:r,nodeConfigs:a={}}=o;if(!Array.isArray(t)||t.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(r))throw new D("Graph edges must be an array");let n=new ge(e);e.stateSchema&&n.setStateSchema(e.stateSchema);let s=new Set,i=new Map,u={};for(let c of t){let m=me(c);i.set(c.id,{...c,resolvedType:m}),m==="decision"&&s.add(c.id)}for(let[c,m]of i){if(s.has(c))continue;let S=m.resolvedType,_=a[c]||{},v=Tt(S,_.tools);v&&(u[c]=v);let E={};_.prompt&&(E.prompt=_.prompt);let f=Re(S);if(I.debug(`[workflow] compiler: node "${c}" type="${S}" registered=${f}`),_.customCode&&!f)n.addNode(c,At(c,_.customCode,_),E),n.setNodeType(c,S);else if(f){let h=bt(S);h.factory?n.addNode(c,h.create(c,{..._,resolvedTools:v}),E):n.addNode(c,h,E),n.setNodeType(c,S)}else if(_.executeCode)n.addNode(c,At(c,_.executeCode,_),E),n.setNodeType(c,S);else throw new D(`Unknown node type "${S}" for node "${c}". Did you forget to register it?`)}n.resolvedToolsMap=u;let d=new Set;for(let c of r)s.has(c.target)||d.add(c.target);let p=t.find(c=>!s.has(c.id)&&!d.has(c.id));if(!p)throw new D("Could not determine entry point: no node without incoming edges found");n.setEntryPoint(p.id);let l=Po(r,"source");for(let c of r)if(!s.has(c.source))if(s.has(c.target)){let m=c.target,S=l.get(m)||[];if(S.length===0)throw new D(`Decision node "${m}" has no outgoing edges`);let _=Co(m,S,s);n.addConditionalEdges(c.source,_)}else n.addEdge(c.source,c.target);return n}function Lr(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 i of o.nodes){let u=me(i);if(u==="decision"||Re(u))continue;let d=t[i.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${i.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(i=>i.id));for(let i of o.edges)r.has(i.source)||e.push(`Edge references unknown source node "${i.source}"`),r.has(i.target)||e.push(`Edge references unknown target node "${i.target}"`);let a=new Set(o.nodes.filter(i=>me(i)==="decision").map(i=>i.id)),n=new Set;for(let i of o.edges)a.has(i.target)||n.add(i.target);let s=o.nodes.filter(i=>!a.has(i.id)&&!n.has(i.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(i=>i.id).join(", ")}`);for(let i of a){let u=o.edges.filter(p=>p.source===i);u.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),u.some(p=>p.data?.conditionalCode||p.conditionalCode)||e.push(`Decision node "${i}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Ur(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>me(e)!=="decision").map(e=>e.id)}function me(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Po(o,e){let t=new Map;for(let r of o){let a=r[e];t.has(a)||t.set(a,[]),t.get(a).push(r)}return t}function Co(o,e,t){let r=e.find(i=>i.data?.conditionalCode||i.conditionalCode);if(!r)throw new D(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let a=r.data?.conditionalCode||r.conditionalCode,n=new Set(e.map(i=>i.target).filter(i=>!t.has(i))),s;try{let u=new Function(`return (${a})`)();s=d=>{let p=u(d);return n.has(p)||I.warn(`[workflow] conditional route from "${o}" returned "${p}" which is not in valid targets: ${[...n].join(", ")}`),p}}catch(i){throw new D(`Failed to compile conditionalCode for "${o}": ${i.message}`)}return s}function At(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new D(`Failed to compile customCode for node "${o}": ${s.message}`)}let a=r(async(...s)=>{let{invokeAgent:i}=await Promise.resolve().then(()=>(te(),ee));return i(...s)},typeof ye<"u"?ye:void 0,console),n=null;return t.outputSchema&&(n=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:n,execute:async s=>{try{let i=await a(s);return typeof i=="object"&&"success"in i?i:{success:!0,output:i,raw:null}}catch(i){return{success:!1,error:i.message,raw:null}}}}}var D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{D as CompilationError,jr as compileGraph,Ur as extractSteps,Lr as validateGraphConfig};
50
+ `)}`}de();W();var Bo={};function At(o,e){if(Array.isArray(e))return Tt(e);let t=Bo[o];return!t||t.length===0?null:Tt(t)}function Tt(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let a of o){let s=Q(a);if(!s){I.warn(`[workflow] unknown skill "${a}" \u2014 skipping`);continue}r.push(a);for(let n of s.tools||[])e.push({name:n.name,description:n.description,input_schema:n.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let n=s.resolve();n&&(t[s.serverName]={...n,toolPrefix:a})}else{let n={};for(let i of s.envKeys||[]){let u=process.env[i];u&&(n[i]=u)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:n,toolPrefix:a}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}W();function Fr(o,e={}){let{nodes:t,edges:r,nodeConfigs:a={}}=o;if(!Array.isArray(t)||t.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(r))throw new D("Graph edges must be an array");let s=new ge(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let n=new Set,i=new Map,u={};for(let c of t){let m=me(c);i.set(c.id,{...c,resolvedType:m}),m==="decision"&&n.add(c.id)}for(let[c,m]of i){if(n.has(c))continue;let S=m.resolvedType,_=a[c]||{},v=At(S,_.tools);v&&(u[c]=v);let E={};_.prompt&&(E.prompt=_.prompt);let g=Re(S);if(I.debug(`[workflow] compiler: node "${c}" type="${S}" registered=${g}`),_.customCode&&!g)s.addNode(c,kt(c,_.customCode,_),E),s.setNodeType(c,S);else if(g){let f=vt(S);f.factory?s.addNode(c,f.create(c,{..._,resolvedTools:v}),E):s.addNode(c,f,E),s.setNodeType(c,S)}else if(_.executeCode)s.addNode(c,kt(c,_.executeCode,_),E),s.setNodeType(c,S);else throw new D(`Unknown node type "${S}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=u;let d=new Set;for(let c of r)n.has(c.target)||d.add(c.target);let h=t.find(c=>!n.has(c.id)&&!d.has(c.id));if(!h)throw new D("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(h.id);let l=Mo(r,"source");for(let c of r)if(!n.has(c.source))if(n.has(c.target)){let m=c.target,S=l.get(m)||[];if(S.length===0)throw new D(`Decision node "${m}" has no outgoing edges`);let _=Do(m,S,n);s.addConditionalEdges(c.source,_)}else s.addEdge(c.source,c.target);return s}function Hr(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 i of o.nodes){let u=me(i);if(u==="decision"||Re(u))continue;let d=t[i.id]||{};d.customCode||d.executeCode||e.push(`Unknown node type "${u}" for node "${i.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(i=>i.id));for(let i of o.edges)r.has(i.source)||e.push(`Edge references unknown source node "${i.source}"`),r.has(i.target)||e.push(`Edge references unknown target node "${i.target}"`);let a=new Set(o.nodes.filter(i=>me(i)==="decision").map(i=>i.id)),s=new Set;for(let i of o.edges)a.has(i.target)||s.add(i.target);let n=o.nodes.filter(i=>!a.has(i.id)&&!s.has(i.id));n.length===0?e.push("No entry point found (every node has incoming edges)"):n.length>1&&e.push(`Multiple entry points found: ${n.map(i=>i.id).join(", ")}`);for(let i of a){let u=o.edges.filter(h=>h.source===i);u.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),u.some(h=>h.data?.conditionalCode||h.conditionalCode)||e.push(`Decision node "${i}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Jr(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>me(e)!=="decision").map(e=>e.id)}function me(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Mo(o,e){let t=new Map;for(let r of o){let a=r[e];t.has(a)||t.set(a,[]),t.get(a).push(r)}return t}function Do(o,e,t){let r=e.find(i=>i.data?.conditionalCode||i.conditionalCode);if(!r)throw new D(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let a=r.data?.conditionalCode||r.conditionalCode,s=new Set(e.map(i=>i.target).filter(i=>!t.has(i))),n;try{let u=new Function(`return (${a})`)();n=d=>{let h=u(d);return s.has(h)||I.warn(`[workflow] conditional route from "${o}" returned "${h}" which is not in valid targets: ${[...s].join(", ")}`),h}}catch(i){throw new D(`Failed to compile conditionalCode for "${o}": ${i.message}`)}return n}function kt(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(n){throw new D(`Failed to compile customCode for node "${o}": ${n.message}`)}let a=r(async(...n)=>{let{invokeAgent:i}=await Promise.resolve().then(()=>(te(),ee));return i(...n)},typeof ye<"u"?ye:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async n=>{try{let i=await a(n);return typeof i=="object"&&"success"in i?i:{success:!0,output:i,raw:null}}catch(i){return{success:!1,error:i.message,raw:null}}}}}var D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};export{D as CompilationError,Fr as compileGraph,Jr as extractSteps,Hr as validateGraphConfig};