@zibby/agent-workflow 0.4.24 → 0.4.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -22
- package/dist/constants.d.ts +3 -0
- package/dist/constants.js +1 -1
- package/dist/graph-compiler.js +7 -7
- package/dist/graph.js +12 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -14
- package/dist/node.js +5 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,22 +43,22 @@ No setup step. The first command bootstraps `.zibby/workflows/` for you.
|
|
|
43
43
|
|
|
44
44
|
```bash
|
|
45
45
|
# 1. Generate a workflow — creates .zibby/workflows/my-pipeline/ + graph.mjs
|
|
46
|
-
npx @zibby/cli
|
|
46
|
+
npx @zibby/cli agent new my-pipeline
|
|
47
47
|
|
|
48
48
|
# 2. Run it locally — names are folder names, not cloud identifiers
|
|
49
|
-
npx @zibby/cli
|
|
49
|
+
npx @zibby/cli agent start my-pipeline
|
|
50
50
|
|
|
51
51
|
# 3. Ship it to Zibby Cloud (returns a UUID + caches it in .zibby-deploy.json)
|
|
52
52
|
npx @zibby/cli login
|
|
53
|
-
npx @zibby/cli
|
|
53
|
+
npx @zibby/cli agent deploy my-pipeline
|
|
54
54
|
|
|
55
55
|
# 4. Trigger a remote run by UUID. Tail the logs Heroku-style.
|
|
56
|
-
npx @zibby/cli
|
|
57
|
-
npx @zibby/cli
|
|
56
|
+
npx @zibby/cli agent trigger <uuid> # uuid printed by `deploy` or `agent list`
|
|
57
|
+
npx @zibby/cli agent logs -t
|
|
58
58
|
|
|
59
59
|
# 5. Manage the fleet
|
|
60
|
-
npx @zibby/cli
|
|
61
|
-
npx @zibby/cli
|
|
60
|
+
npx @zibby/cli agent list # local + deployed (shows UUIDs)
|
|
61
|
+
npx @zibby/cli agent delete <uuid> # tear one down
|
|
62
62
|
```
|
|
63
63
|
|
|
64
64
|
Prefer to install once instead of `npx` every time:
|
|
@@ -72,25 +72,23 @@ zibby --help
|
|
|
72
72
|
|
|
73
73
|
## The CLI: full workflow lifecycle
|
|
74
74
|
|
|
75
|
-
All workflow operations live under `zibby
|
|
75
|
+
All workflow operations live under `zibby agent <verb>` for consistency. The bare top-level forms (`zibby start`, `zibby deploy`, `zibby trigger`, `zibby logs`) are kept as backward-compat aliases.
|
|
76
76
|
|
|
77
77
|
| Command | What it does |
|
|
78
78
|
|---|---|
|
|
79
|
-
| `zibby
|
|
80
|
-
| `zibby
|
|
79
|
+
| `zibby agent new <name>` | **Generate** a new custom workflow under `.zibby/workflows/<name>/`. Auto-creates `.zibby/` if missing — no separate init step required. |
|
|
80
|
+
| `zibby agent start <name>` | Run a workflow **locally** with hot-reload (defaults to port 3848). Name = folder under `.zibby/workflows/`. |
|
|
81
81
|
| `zibby login` / `logout` / `status` | Cloud auth. |
|
|
82
|
-
| `zibby
|
|
83
|
-
| `zibby
|
|
84
|
-
| `zibby
|
|
85
|
-
| `zibby
|
|
86
|
-
| `zibby
|
|
87
|
-
| `zibby
|
|
82
|
+
| `zibby agent deploy [name]` | **Deploy** a workflow to Zibby Cloud (interactive picker if name omitted). |
|
|
83
|
+
| `zibby agent trigger <uuid>` | **Run** a deployed workflow in the cloud. UUID is canonical (names are local-only). Get UUIDs from `agent list` or the `deploy` output. |
|
|
84
|
+
| `zibby agent logs [jobId] -t` | Tail **logs** from a run, Heroku-style. `-t` to follow live. |
|
|
85
|
+
| `zibby agent list` | **List** local + deployed workflows. |
|
|
86
|
+
| `zibby agent download <uuid>` | **Pull** a deployed workflow back to local — edit + redeploy. |
|
|
87
|
+
| `zibby agent delete <uuid>` | **Delete** a deployed workflow. |
|
|
88
88
|
|
|
89
89
|
**Local** runs land in `.zibby/output/sessions/<id>/` with raw outputs, parsed JSON, and a JSONL execution log — replay-friendly. **Cloud** runs use the same on-disk format, fronted by the trigger/logs commands.
|
|
90
90
|
|
|
91
|
-
**Local vs cloud identity**: workflow folder names (`my-pipeline`) are *local* — used by `
|
|
92
|
-
|
|
93
|
-
The CLI also integrates with [Zibby Studio](https://zibby.dev) — a desktop UI for visualising live runs, pinning sessions, and stopping a workflow from a button.
|
|
91
|
+
**Local vs cloud identity**: workflow folder names (`my-pipeline`) are *local* — used by `agent new`, `agent start`, `agent deploy`. Cloud workflows are identified by **UUID** — used by `agent trigger`, `agent logs`, `agent download`, `agent delete`. After your first `deploy`, the UUID is cached in `.zibby/workflows/<name>/.zibby-deploy.json` (commit it to git so collaborators share the same canonical reference).
|
|
94
92
|
|
|
95
93
|
> 📋 **Full CLI cheat sheet** including `zibby init`, `zibby template list/add`, `zibby memory remote/cost/pull/push` (UI agent memory + team sync), and `zibby test` is in [`@zibby/cli`'s README](https://www.npmjs.com/package/@zibby/cli). Workflow commands above are the engine-relevant subset.
|
|
96
94
|
|
|
@@ -105,7 +103,7 @@ npm install @zibby/agent-workflow
|
|
|
105
103
|
```
|
|
106
104
|
|
|
107
105
|
```js
|
|
108
|
-
import {
|
|
106
|
+
import { Graph, AgentStrategy, registerStrategy } from '@zibby/agent-workflow';
|
|
109
107
|
import { z } from 'zod';
|
|
110
108
|
|
|
111
109
|
class MyAgent extends AgentStrategy {
|
|
@@ -120,7 +118,7 @@ registerStrategy(new MyAgent());
|
|
|
120
118
|
const Plan = z.object({ tasks: z.array(z.string()) });
|
|
121
119
|
const Done = z.object({ summary: z.string() });
|
|
122
120
|
|
|
123
|
-
const graph = new
|
|
121
|
+
const graph = new Graph()
|
|
124
122
|
.addNode('plan', { prompt: 'List 3 tasks for: {{goal}}', outputSchema: Plan })
|
|
125
123
|
.addNode('finish', { prompt: 'Summarise the work', outputSchema: Done })
|
|
126
124
|
.addEdge('plan', 'finish')
|
|
@@ -154,7 +152,7 @@ If you want to compose Claude Code + Cursor + Codex into one pipeline with struc
|
|
|
154
152
|
|
|
155
153
|
| Primitive | What it does |
|
|
156
154
|
|---|---|
|
|
157
|
-
| `
|
|
155
|
+
| `Graph` | The DAG. `addNode`, `addEdge`, `addConditionalEdges`, `setEntryPoint`. |
|
|
158
156
|
| `Node` | One agent invocation. Config: `prompt`, `outputSchema` (Zod), optional `agent`, `retries`, `skills`. |
|
|
159
157
|
| Sub-graph node | `addNode(name, { workflow: 'other-name', ... })` — dispatches another deployed workflow as a child. Sync (poll + merge) or async (`async: true`, fire-and-forget). See [Sub-graphs](#sub-graphs) below. |
|
|
160
158
|
| `AgentStrategy` | Abstract base. Implement `canHandle(ctx)` and `invoke(prompt, opts)`. |
|
package/dist/constants.d.ts
CHANGED
|
@@ -25,6 +25,7 @@ export namespace SKILLS {
|
|
|
25
25
|
let GIT_WRITE: string;
|
|
26
26
|
let SLACK: string;
|
|
27
27
|
let LARK: string;
|
|
28
|
+
let DISCORD: string;
|
|
28
29
|
let CHAT_NOTIFY: string;
|
|
29
30
|
let SENTRY: string;
|
|
30
31
|
let MEMORY: string;
|
|
@@ -40,6 +41,8 @@ export namespace SKILLS {
|
|
|
40
41
|
let CURSOR_ADMIN: string;
|
|
41
42
|
let NOTION: string;
|
|
42
43
|
let GOOGLE_DOCS: string;
|
|
44
|
+
let LARK_DOCS: string;
|
|
45
|
+
let DOC_SOURCE: string;
|
|
43
46
|
let LINEAR: string;
|
|
44
47
|
let PLANE: string;
|
|
45
48
|
let CODEBASE_MEMORY: string;
|
package/dist/constants.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=".zibby/output",t="sessions",E=".session-info.json",
|
|
1
|
+
var I=".zibby/output",t="sessions",E=".session-info.json",_=".zibby-stop",e="result.json",s="raw_stream_output.txt",O="events.json",o={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"},r=Object.freeze([o.CODEBASE_MEMORY]),n=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{n as CI_ENV_VARS,I as DEFAULT_OUTPUT_BASE,O as EVENTS_FILE,r as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,s as RAW_OUTPUT_FILE,e as RESULT_FILE,t as SESSIONS_DIR,E as SESSION_INFO_FILE,o as SKILLS,_ as STOP_REQUEST_FILE};
|
package/dist/graph-compiler.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Dt=Object.defineProperty;var we=(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 ae=(o,e)=>()=>(o&&(e=o(o=0)),e);var He=(o,e)=>{for(var t in e)Dt(o,t,{get:e[t],enumerable:!0})};var Je,
|
|
1
|
+
var Dt=Object.defineProperty;var we=(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 ae=(o,e)=>()=>(o&&(e=o(o=0)),e);var He=(o,e)=>{for(var t in e)Dt(o,t,{get:e[t],enumerable:!0})};var Je,jt,ue,_,G=ae(()=>{Je=()=>{},jt={debug:Je,info:Je,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},ue={impl:jt},_={debug:(...o)=>ue.impl.debug?.(...o),info:(...o)=>ue.impl.info?.(...o),warn:(...o)=>ue.impl.warn?.(...o),error:(...o)=>ue.impl.error?.(...o)}});var ot=ae(()=>{});var rt={};He(rt,{clearSkills:()=>Zt,getAllSkills:()=>Jt,getSkill:()=>Q,hasSkill:()=>Ht,listSkillIds:()=>Yt,registerSkill:()=>Wt});function Wt(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 Ht(o){return q.has(o)}function Jt(){return new Map(q)}function Yt(){return Array.from(q.keys())}function Zt(){q.clear()}var $e,q,pe=ae(()=>{$e=Symbol.for("@zibby/agent-workflow.skills");globalThis[$e]||(globalThis[$e]=new Map);q=globalThis[$e]});var ee={};He(ee,{getAgentStrategy:()=>nt,invokeAgent:()=>qt,listStrategies:()=>Kt,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=F.findIndex(t=>t.getName()===o.getName());e>=0?F[e]=o:F.push(o)}function Kt(){return F.map(o=>o.getName())}function nt(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let n=F.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}_.debug(`[workflow] agent selection: requested=${r}`);let s=F.find(n=>n.getName()===r);if(!s){let n=F.map(a=>a.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${n}`)}if(!s.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${s.getName()}`),s}async function qt(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},s={...e,state:r},n=nt(s),a=r.config||t.config||{},i=a.models||{},l=t.nodeName&&i[t.nodeName]||null,u=i.default||null,p=a.agent?.[n.name]?.model||null,c=l||u||p||t.model||null,d={...t,model:c,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],config:a},f=o,I=d.skills||[];if(I.length>0&&!t.skipPromptFragments){let E=I.map(h=>{let g=Q(h)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);E.length>0&&(f+=`
|
|
2
2
|
|
|
3
3
|
${E.join(`
|
|
4
4
|
|
|
@@ -14,7 +14,7 @@ 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
|
${$}
|
|
17
|
-
`),_.debug(`[workflow] prompt length: ${f.length} chars`),n.invoke(f,d)}var Te,F,te=ae(()=>{ot();G();pe();Te=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Te]||(globalThis[Te]=[]);F=globalThis[Te]});var
|
|
17
|
+
`),_.debug(`[workflow] prompt length: ${f.length} chars`),n.invoke(f,d)}var Te,F,te=ae(()=>{ot();G();pe();Te=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Te]||(globalThis[Te]=[]);F=globalThis[Te]});var Lt=new Set(["__proto__","constructor","prototype"]);function _e(o){if(Lt.has(o))throw new Error(`Invalid state key: "${o}"`)}var ce=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){_e(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)_e(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){_e(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 W from"handlebars";var le=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(s=>s[0]);for(let s of r)try{return this.validate(JSON.parse(s))}catch(n){if(!(n instanceof SyntaxError))throw n}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&s.type){let n=typeof e[r];n!==s.type&&t.push(`Field '${r}' expected ${s.type}, got ${n}`)}if(s.validate&&r in e){let n=s.validate(e[r]);n&&t.push(`Field '${r}': ${n}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
19
|
`)}`);return e}};G();import{writeFileSync as ve,readFileSync as st,existsSync as it,mkdirSync as Vt}from"node:fs";import{join as Ae,dirname as Xt}from"node:path";import k from"chalk";var Ut="__WORKFLOW_GRAPH_LOG__",X=k.gray("\u2502"),Gt=k.gray("\u250C"),Ye=k.gray("\u2514"),Ie=k.green("\u25C6"),Ze=k.hex("#c084fc")("\u25C6"),ze=k.hex("#2dd4bf")("\u25C6"),Ee=k.red("\u25C6"),Ke=`${X} `,qe=2;function Ve(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function Xe(o,e){return(t,r,s)=>{if(typeof t!="string")return o(t,r,s);let n=process.stdout.columns||120,a="";for(let i=0;i<t.length;i++){let l=t[i];e.lineStart&&(a+=Ke,e.col=qe,e.lineStart=!1),l===`
|
|
20
20
|
`?(a+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,a+=l):e.inEsc?(a+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,a+=l,e.col>=n&&(a+=`
|
|
@@ -29,17 +29,17 @@ ${Ke}`,e.col=qe))}return o(a,r,s)}}var be=class{constructor(){this._currentNode=
|
|
|
29
29
|
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(Ze,e):process.stdout.write.bind(process.stdout)(`${X} ${Ze} ${e}
|
|
30
30
|
`)}stepMemory(e){let t=k.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(Ee,k.red(e)):process.stdout.write.bind(process.stdout)(`${X} ${Ee} ${k.red(e)}
|
|
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:s}=t;if(s)for(let a of s)this._rawWrite(`${Ie} ${a}`);let n=r?k.dim(` ${Ve(r)}`):"";this._rawWrite(`${Ye} ${k.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?k.dim(` ${Ve(s)}`):"";this._rawWrite(`${Ee} ${k.red(t)}`),this._rawWrite(`${Ye} ${k.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(k.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new be;var de=".zibby/output",Qe="sessions",K=".session-info.json",et=".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",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Go=Object.freeze([Ft.CODEBASE_MEMORY]),tt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",o=>Number(o)+1);W.helpers.json||W.registerHelper("json",o=>JSON.stringify(o,null,2));W.helpers.eq||W.registerHelper("eq",(o,e)=>o===e);var
|
|
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:s}=t;if(s)for(let a of s)this._rawWrite(`${Ie} ${a}`);let n=r?k.dim(` ${Ve(r)}`):"";this._rawWrite(`${Ye} ${k.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:s}=r,n=s?k.dim(` ${Ve(s)}`):"";this._rawWrite(`${Ee} ${k.red(t)}`),this._rawWrite(`${Ye} ${k.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(k.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},x=new be;var de=".zibby/output",Qe="sessions",K=".session-info.json",et=".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"},Go=Object.freeze([Ft.CODEBASE_MEMORY]),tt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",o=>Number(o)+1);W.helpers.json||W.registerHelper("json",o=>JSON.stringify(o,null,2));W.helpers.eq||W.registerHelper("eq",(o,e)=>o===e);var j=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new le(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,s=c=>t&&typeof t.get=="function"?t.get(c):e?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(e);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return _.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let n;typeof this.prompt=="function"?n=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(r())):n=this.prompt;let a=s("_skillHints");a&&(n=`${a}
|
|
33
33
|
|
|
34
|
-
${n}`);let i=r(),l=i.cwd||process.cwd(),u=i.sessionPath;try{if(u){let c=Ae(u,K);if(it(c)){let f=JSON.parse(st(c,"utf-8"));f.currentNode=this.name,ve(c,JSON.stringify(f,null,2),"utf-8")}let d=Ae(u,"..",K);if(it(d))try{let f=JSON.parse(st(d,"utf-8"));f.currentNode=this.name,ve(d,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let d=r().config||{},f=d.agents||{},I=this.config.agent??f[this.name]??null,w={state:r()};I&&(w.preferredAgent=I);let $={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let h=await E(n,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let S=Ae(u,this.name,"raw_stream_output.txt");Vt(Xt(S),{recursive:!0}),ve(S,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(S){_.debug(`[workflow] could not save raw output: ${S.message}`)}if(this.isZodSchema&&m){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let S=m;if(typeof this.onComplete=="function")try{S=await this.onComplete(r(),m)}catch(N){_.warn(`[workflow] onComplete hook failed: ${N.message}`)}return{success:!0,output:S,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(S){throw new Error(`onComplete failed: ${S.message}`,{cause:S})}if(this.parser){let S=this.parser.parse(g);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(S,null,2)}`),x.step("Output parsed"),{success:!0,output:S,raw:g}}return{success:!0,output:g,raw:g}}catch(d){p=d,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},oe=class extends L{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}};G();G();import{mkdirSync as to,existsSync as J,statSync as ft,readdirSync as ht,rmSync as oo}from"node:fs";import{spawn as pt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as ro}from"node:url";import{AsyncLocalStorage as Qt}from"node:async_hooks";var ke=new Qt;function re(){let o=ke.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function at(o,e){let t=ke.getStore()||re(),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 ke.run(r,e)}var xe=new Map,Oe=new Map,ct=new Map;function lt(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");xe.set(o,e),Oe.set(o,"ready"),ct.set(o,{...t,cachedAt:Date.now()})}function ut(o,e){Oe.set(o,"failed"),ct.set(o,{error:e?.message||String(e),failedAt:Date.now()}),xe.delete(o)}function dt(o){return Oe.get(o)==="ready"?xe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function no(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function so(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function io({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 O("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=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=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=n,a}if(r.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new O("begin-status",`begin returned ${r.status}`)}return s?.data||s}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||_.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){_.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ao(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;to(e,{recursive:!0});let s=U(e,".lock"),n=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),l=a(s,"wx");i(l),n=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!n){let a=Date.now()+3e4;for(;Date.now()<a;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=pt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),c=pt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let d,f,I=()=>{if(d!==void 0&&f!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(f!==0)return u(new Error(`tar exited ${f}`));l()}};p.on("close",w=>{d=w,I()}),c.on("close",w=>{f=w,I()}),p.on("error",u),c.on("error",u)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(t,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new O("bundle-extract-failed",a.message)}}async function co(o){let e=U(o,"graph.mjs");if(!J(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(ro(e).href)}catch(s){throw new O("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function gt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=so()}catch(m){throw m}_.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await io({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:n,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,d=no();if(a&&a!==d)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${d} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${d} vs ${a}`);if(!c||!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 O("no-bundle","workflow bundle not built yet");let f=dt(o);if(!f){let m=U(fe,`${p}@${u||"0"}`);try{await ao(i,m);try{uo()}catch{}}catch(S){throw S.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{f=await co(m),lt(o,f,{workflowUuid:p,version:u,runtimeTag:a,cacheDir:m})}catch(S){throw ut(o,S),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new O("import-failed",S.message)}}let I=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await at({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-I}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-I}});let m=new Error(`Sub-graph '${o}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=n,m}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-I}}),{finalState:g,executionId:n}}function lo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=ft(r)}catch{continue}if(s.isDirectory()){let n;try{n=ht(r)}catch{continue}for(let a of n)t.push(U(r,a))}else e+=s.size}return e}function uo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(fe))return{evicted:0,freedBytes:0};let e=ht(fe),t=[],r=0;for(let i of e){let l=U(fe,i),u;try{u=ft(l)}catch{continue}let p=u.isDirectory()?lo(l):u.size;r+=p,t.push({name:i,full:l,size:p,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,l)=>i.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),n=0,a=0;for(let i of t){if(r-n<=s)break;if(!J(U(i.full,".lock")))try{oo(i.full,{recursive:!0,force:!0}),n+=i.size,a+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${i.name}: ${l.message}`)}}return a>0&&_.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:n,totalBytes:r-n}}catch(e){return _.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var po=2e3,fo=600*1e3,ho=new Set(["completed","failed","canceled","timeout"]);function go(){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 mo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function So(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function yo(){return process.env.EXECUTION_ID||null}function mt(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 St(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re(),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{_.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:m}=await gt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),S=mt(m,e.output);return _.info(`[sub-graph] '${o}' completed in-process`),S}catch(m){if(m instanceof O||m?.fallback)_.info(`[sub-graph] in-process fallback for '${o}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let s=go(),n=mo(),a=So(),i=yo(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};_.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(u)});if(!p.ok){let m=null,S="";try{m=await p.json(),S=m?.error||m?.message||JSON.stringify(m)}catch{S=await p.text().catch(()=>"")}if(p.status===429){let v=m?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.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=v,R}if(p.status===400){let v=new Error(`Sub-graph '${o}' rejected input: ${S}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=o,v.validationErrors=m?.validationErrors||null,v.missing=m?.missing||null,v}let N=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${S}`);throw N.code="SUBGRAPH_TRIGGER_FAILED",N.status=p.status,N.subgraph=o,N}let c=await p.json(),d=c?.data?.jobId||c?.jobId;if(!d)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return _.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:o};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:fo,I=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:po,w=`${s}/executions/${encodeURIComponent(d)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(v=>setTimeout(v,I)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${a}`}});if(!m.ok){if(m.status>=500){_.warn(`[sub-graph] status poll for ${d} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${m.status}`)}let S=await m.json(),N=S?.data||S?.execution||S;if(E=N?.status||E,ho.has(E)){if(E!=="completed"){let y=new Error(`Sub-graph '${o}' (${d}) ended in status '${E}'`);throw y.subgraphJobId=d,y.subgraphStatus=E,y}let v=N?.finalState||N?.state||{},R=mt(v,e.output);return _.info(`[sub-graph] '${o}' (${d}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=d,g.subgraphStatus=E,g}import{existsSync as yt,readFileSync as wo}from"node:fs";import{join as Ne,dirname as wt}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=wt(Ne(t,e));for(let l of n){let u=await this.findAndMergeContextFiles(l,i,t);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let a=r.discovery||{};for(let[i,l]of Object.entries(a))try{let u=Ne(t,l);yt(u)&&(s[i]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${i}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],n=t;for(;n.startsWith(r);){let a=Ne(n,e);if(yt(a))try{s.unshift(await this.loadFile(a))}catch(l){console.warn(`[workflow] could not load ${e} from ${a}: ${l.message}`)}let i=wt(n);if(i===n)break;n=i}return s.length===0?null:s.every(a=>typeof a=="string")?s.join(`
|
|
34
|
+
${n}`);let i=r(),l=i.cwd||process.cwd(),u=i.sessionPath;try{if(u){let c=Ae(u,K);if(it(c)){let f=JSON.parse(st(c,"utf-8"));f.currentNode=this.name,ve(c,JSON.stringify(f,null,2),"utf-8")}let d=Ae(u,"..",K);if(it(d))try{let f=JSON.parse(st(d,"utf-8"));f.currentNode=this.name,ve(d,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let d=r().config||{},f=d.agents||{},I=this.config.agent??f[this.name]??null,w={state:r()};I&&(w.preferredAgent=I);let $={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:d,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let h=await E(n,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let S=Ae(u,this.name,"raw_stream_output.txt");Vt(Xt(S),{recursive:!0}),ve(S,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(S){_.debug(`[workflow] could not save raw output: ${S.message}`)}if(this.isZodSchema&&m){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let S=m;if(typeof this.onComplete=="function")try{S=await this.onComplete(r(),m)}catch(N){_.warn(`[workflow] onComplete hook failed: ${N.message}`)}return{success:!0,output:S,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:g}),raw:g}}catch(S){throw new Error(`onComplete failed: ${S.message}`,{cause:S})}if(this.parser){let S=this.parser.parse(g);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(S,null,2)}`),x.step("Output parsed"),{success:!0,output:S,raw:g}}return{success:!0,output:g,raw:g}}catch(d){p=d,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},oe=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,t){let r=t&&typeof t.getAll=="function"?t.getAll():e;return{success:!0,output:{nextNode:this.condition(r)},raw:null}}};G();G();import{mkdirSync as to,existsSync as J,statSync as ft,readdirSync as ht,rmSync as oo}from"node:fs";import{spawn as pt}from"node:child_process";import{join as U}from"node:path";import{pathToFileURL as ro}from"node:url";import{AsyncLocalStorage as Qt}from"node:async_hooks";var ke=new Qt;function re(){let o=ke.getStore();return o||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function at(o,e){let t=ke.getStore()||re(),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 ke.run(r,e)}var xe=new Map,Oe=new Map,ct=new Map;function lt(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");xe.set(o,e),Oe.set(o,"ready"),ct.set(o,{...t,cachedAt:Date.now()})}function ut(o,e){Oe.set(o,"failed"),ct.set(o,{error:e?.message||String(e),failedAt:Date.now()}),xe.delete(o)}function dt(o){return Oe.get(o)==="ready"?xe.get(o):null}var fe=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function no(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var O=class extends Error{constructor(e,t){super(`in-process sub-graph fallback: ${e}${t?` (${t})`:""}`),this.fallback=!0,this.reason=e,this.detail=t||null,this.name="SubgraphFallback"}};function so(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!t||!r||!s)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:s}}async function io({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 O("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=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=s?.quotaInfo||{},a=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw a.code="SUBGRAPH_QUOTA_EXCEEDED",a.status=429,a.quotaInfo=n,a}if(r.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new O("begin-status",`begin returned ${r.status}`)}return s?.data||s}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||_.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){_.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function ao(o,e){let t=U(e,".ready"),r=U(e,"graph.mjs");if(J(t)&&J(r))return;to(e,{recursive:!0});let s=U(e,".lock"),n=!1;try{let{openSync:a,closeSync:i}=await import("node:fs"),l=a(s,"wx");i(l),n=!0}catch(a){if(a.code!=="EEXIST")throw a}if(!n){let a=Date.now()+3e4;for(;Date.now()<a;){if(J(t)&&J(r))return;await new Promise(i=>setTimeout(i,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=pt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),c=pt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let d,f,I=()=>{if(d!==void 0&&f!==void 0){if(d!==0)return u(new Error(`curl exited ${d}`));if(f!==0)return u(new Error(`tar exited ${f}`));l()}};p.on("close",w=>{d=w,I()}),c.on("close",w=>{f=w,I()}),p.on("error",u),c.on("error",u)});let{writeFileSync:a,unlinkSync:i}=await import("node:fs");a(t,"");try{i(s)}catch{}}catch(a){try{let{unlinkSync:i}=await import("node:fs");i(s)}catch{}throw new O("bundle-extract-failed",a.message)}}async function co(o){let e=U(o,"graph.mjs");if(!J(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(ro(e).href)}catch(s){throw new O("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let r=t.default||Object.values(t).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function gt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=re(),r;try{r=so()}catch(m){throw m}_.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let s=await io({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:n,runtimeTag:a,bundlePresignedUrl:i,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,d=no();if(a&&a!==d)throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${d} child=${a}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${d} vs ${a}`);if(!c||!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 O("no-bundle","workflow bundle not built yet");let f=dt(o);if(!f){let m=U(fe,`${p}@${u||"0"}`);try{await ao(i,m);try{uo()}catch{}}catch(S){throw S.fallback&&await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason}}}),S}try{f=await co(m),lt(o,f,{workflowUuid:p,version:u,runtimeTag:a,cacheDir:m})}catch(S){throw ut(o,S),await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:S.message,code:S.reason||"IMPORT_FAILED"}}}),S.fallback?S:new O("import-failed",S.message)}}let I=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await at({executionId:n,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-I}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"canceled",finalState:g,durationMs:Date.now()-I}});let m=new Error(`Sub-graph '${o}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=n,m}return await H({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:n,status:"completed",finalState:g,durationMs:Date.now()-I}}),{finalState:g,executionId:n}}function lo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),s;try{s=ft(r)}catch{continue}if(s.isDirectory()){let n;try{n=ht(r)}catch{continue}for(let a of n)t.push(U(r,a))}else e+=s.size}return e}function uo({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!J(fe))return{evicted:0,freedBytes:0};let e=ht(fe),t=[],r=0;for(let i of e){let l=U(fe,i),u;try{u=ft(l)}catch{continue}let p=u.isDirectory()?lo(l):u.size;r+=p,t.push({name:i,full:l,size:p,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((i,l)=>i.mtimeMs-l.mtimeMs);let s=Math.floor(o*.7),n=0,a=0;for(let i of t){if(r-n<=s)break;if(!J(U(i.full,".lock")))try{oo(i.full,{recursive:!0,force:!0}),n+=i.size,a+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${i.name}: ${l.message}`)}}return a>0&&_.info(`[sub-graph cache] evicted ${a} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:a,freedBytes:n,totalBytes:r-n}}catch(e){return _.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var po=2e3,fo=600*1e3,ho=new Set(["completed","failed","canceled","timeout"]);function go(){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 mo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function So(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function yo(){return process.env.EXECUTION_ID||null}function mt(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 St(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=re(),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{_.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:m}=await gt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),S=mt(m,e.output);return _.info(`[sub-graph] '${o}' completed in-process`),S}catch(m){if(m instanceof O||m?.fallback)_.info(`[sub-graph] in-process fallback for '${o}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let s=go(),n=mo(),a=So(),i=yo(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...i?{parentExecutionId:i}:{},...e.conversationId?{conversationId:e.conversationId}:{}};_.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${i||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(u)});if(!p.ok){let m=null,S="";try{m=await p.json(),S=m?.error||m?.message||JSON.stringify(m)}catch{S=await p.text().catch(()=>"")}if(p.status===429){let v=m?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${v.used??"?"}/${v.limit??"?"} on plan ${v.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=v,R}if(p.status===400){let v=new Error(`Sub-graph '${o}' rejected input: ${S}`);throw v.code="SUBGRAPH_INVALID_INPUT",v.status=400,v.subgraph=o,v.validationErrors=m?.validationErrors||null,v.missing=m?.missing||null,v}let N=new Error(`Sub-graph '${o}' trigger rejected (${p.status}): ${S}`);throw N.code="SUBGRAPH_TRIGGER_FAILED",N.status=p.status,N.subgraph=o,N}let c=await p.json(),d=c?.data?.jobId||c?.jobId;if(!d)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(e.async)return _.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${d} (not waiting)`),{jobId:d,status:"accepted",workflow:o};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:fo,I=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:po,w=`${s}/executions/${encodeURIComponent(d)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(v=>setTimeout(v,I)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${a}`}});if(!m.ok){if(m.status>=500){_.warn(`[sub-graph] status poll for ${d} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${d}: ${m.status}`)}let S=await m.json(),N=S?.data||S?.execution||S;if(E=N?.status||E,ho.has(E)){if(E!=="completed"){let y=new Error(`Sub-graph '${o}' (${d}) ended in status '${E}'`);throw y.subgraphJobId=d,y.subgraphStatus=E,y}let v=N?.finalState||N?.state||{},R=mt(v,e.output);return _.info(`[sub-graph] '${o}' (${d}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${o}' (${d}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=d,g.subgraphStatus=E,g}import{existsSync as yt,readFileSync as wo}from"node:fs";import{join as Ne,dirname as wt}from"node:path";var he=class{static async loadContext(e,t,r={}){let s={},n=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let i=wt(Ne(t,e));for(let l of n){let u=await this.findAndMergeContextFiles(l,i,t);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let a=r.discovery||{};for(let[i,l]of Object.entries(a))try{let u=Ne(t,l);yt(u)&&(s[i]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${i}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(e,t,r){let s=[],n=t;for(;n.startsWith(r);){let a=Ne(n,e);if(yt(a))try{s.unshift(await this.loadFile(a))}catch(l){console.warn(`[workflow] could not load ${e} from ${a}: ${l.message}`)}let i=wt(n);if(i===n)break;n=i}return s.length===0?null:s.every(a=>typeof a=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
38
|
`):s.every(a=>typeof a=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(e){let t=wo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(e).href);return s.default||s}return t}};import{mkdirSync as Et,existsSync as Pe,writeFileSync as _t,unlinkSync as _o}from"node:fs";import{join as Y,resolve as bt}from"node:path";import{config as Io}from"dotenv";import{zodToJsonSchema as It}from"zod-to-json-schema";import{z as ge}from"zod";import Eo from"handlebars";function bo({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let a=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${a} sessionId=${e} source=${r} mkdir=${s?"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(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${p}`)}}function $o(){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 To(){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 bt(String(e).trim())}catch{return String(e).trim()}}function vo(){$o()||(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 ko(o={}){let e=tt.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function xo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,n=t.sessionTimestamp,a="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=bt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,a="ZIBBY_SESSION_PATH")}catch{}let i;if(s)i=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)i=u,a="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(i=c,a="config.sessionId"):(i=ko(e),a="generated")}n=n??Date.now();let p=e.paths?.output||de;s=Y(o,p,Qe,i)}let l=!Pe(s);return l&&Et(s,{recursive:!0}),(l||a!=="initialState.sessionPath")&&bo({traceFrom:r,sessionId:i,sessionPath:s,idSource:a,mkdirFresh:l}),Ao({sessionPath:s,sessionId:i}),{sessionPath:s,sessionId:i,sessionTimestamp:n}}var me=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,a={name:e,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},St(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},i=new L(a);return i.name=e,this.nodes.set(e,i),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=t instanceof L?t:new L(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}addConditionalNode(e,t){return this.nodes.set(e,new oe({...t,name:e})),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels: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,s,n){let a=r;for(let i=e.length-1;i>=0;i--){let l=e[i],u=a;a=()=>l(t,u,s,n)}return a()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let d=this.nodeTypeMap.get(p)||(c instanceof oe?"decision":p);e.push({id:p,type:d,data:{nodeType:d,label:p}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let I=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;I&&(f.description=I);let w=this.nodePrompts.get(p);if(w)f.prompt=w;else if(typeof c.prompt=="function")try{let g=c.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let g=null;if(typeof ge?.toJSONSchema=="function")try{g=ge.toJSONSchema(c.outputSchema)}catch{}if(!g)try{g=It(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[p];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(t[p]=f)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(c.conditional){let d=this.conditionalCodeMap.get(p)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),I=c.labels||{};for(let w of f){let $={source:p,target:w,data:{conditionalCode:d}};I[w]&&($.label=I[w]),r.push($)}}let s=p=>{if(!p)return null;if(typeof ge?.toJSONSchema=="function")try{return ge.toJSONSchema(p)}catch{}try{return It(p,{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 p of r)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let a=this._runtimeSchema(),i=s(a||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:e,edges:r,nodeConfigs:t,stateSchema:i,inputSchema:l,contextSchema:u}}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,a;for(;(a=n.exec(r))!==null;){let u=a[2]!==void 0?a[2]:a[3];u!==void 0&&u!==""&&s.add(u)}let i=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())i.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))i.add(u);let l=new Set;for(let u of s)i.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=u.exec(r))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},n=e.required||[];for(let[a,i]of Object.entries(s)){let l=t?`${t}.${a}`:a;r.push({path:l,type:i.type||"unknown",label:i.description||this._formatLabel(a),optional:!n.includes(a)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,l)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,n]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${s}: ${n}`);else if(Array.isArray(n)){let a=n.length,i=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);r.push(l?`${s}: ${i}/${a} passed${a-i?`, ${a-i} failed`:""}`:`${s}: ${a} 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 s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,a=t.cwd||process.cwd();Io({path:Y(a,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let b=Y(a,".zibby.config.js");Pe(b)&&(i=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let l=t.agentType;if(!l){let b=i?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},p=this._runtimeSchema();if(p){let b=p.safeParse(t);if(!b.success){let P=b.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let c=To(),d=t.sessionPath||c;d||vo();let{sessionPath:f,sessionTimestamp:I,sessionId:w}=xo({cwd:a,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:d,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${w}`);let $=await he.loadContext(t.specPath||"",a,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).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 h=new ce({...t,config:i,agentType:l,outputPath:E,sessionPath:f,sessionTimestamp:I,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(pe(),rt)),S=i.skills&&typeof i.skills=="object"?i.skills:{},N=Object.values(S).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),v=b=>{for(let P of N)if(P.id===b)return P;return m(b)},R=new Set;for(let[,b]of this.nodes)for(let P of b.config?.skills||[])R.add(P);for(let b of R){let P=v(b);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&g.set(b,C)}catch{}}let y=this.entryPoint,ne=[],Me=i?.recursionLimit??100,kt=0;try{for(;y&&y!=="END";){if(++kt>Me)throw new Error(`Workflow exceeded recursion limit (${Me}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(f,et);if(Pe(P)){try{_o(P)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ne,stoppedExternally:!0};let C=this.nodes.get(y);if(!C)throw new Error(`Node '${y}' not found in graph`);let De=JSON.stringify({sessionPath:f,sessionTimestamp:I,currentNode:y,createdAt:new Date().toISOString(),config:h.get("config")}),xt=Y(f,K);_t(xt,De,"utf-8");let
|
|
41
|
+
${p}`)}}function $o(){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 To(){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 bt(String(e).trim())}catch{return String(e).trim()}}function vo(){$o()||(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 ko(o={}){let e=tt.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function xo({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let s=t.sessionPath,n=t.sessionTimestamp,a="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=bt(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,a="ZIBBY_SESSION_PATH")}catch{}let i;if(s)i=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)i=u,a="ZIBBY_SESSION_ID";else{let c=e.sessionId!=null?String(e.sessionId).trim():"";c&&c!=="last"?(i=c,a="config.sessionId"):(i=ko(e),a="generated")}n=n??Date.now();let p=e.paths?.output||de;s=Y(o,p,Qe,i)}let l=!Pe(s);return l&&Et(s,{recursive:!0}),(l||a!=="initialState.sessionPath")&&bo({traceFrom:r,sessionId:i,sessionPath:s,idSource:a,mkdirFresh:l}),Ao({sessionPath:s,sessionId:i}),{sessionPath:s,sessionId:i,sessionTimestamp:n}}var me=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 j)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,a={name:e,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},St(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},i=new j(a);return i.name=e,this.nodes.set(e,i),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let s=t instanceof j?t:new j(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}addConditionalNode(e,t){return this.nodes.set(e,new oe({...t,name:e})),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels: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,s,n){let a=r;for(let i=e.length-1;i>=0;i--){let l=e[i],u=a;a=()=>l(t,u,s,n)}return a()}serialize(){let e=[],t={};for(let[p,c]of this.nodes){let d=this.nodeTypeMap.get(p)||(c instanceof oe?"decision":p);e.push({id:p,type:d,data:{nodeType:d,label:p}});let f={};c._isCustomCode&&typeof c.execute=="function"&&(f.customCode=c.execute.toString());let I=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;I&&(f.description=I);let w=this.nodePrompts.get(p);if(w)f.prompt=w;else if(typeof c.prompt=="function")try{let g=c.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(f.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let g=null;if(typeof ge?.toJSONSchema=="function")try{g=ge.toJSONSchema(c.outputSchema)}catch{}if(!g)try{g=It(c.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:c.outputSchema}}else f.outputSchema={schema:c.outputSchema};let $=(this.resolvedToolsMap||{})[p];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(t[p]=f)}let r=[];for(let[p,c]of this.edges)if(typeof c=="string")r.push({source:p,target:c});else if(c.conditional){let d=this.conditionalCodeMap.get(p)||c.routes.toString(),f=this._inferConditionalTargets(c.routes,c.labels),I=c.labels||{};for(let w of f){let $={source:p,target:w,data:{conditionalCode:d}};I[w]&&($.label=I[w]),r.push($)}}let s=p=>{if(!p)return null;if(typeof ge?.toJSONSchema=="function")try{return ge.toJSONSchema(p)}catch{}try{return It(p,{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 p of r)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:p,target:c})}let a=this._runtimeSchema(),i=s(a||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:e,edges:r,nodeConfigs:t,stateSchema:i,inputSchema:l,contextSchema:u}}_inferConditionalTargets(e,t){let r=e.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,a;for(;(a=n.exec(r))!==null;){let u=a[2]!==void 0?a[2]:a[3];u!==void 0&&u!==""&&s.add(u)}let i=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())i.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))i.add(u);let l=new Set;for(let u of s)i.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=u.exec(r))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let s=e.$ref.replace("#/definitions/","");r=e.definitions[s]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],s=e.properties||{},n=e.required||[];for(let[a,i]of Object.entries(s)){let l=t?`${t}.${a}`:a;r.push({path:l,type:i.type||"unknown",label:i.description||this._formatLabel(a),optional:!n.includes(a)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,l)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[s,n]of Object.entries(t))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)r.push(`${s}: ${n}`);else if(Array.isArray(n)){let a=n.length,i=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);r.push(l?`${s}: ${i}/${a} passed${a-i?`, ${a-i} failed`:""}`:`${s}: ${a} 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 s=new AbortController;r.signal&&(r.signal.aborted?s.abort():r.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,a=t.cwd||process.cwd();Io({path:Y(a,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let b=Y(a,".zibby.config.js");Pe(b)&&(i=(await import(b)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let l=t.agentType;if(!l){let b=i?.agent;b?.provider?l=b.provider:b?.gemini?l="gemini":b?.claude?l="claude":b?.cursor?l="cursor":b?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},p=this._runtimeSchema();if(p){let b=p.safeParse(t);if(!b.success){let P=b.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let c=To(),d=t.sessionPath||c;d||vo();let{sessionPath:f,sessionTimestamp:I,sessionId:w}=xo({cwd:a,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:d,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${w}`);let $=await he.loadContext(t.specPath||"",a,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).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 h=new ce({...t,config:i,agentType:l,outputPath:E,sessionPath:f,sessionTimestamp:I,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(pe(),rt)),S=i.skills&&typeof i.skills=="object"?i.skills:{},N=Object.values(S).filter(b=>b&&typeof b=="object"&&typeof b.id=="string"),v=b=>{for(let P of N)if(P.id===b)return P;return m(b)},R=new Set;for(let[,b]of this.nodes)for(let P of b.config?.skills||[])R.add(P);for(let b of R){let P=v(b);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&g.set(b,C)}catch{}}let y=this.entryPoint,ne=[],Me=i?.recursionLimit??100,kt=0;try{for(;y&&y!=="END";){if(++kt>Me)throw new Error(`Workflow exceeded recursion limit (${Me}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(f,et);if(Pe(P)){try{_o(P)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ne,stoppedExternally:!0};let C=this.nodes.get(y);if(!C)throw new Error(`Node '${y}' not found in graph`);let De=JSON.stringify({sessionPath:f,sessionTimestamp:I,currentNode:y,createdAt:new Date().toISOString(),config:h.get("config")}),xt=Y(f,K);_t(xt,De,"utf-8");let Le=h.get("config")?.paths?.output||de,Ot=Y(a,Le,K);Et(Y(a,Le),{recursive:!0});try{_t(Ot,De,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:a,sessionPath:f,sessionId:w,outputBase:h.get("config")?.paths?.output||de,currentNode:y})}catch{}let Nt=(this.resolvedToolsMap||{})[y]||null;h.set("_currentNodeTools",Nt);let Pt=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",Pt[y]||{}),x.nodeStart(y);let Ue=Date.now(),se=this.nodePrompts.get(y);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=A.invokeAgent}let Ct=this._invokeAgent,ye={},Rt=C.config?.skills||[];for(let A of Rt){let B=v(A);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:y});T&&typeof T=="object"&&(ye={...ye,...T})}catch(T){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${T.message}`)}}let Ge=async(A,B,T={})=>{let M=Ct(A,B,{...ye,...T,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let L=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${n}ms`);V.name="AbortError",z(V)},n)};s.signal.addEventListener("abort",L,{once:!0})})])},Bt=async(A={},B={})=>{let T=B.prompt||"";if(se){let M=this._compiledPrompts.get(y);M||(M=Eo.compile(se,{noEscape:!0}),this._compiledPrompts.set(y,M));try{T=M(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${y}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return Ge(T,{state:h.getAll(),images:B.images||[]},{model:B.model||h.get("model"),workspace:h.get("workspace"),schema:B.schema,...B,signal:s.signal})},Fe=h.getAll(),Mt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of Mt)Object.prototype.hasOwnProperty.call(Fe,A)&&console.warn(`[workflow] node "${y}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let We={...Fe,state:h,invokeAgent:Bt,_coreInvokeAgent:Ge,agent:e,nodeId:y,promptTemplate:se,getPromptTemplate:()=>se};try{let A=(C.config?.skills||[]).map(L=>g.get(L)).filter(Boolean),B=[...this.middleware,...A],T;B.length>0?T=await this._composeMiddleware(B,y,async()=>C.execute(We,h),h.getAll(),h):T=await C.execute(We,h);let M=Date.now()-Ue;if(ne.push({node:y,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(s.signal.aborted)return x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:ne,stoppedExternally:!0};h.append("errors",{node:y,error:T.error});let L=C.config?.retries||0,V=`${y}_retries`,ie=h.getAll()[V]||0;if(ie<L){x.stepInfo(`Retrying (attempt ${ie+1}/${L})`),h.update({[V]:ie+1,[`${y}_raw`]:T.raw});continue}throw x.nodeFailed(y,T.error,{duration:M}),new Error(`Node '${y}' failed after ${ie} attempts: ${T.error}`)}h.update({[y]:T.output});let Z=this._summarizeNodeOutput(y,T.output);x.nodeComplete(y,{duration:M,details:Z});let z=this.edges.get(y);if(!z)y="END";else if(z.conditional){let L=z.routes(h.getAll());x.route(y,L),y=L}else y=z}catch(A){throw x.isInsideNode&&x.nodeFailed(y,A.message,{duration:Date.now()-Ue}),h.set("failed",!0),h.set("failedAt",y),A}}x.graphComplete();let b={success:!0,state:h.getAll(),executionLog:ne};return e&&typeof e.onComplete=="function"&&await e.onComplete(b),b}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(b){console.warn(`[workflow] agent.cleanup() failed: ${b.message}`)}}}};var Ce=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ce]||(globalThis[Ce]=new Map);var Re=globalThis[Ce];function Oo(o,e){Re.set(o,e)}function $t(o){return Re.get(o)}function Be(o){return Re.has(o)}Oo("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 s=e.extraPromptInstructions||"Execute the task based on the current state.",n=No(s,t),a=await r(n,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:a,nodeId:o},raw:typeof a=="string"?a:a.raw}}})});function No(o,e){let t=/@([\w.]+)/g,r=new Set,s;for(;(s=t.exec(o))!==null;)r.add(s[1]);if(r.size===0)return o;let n=[],a=new Set;for(let i of r){let l=i.split(".")[0];if(a.has(l))continue;let u=i.split(".").reduce((d,f)=>d?.[f],e);if(u===void 0)continue;let p=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),c=i.replace(/_/g," ").replace(/\b\w/g,d=>d.toUpperCase());n.push(`## ${c}
|
|
43
43
|
${p}`),i.includes(".")||a.add(l)}return n.length===0?o:`${o}
|
|
44
44
|
|
|
45
45
|
---
|
|
@@ -47,4 +47,4 @@ ${p}`),i.includes(".")||a.add(l)}return n.length===0?o:`${o}
|
|
|
47
47
|
|
|
48
48
|
${n.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}pe();G();var Po={};function vt(o,e){if(Array.isArray(e))return Tt(e);let t=Po[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 s of o){let n=Q(s);if(!n){_.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let a of n.tools||[])e.push({name:a.name,description:a.description,input_schema:a.input_schema||{type:"object",properties:{}}});if(!t[n.serverName])if(typeof n.resolve=="function"){let a=n.resolve();a&&(t[n.serverName]={...a,toolPrefix:s})}else{let a={};for(let i of n.envKeys||[]){let l=process.env[i];l&&(a[i]=l)}t[n.serverName]={command:n.command,args:[...n.args||[]],env:a,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}G();function
|
|
50
|
+
`)}`}pe();G();var Po={};function vt(o,e){if(Array.isArray(e))return Tt(e);let t=Po[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 s of o){let n=Q(s);if(!n){_.warn(`[workflow] unknown skill "${s}" \u2014 skipping`);continue}r.push(s);for(let a of n.tools||[])e.push({name:a.name,description:a.description,input_schema:a.input_schema||{type:"object",properties:{}}});if(!t[n.serverName])if(typeof n.resolve=="function"){let a=n.resolve();a&&(t[n.serverName]={...a,toolPrefix:s})}else{let a={};for(let i of n.envKeys||[]){let l=process.env[i];l&&(a[i]=l)}t[n.serverName]={command:n.command,args:[...n.args||[]],env:a,toolPrefix:s}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}G();function jr(o,e={}){let{nodes:t,edges:r,nodeConfigs:s={}}=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 me(e);e.stateSchema&&n.setStateSchema(e.stateSchema);let a=new Set,i=new Map,l={};for(let d of t){let f=Se(d);i.set(d.id,{...d,resolvedType:f}),f==="decision"&&a.add(d.id)}for(let[d,f]of i){if(a.has(d))continue;let I=f.resolvedType,w=s[d]||{},$=vt(I,w.tools);$&&(l[d]=$);let E={};w.prompt&&(E.prompt=w.prompt);let h=Be(I);if(_.debug(`[workflow] compiler: node "${d}" type="${I}" registered=${h}`),w.customCode&&!h)n.addNode(d,At(d,w.customCode,w),E),n.setNodeType(d,I);else if(h){let g=$t(I);g.factory?n.addNode(d,g.create(d,{...w,resolvedTools:$}),E):n.addNode(d,g,E),n.setNodeType(d,I)}else if(w.executeCode)n.addNode(d,At(d,w.executeCode,w),E),n.setNodeType(d,I);else throw new D(`Unknown node type "${I}" for node "${d}". Did you forget to register it?`)}n.resolvedToolsMap=l;let u=new Set;for(let d of r)a.has(d.target)||u.add(d.target);let p=t.find(d=>!a.has(d.id)&&!u.has(d.id));if(!p)throw new D("Could not determine entry point: no node without incoming edges found");n.setEntryPoint(p.id);let c=Co(r,"source");for(let d of r)if(!a.has(d.source))if(a.has(d.target)){let f=d.target,I=c.get(f)||[];if(I.length===0)throw new D(`Decision node "${f}" has no outgoing edges`);let w=Ro(f,I,a);n.addConditionalEdges(d.source,w)}else n.addEdge(d.source,d.target);return n}function Ur(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 l=Se(i);if(l==="decision"||Be(l))continue;let u=t[i.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" 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 s=new Set(o.nodes.filter(i=>Se(i)==="decision").map(i=>i.id)),n=new Set;for(let i of o.edges)s.has(i.target)||n.add(i.target);let a=o.nodes.filter(i=>!s.has(i.id)&&!n.has(i.id));a.length===0?e.push("No entry point found (every node has incoming edges)"):a.length>1&&e.push(`Multiple entry points found: ${a.map(i=>i.id).join(", ")}`);for(let i of s){let l=o.edges.filter(p=>p.source===i);l.length===0&&e.push(`Decision node "${i}" has no outgoing edges`),l.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 Gr(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>Se(e)!=="decision").map(e=>e.id)}function Se(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Co(o,e){let t=new Map;for(let r of o){let s=r[e];t.has(s)||t.set(s,[]),t.get(s).push(r)}return t}function Ro(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 s=r.data?.conditionalCode||r.conditionalCode,n=new Set(e.map(i=>i.target).filter(i=>!t.has(i))),a;try{let l=new Function(`return (${s})`)();a=u=>{let p=l(u);return n.has(p)||_.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 a}function At(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(a){throw new D(`Failed to compile customCode for node "${o}": ${a.message}`)}let s=r(async(...a)=>{let{invokeAgent:i}=await Promise.resolve().then(()=>(te(),ee));return i(...a)},typeof we<"u"?we:void 0,console),n=null;return t.outputSchema&&(n=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:n,execute:async a=>{try{let i=await s(a);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,Gr as extractSteps,Ur as validateGraphConfig};
|
package/dist/graph.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Oe=Object.defineProperty;var ot=(r,t)=>()=>(r&&(t=r(r=0)),t);var Dt=(r,t)=>{for(var e in t)Oe(r,e,{get:t[e],enumerable:!0})};var Lt,ke,it,_,V=ot(()=>{Lt=()=>{},ke={debug:Lt,info:Lt,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},it={impl:ke},_={debug:(...r)=>it.impl.debug?.(...r),info:(...r)=>it.impl.info?.(...r),warn:(...r)=>it.impl.warn?.(...r),error:(...r)=>it.impl.error?.(...r)}});var Kt=ot(()=>{});var Vt={};Dt(Vt,{clearSkills:()=>De,getAllSkills:()=>Be,getSkill:()=>St,hasSkill:()=>Ce,listSkillIds:()=>Me,registerSkill:()=>Re});function Re(r){if(!r||typeof r.id!="string")throw new Error("Skill definition must include a string id");z.set(r.id,Object.freeze({...r}))}function St(r){return z.get(r)||null}function Ce(r){return z.has(r)}function Be(){return new Map(z)}function Me(){return Array.from(z.keys())}function De(){z.clear()}var mt,z,yt=ot(()=>{mt=Symbol.for("@zibby/agent-workflow.skills");globalThis[mt]||(globalThis[mt]=new Map);z=globalThis[mt]});var wt={};Dt(wt,{getAgentStrategy:()=>qt,invokeAgent:()=>Ue,listStrategies:()=>je,registerStrategy:()=>Le});function Le(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=U.findIndex(e=>e.getName()===r.getName());t>=0?U[t]=r:U.push(r)}function je(){return U.map(r=>r.getName())}function qt(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let n=U.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${n}`)}_.debug(`[workflow] agent selection: requested=${o}`);let s=U.find(n=>n.getName()===o);if(!s){let n=U.map(i=>i.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${n}`)}if(!s.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return _.debug(`[workflow] using agent: ${s.getName()}`),s}async function Ue(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},s={...t,state:o},n=qt(s),i=o.config||e.config||{},a=i.models||{},l=e.nodeName&&a[e.nodeName]||null,u=a.default||null,p=i.agent?.[n.name]?.model||null,c=l||u||p||e.model||null,S={...e,model:c,workspace:o.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:i},h=r,b=S.skills||[];if(b.length>0&&!e.skipPromptFragments){let I=b.map(d=>{let f=St(d)?.promptFragment;return typeof f=="function"?f():f}).filter(Boolean);I.length>0&&(h+=`
|
|
2
2
|
|
|
3
3
|
${I.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let E=o._currentNodeConfig?.stores;if(Array.isArray(E)&&E.length>0&&typeof E[0]=="object"){let I=E.length<=8,d=E.map(f=>{let g=f?.id??f?.storeId??"",m=(f?.name??"").toString().trim()||g,P=f?.type?` \xB7 ${f.type}`:"",T=(f?.description||"").toString().replace(/\s+/g," ").trim(),
|
|
6
|
-
fields: ${y.join(", ")}`)}return
|
|
5
|
+
`)}`)}let E=o._currentNodeConfig?.stores;if(Array.isArray(E)&&E.length>0&&typeof E[0]=="object"){let I=E.length<=8,d=E.map(f=>{let g=f?.id??f?.storeId??"",m=(f?.name??"").toString().trim()||g,P=f?.type?` \xB7 ${f.type}`:"",T=(f?.description||"").toString().replace(/\s+/g," ").trim(),C=`- ${m} \xB7 ${T||"(no description)"}${P} (id: ${g})`;if(I&&f?.schema&&typeof f.schema=="object"){let y=f.schema.properties&&typeof f.schema.properties=="object"?Object.keys(f.schema.properties):Object.keys(f.schema);y.length&&(C+=`
|
|
6
|
+
fields: ${y.join(", ")}`)}return C});h+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${d.join(`
|
|
@@ -14,9 +14,9 @@ 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
|
${A}
|
|
17
|
-
`),_.debug(`[workflow] prompt length: ${h.length} chars`),n.invoke(h,S)}var _t,U,It=ot(()=>{Kt();V();yt();_t=Symbol.for("@zibby/agent-workflow.strategies");globalThis[_t]||(globalThis[_t]=[]);U=globalThis[_t]});var
|
|
17
|
+
`),_.debug(`[workflow] prompt length: ${h.length} chars`),n.invoke(h,S)}var _t,U,It=ot(()=>{Kt();V();yt();_t=Symbol.for("@zibby/agent-workflow.strategies");globalThis[_t]||(globalThis[_t]=[]);U=globalThis[_t]});var ve=new Set(["__proto__","constructor","prototype"]);function dt(r){if(ve.has(r))throw new Error(`Invalid state key: "${r}"`)}var st=class{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,e){dt(t),this._history.push({...this._state}),this._state[t]=e}update(t){let e=Object.getOwnPropertyNames(t);for(let o of e)dt(o);this._history.push({...this._state});for(let o of e)this._state[o]=t[o]}append(t,e){dt(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(e)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import W from"handlebars";var nt=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(s=>s[0]);for(let s of o)try{return this.validate(JSON.parse(s))}catch(n){if(!(n instanceof SyntaxError))throw n}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,s]of Object.entries(this.schema)){if(s.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&s.type){let n=typeof t[o];n!==s.type&&e.push(`Field '${o}' expected ${s.type}, got ${n}`)}if(s.validate&&o in t){let n=s.validate(t[o]);n&&e.push(`Field '${o}': ${n}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};V();import{writeFileSync as Et,readFileSync as Xt,existsSync as Qt,mkdirSync as We}from"node:fs";import{join as bt,dirname as Ge}from"node:path";import
|
|
19
|
+
`)}`);return t}};V();import{writeFileSync as Et,readFileSync as Xt,existsSync as Qt,mkdirSync as We}from"node:fs";import{join as bt,dirname as Ge}from"node:path";import v from"chalk";var xe="__WORKFLOW_GRAPH_LOG__",q=v.gray("\u2502"),Pe=v.gray("\u250C"),jt=v.gray("\u2514"),ft=v.green("\u25C6"),Ut=v.hex("#c084fc")("\u25C6"),Wt=v.hex("#2dd4bf")("\u25C6"),ht=v.red("\u25C6"),Gt=`${q} `,Ft=2;function Ht(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function Jt(r,t){return(e,o,s)=>{if(typeof e!="string")return r(e,o,s);let n=process.stdout.columns||120,i="";for(let a=0;a<e.length;a++){let l=e[a];t.lineStart&&(i+=Gt,t.col=Ft,t.lineStart=!1),l===`
|
|
20
20
|
`?(i+=l,t.lineStart=!0,t.col=0,t.inEsc=!1):l==="\x1B"?(t.inEsc=!0,i+=l):t.inEsc?(i+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(t.inEsc=!1)):(t.col++,i+=l,t.col>=n&&(i+=`
|
|
21
21
|
${Gt}`,t.col=Ft))}return r(i,o,s)}}var gt=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=Jt(this._origStdoutWrite,t),process.stderr.write=Jt(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
@@ -27,16 +27,16 @@ ${Gt}`,t.col=Ft))}return r(i,o,s)}}var gt=class{constructor(){this._currentNode=
|
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${t} ${e}
|
|
28
28
|
`)}step(t){this._origStdoutWrite?this._writeDot(ft,t):process.stdout.write.bind(process.stdout)(`${q} ${ft} ${t}
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(Ut,t):process.stdout.write.bind(process.stdout)(`${q} ${Ut} ${t}
|
|
30
|
-
`)}stepMemory(t){let e=
|
|
31
|
-
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?
|
|
30
|
+
`)}stepMemory(t){let e=v.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(Wt,e):process.stdout.write.bind(process.stdout)(`${q} ${Wt} ${e}
|
|
31
|
+
`)}stepFail(t){this._origStdoutWrite?this._writeDot(ht,v.red(t)):process.stdout.write.bind(process.stdout)(`${q} ${ht} ${v.red(t)}
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${Pe} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:s}=e;if(s)for(let i of s)this._rawWrite(`${ft} ${i}`);let n=o?v.dim(` ${Ht(o)}`):"";this._rawWrite(`${jt} ${v.green("done")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:s}=o,n=s?v.dim(` ${Ht(s)}`):"";this._rawWrite(`${ht} ${v.red(e)}`),this._rawWrite(`${jt} ${v.red("failed")}${n}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(v.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},k=new gt;var at=".zibby/output",Yt="sessions",Z=".session-info.json",Zt=".zibby-stop";var Ne={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"},Tr=Object.freeze([Ne.CODEBASE_MEMORY]),zt=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];W.helpers.inc||W.registerHelper("inc",r=>Number(r)+1);W.helpers.json||W.registerHelper("json",r=>JSON.stringify(r,null,2));W.helpers.eq||W.registerHelper("eq",(r,t)=>r===t);var L=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new nt(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,s=c=>e&&typeof e.get=="function"?e.get(c):t?.[c];if(typeof this.customExecute=="function"){_.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let c=await this.customExecute(t);return typeof c=="object"&&c!==null&&c.success===!1?{success:!1,error:c.error||"Node execution failed",raw:c.raw||null}:this.isZodSchema?(_.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(c),raw:null}):{success:!0,output:c,raw:null}}catch(c){return _.error(`[workflow] node '${this.name}' failed: ${c.message}`),c.name==="ZodError"&&_.error(`Schema errors: ${JSON.stringify(c.issues||c.errors,null,2)}`),{success:!1,error:c.message,raw:null}}}let n;typeof this.prompt=="function"?n=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=W.compile(this.prompt,{noEscape:!0})),n=this._compiledPrompt(o())):n=this.prompt;let i=s("_skillHints");i&&(n=`${i}
|
|
33
33
|
|
|
34
|
-
${n}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let c=bt(u,Z);if(Qt(c)){let h=JSON.parse(Xt(c,"utf-8"));h.currentNode=this.name,Et(c,JSON.stringify(h,null,2),"utf-8")}let S=bt(u,"..",Z);if(Qt(S))try{let h=JSON.parse(Xt(S,"utf-8"));h.currentNode=this.name,Et(S,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let S=o().config||{},h=S.agents||{},b=this.config.agent??h[this.name]??null,E={state:o()};b&&(E.preferredAgent=b);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let d=await I(n,E,A),f,g;if(typeof d=="string"?(f=d,g=null):d.structured?(f=d.raw||JSON.stringify(d.structured,null,2),g=d.structured):(f=d.raw||JSON.stringify(d,null,2),g=d.extracted||null),u)try{let m=bt(u,this.name,"raw_stream_output.txt");We(Ge(m),{recursive:!0}),Et(m,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let m=g;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),g)}catch(P){_.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:m,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(f);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:f}}return{success:!0,output:f,raw:f}}catch(S){p=S,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},X=class extends L{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};V();V();import{mkdirSync as Je,existsSync as F,statSync as ie,readdirSync as ae,rmSync as Ye}from"node:fs";import{spawn as ne}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ze}from"node:url";import{AsyncLocalStorage as Fe}from"node:async_hooks";var $t=new Fe;function Q(){let r=$t.getStore();return r||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 te(r,t){let e=$t.getStore()||Q(),o=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return $t.run(o,t)}var Tt=new Map,At=new Map,ee=new Map;function re(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),At.set(r,"ready"),ee.set(r,{...e,cachedAt:Date.now()})}function oe(r,t){At.set(r,"failed"),ee.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function se(r){return At.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var x=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}};function Ke(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!o||!s)throw new x("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Ve({apiBase:r,authToken:t,body:e}){let o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new x("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let n=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(o.status===429){let n=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=n,i}if(o.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new x("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function G({apiBase:r,authToken:t,payload:e}){try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function qe(r,t){let e=j(t,".ready"),o=j(t,"graph.mjs");if(F(e)&&F(o))return;Je(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),l=i(s,"wx");a(l),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(F(e)&&F(o))return;await new Promise(a=>setTimeout(a,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let S,h,b=()=>{if(S!==void 0&&h!==void 0){if(S!==0)return u(new Error(`curl exited ${S}`));if(h!==0)return u(new Error(`tar exited ${h}`));l()}};p.on("close",E=>{S=E,b()}),c.on("close",E=>{h=E,b()}),p.on("error",u),c.on("error",u)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(e,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new x("bundle-extract-failed",i.message)}}async function Xe(r){let t=j(r,"graph.mjs");if(!F(t))throw new x("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ze(t).href)}catch(s){throw new x("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new x("entry-class-missing","no buildGraph() class export found");return o}async function ce(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),o;try{o=Ke()}catch(g){throw g}_.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await Ve({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,S=ze();if(i&&i!==S)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new x("runtime-mismatch",`${S} vs ${i}`);if(!c||!a)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new x("no-bundle","workflow bundle not built yet");let h=se(r);if(!h){let g=j(ct,`${p}@${u||"0"}`);try{await qe(a,g);try{tr()}catch{}}catch(m){throw m.fallback&&await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason}}}),m}try{h=await Xe(g),re(r,h,{workflowUuid:p,version:u,runtimeTag:i,cacheDir:g})}catch(m){throw oe(r,m),await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason||"IMPORT_FAILED"}}}),m.fallback?m:new x("import-failed",m.message)}}let b=Date.now(),A=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),I={...t.input||{}},d,f;try{d=await te({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>A.run(t.parentAgent,I,{signal:t.signal})),f=d&&typeof d=="object"&&"state"in d?d.state:d}catch(g){throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-b}}),g}if(d&&typeof d=="object"&&d.stoppedExternally){await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:f,durationMs:Date.now()-b}});let g=new Error(`Sub-graph '${r}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=n,g}return await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:f,durationMs:Date.now()-b}}),{finalState:f,executionId:n}}function Qe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ie(o)}catch{continue}if(s.isDirectory()){let n;try{n=ae(o)}catch{continue}for(let i of n)e.push(j(o,i))}else t+=s.size}return t}function tr({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(ct))return{evicted:0,freedBytes:0};let t=ae(ct),e=[],o=0;for(let a of t){let l=j(ct,a),u;try{u=ie(l)}catch{continue}let p=u.isDirectory()?Qe(l):u.size;o+=p,e.push({name:a,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let a of e){if(o-n<=s)break;if(!F(j(a.full,".lock")))try{Ye(a.full,{recursive:!0,force:!0}),n+=a.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:o-n}}catch(t){return _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var er=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","timeout"]);function sr(){let r=process.env.PROGRESS_API_URL;if(!r)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 r.replace(/\/executions\/?$/,"")}function nr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function ir(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ar(){return process.env.EXECUTION_ID||null}function le(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],r):r}async function ue(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=o)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{_.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(g,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(g){if(g instanceof x||g?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=sr(),n=nr(),i=ir(),a=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(u)});if(!p.ok){let g=null,m="";try{g=await p.json(),m=g?.error||g?.message||JSON.stringify(g)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let T=g?.quotaInfo||{},B=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw B.code="SUBGRAPH_QUOTA_EXCEEDED",B.status=429,B.subgraph=r,B.quotaInfo=T,B}if(p.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${m}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=g?.validationErrors||null,T.missing=g?.missing||null,T}let P=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${m}`);throw P.code="SUBGRAPH_TRIGGER_FAILED",P.status=p.status,P.subgraph=r,P}let c=await p.json(),S=c?.data?.jobId||c?.jobId;if(!S)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${S} (not waiting)`),{jobId:S,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:rr,b=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:er,E=`${s}/executions/${encodeURIComponent(S)}`,A=Date.now()+h,I="accepted",d=0;for(;Date.now()<A;){await new Promise(T=>setTimeout(T,b)),d+=1;let g=await fetch(E,{headers:{Authorization:`Bearer ${i}`}});if(!g.ok){if(g.status>=500){_.warn(`[sub-graph] status poll for ${S} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${S}: ${g.status}`)}let m=await g.json(),P=m?.data||m?.execution||m;if(I=P?.status||I,or.has(I)){if(I!=="completed"){let y=new Error(`Sub-graph '${r}' (${S}) ended in status '${I}'`);throw y.subgraphJobId=S,y.subgraphStatus=I,y}let T=P?.finalState||P?.state||{},B=le(T,t.output);return _.info(`[sub-graph] '${r}' (${S}) completed after ${d} polls`),B}}let f=new Error(`Sub-graph '${r}' (${S}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw f.subgraphJobId=S,f.subgraphStatus=I,f}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as vt,dirname as de}from"node:path";var lt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=de(vt(e,t));for(let l of n){let u=await this.findAndMergeContextFiles(l,a,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let u=vt(e,l);pe(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=vt(n,t);if(pe(i))try{s.unshift(await this.loadFile(i))}catch(l){console.warn(`[workflow] could not load ${t} from ${i}: ${l.message}`)}let a=de(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
34
|
+
${n}`);let a=o(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let c=bt(u,Z);if(Qt(c)){let h=JSON.parse(Xt(c,"utf-8"));h.currentNode=this.name,Et(c,JSON.stringify(h,null,2),"utf-8")}let S=bt(u,"..",Z);if(Qt(S))try{let h=JSON.parse(Xt(S,"utf-8"));h.currentNode=this.name,Et(S,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(c){_.debug(`[workflow] could not update session info: ${c.message}`)}let p=null;for(let c=0;c<=this.retries;c++)try{_.debug(`[workflow] node '${this.name}' attempt ${c}`);let S=o().config||{},h=S.agents||{},b=this.config.agent??h[this.name]??null,E={state:o()};b&&(E.preferredAgent=b);let A={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:S,nodeName:this.name,timeout:this.config?.timeout||3e5},I=t?._coreInvokeAgent;I||(I=(await Promise.resolve().then(()=>(It(),wt))).invokeAgent);let d=await I(n,E,A),f,g;if(typeof d=="string"?(f=d,g=null):d.structured?(f=d.raw||JSON.stringify(d.structured,null,2),g=d.structured):(f=d.raw||JSON.stringify(d,null,2),g=d.extracted||null),u)try{let m=bt(u,this.name,"raw_stream_output.txt");We(Ge(m),{recursive:!0}),Et(m,typeof f=="string"?f:JSON.stringify(f),"utf-8")}catch(m){_.debug(`[workflow] could not save raw output: ${m.message}`)}if(this.isZodSchema&&g){_.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let m=g;if(typeof this.onComplete=="function")try{m=await this.onComplete(o(),g)}catch(P){_.warn(`[workflow] onComplete hook failed: ${P.message}`)}return{success:!0,output:m,raw:f}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:f}),raw:f}}catch(m){throw new Error(`onComplete failed: ${m.message}`,{cause:m})}if(this.parser){let m=this.parser.parse(f);return _.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(m,null,2)}`),k.step("Output parsed"),{success:!0,output:m,raw:f}}return{success:!0,output:f,raw:f}}catch(S){p=S,c<this.retries&&_.info(`[workflow] node '${this.name}' failed, retrying (${c+1}/${this.retries})\u2026`)}return{success:!1,error:p.message,raw:null}}},X=class extends L{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};V();V();import{mkdirSync as Je,existsSync as F,statSync as ie,readdirSync as ae,rmSync as Ye}from"node:fs";import{spawn as ne}from"node:child_process";import{join as j}from"node:path";import{pathToFileURL as Ze}from"node:url";import{AsyncLocalStorage as Fe}from"node:async_hooks";var $t=new Fe;function Q(){let r=$t.getStore();return r||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 te(r,t){let e=$t.getStore()||Q(),o=Object.freeze({executionId:r.executionId,parentExecutionId:r.parentExecutionId??e.executionId??null,depth:(e.depth||0)+(r.executionId!==e.executionId?1:0),conversationId:r.conversationId!==void 0?r.conversationId:e.conversationId??null,dispatchMode:r.dispatchMode??null});return $t.run(o,t)}var Tt=new Map,At=new Map,ee=new Map;function re(r,t,e={}){if(!r||typeof r!="string")throw new Error("subgraph-registry.register: name required");if(typeof t!="function")throw new Error("subgraph-registry.register: factory must be a function");Tt.set(r,t),At.set(r,"ready"),ee.set(r,{...e,cachedAt:Date.now()})}function oe(r,t){At.set(r,"failed"),ee.set(r,{error:t?.message||String(t),failedAt:Date.now()}),Tt.delete(r)}function se(r){return At.get(r)==="ready"?Tt.get(r):null}var ct=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function ze(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var x=class extends Error{constructor(t,e){super(`in-process sub-graph fallback: ${t}${e?` (${e})`:""}`),this.fallback=!0,this.reason=t,this.detail=e||null,this.name="SubgraphFallback"}};function Ke(){let r=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),t=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),e=r||t,o=process.env.PROJECT_ID,s=process.env.PROJECT_API_TOKEN;if(!e||!o||!s)throw new x("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:e,projectId:o,authToken:s}}async function Ve({apiBase:r,authToken:t,body:e}){let o;try{o=await fetch(`${r}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)})}catch(n){throw new x("network",`begin fetch failed: ${n.message}`)}let s=null;try{s=await o.json()}catch{}if(!o.ok){if(o.status===404){let n=new Error(`Sub-graph child '${e.childWorkflowType}' not found in project`);throw n.code="SUBGRAPH_NOT_FOUND",n.status=404,n}if(o.status===429){let n=s?.quotaInfo||{},i=new Error(`Sub-graph blocked by quota (${n.used??"?"}/${n.limit??"?"} on ${n.planId||"plan"})`);throw i.code="SUBGRAPH_QUOTA_EXCEEDED",i.status=429,i.quotaInfo=n,i}if(o.status===400&&s?.validationErrors){let n=new Error(`Sub-graph rejected input: ${s?.error||s?.message||"validation failed"}`);throw n.code="SUBGRAPH_INVALID_INPUT",n.status=400,n.validationErrors=s.validationErrors,n.missing=s.missing,n}throw new x("begin-status",`begin returned ${o.status}`)}return s?.data||s}async function G({apiBase:r,authToken:t,payload:e}){try{let o=await fetch(`${r}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});o.ok||_.warn(`[in-process subgraph] finalize returned ${o.status} for ${e.childExecutionId}`)}catch(o){_.warn(`[in-process subgraph] finalize failed: ${o.message}`)}}async function qe(r,t){let e=j(t,".ready"),o=j(t,"graph.mjs");if(F(e)&&F(o))return;Je(t,{recursive:!0});let s=j(t,".lock"),n=!1;try{let{openSync:i,closeSync:a}=await import("node:fs"),l=i(s,"wx");a(l),n=!0}catch(i){if(i.code!=="EEXIST")throw i}if(!n){let i=Date.now()+3e4;for(;Date.now()<i;){if(F(e)&&F(o))return;await new Promise(a=>setTimeout(a,100))}throw new x("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let p=ne("curl",["-fsSL",r],{stdio:["ignore","pipe","inherit"]}),c=ne("tar",["-xzf","-","-C",t],{stdio:["pipe","inherit","inherit"]});p.stdout.pipe(c.stdin);let S,h,b=()=>{if(S!==void 0&&h!==void 0){if(S!==0)return u(new Error(`curl exited ${S}`));if(h!==0)return u(new Error(`tar exited ${h}`));l()}};p.on("close",E=>{S=E,b()}),c.on("close",E=>{h=E,b()}),p.on("error",u),c.on("error",u)});let{writeFileSync:i,unlinkSync:a}=await import("node:fs");i(e,"");try{a(s)}catch{}}catch(i){try{let{unlinkSync:a}=await import("node:fs");a(s)}catch{}throw new x("bundle-extract-failed",i.message)}}async function Xe(r){let t=j(r,"graph.mjs");if(!F(t))throw new x("entry-missing",`graph.mjs missing under ${r}`);let e;try{e=await import(Ze(t).href)}catch(s){throw new x("import-failed",`${s?.code||s?.name||"unknown"}: ${s.message}`)}let o=e.default||Object.values(e).find(s=>typeof s=="function"&&s.prototype?.buildGraph);if(!o)throw new x("entry-class-missing","no buildGraph() class export found");return o}async function ce(r,t={}){if(!r||typeof r!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let e=Q(),o;try{o=Ke()}catch(g){throw g}_.debug(`[in-process subgraph] begin '${r}' parent=${e.executionId||"<root>"}`);let s=await Ve({apiBase:o.apiBase,authToken:o.authToken,body:{parentExecutionId:e.executionId,childWorkflowType:r,input:t.input||{},...t.conversationId?{conversationId:t.conversationId}:{}}}),{childExecutionId:n,runtimeTag:i,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:p,bundleReady:c}=s,S=ze();if(i&&i!==S)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${i}`,code:"RUNTIME_MISMATCH"}}}),new x("runtime-mismatch",`${S} vs ${i}`);if(!c||!a)throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new x("no-bundle","workflow bundle not built yet");let h=se(r);if(!h){let g=j(ct,`${p}@${u||"0"}`);try{await qe(a,g);try{tr()}catch{}}catch(m){throw m.fallback&&await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason}}}),m}try{h=await Xe(g),re(r,h,{workflowUuid:p,version:u,runtimeTag:i,cacheDir:g})}catch(m){throw oe(r,m),await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:m.message,code:m.reason||"IMPORT_FAILED"}}}),m.fallback?m:new x("import-failed",m.message)}}let b=Date.now(),A=await(typeof h=="function"&&h.prototype?.buildGraph?new h:h).buildGraph(),I={...t.input||{}},d,f;try{d=await te({executionId:n,parentExecutionId:e.executionId,conversationId:t.conversationId!==void 0?t.conversationId:e.conversationId,dispatchMode:"inprocess"},()=>A.run(t.parentAgent,I,{signal:t.signal})),f=d&&typeof d=="object"&&"state"in d?d.state:d}catch(g){throw await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"failed",error:{message:g.message,code:g.code||"CHILD_THREW",stack:g.stack},durationMs:Date.now()-b}}),g}if(d&&typeof d=="object"&&d.stoppedExternally){await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"canceled",finalState:f,durationMs:Date.now()-b}});let g=new Error(`Sub-graph '${r}' canceled by parent abort`);throw g.code="SUBGRAPH_CANCELED",g.subgraphJobId=n,g}return await G({apiBase:o.apiBase,authToken:o.authToken,payload:{childExecutionId:n,status:"completed",finalState:f,durationMs:Date.now()-b}}),{finalState:f,executionId:n}}function Qe(r){let t=0,e=[r];for(;e.length;){let o=e.pop(),s;try{s=ie(o)}catch{continue}if(s.isDirectory()){let n;try{n=ae(o)}catch{continue}for(let i of n)e.push(j(o,i))}else t+=s.size}return t}function tr({cap:r=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!F(ct))return{evicted:0,freedBytes:0};let t=ae(ct),e=[],o=0;for(let a of t){let l=j(ct,a),u;try{u=ie(l)}catch{continue}let p=u.isDirectory()?Qe(l):u.size;o+=p,e.push({name:a,full:l,size:p,mtimeMs:u.mtimeMs})}if(o<=r)return{evicted:0,freedBytes:0,totalBytes:o};e.sort((a,l)=>a.mtimeMs-l.mtimeMs);let s=Math.floor(r*.7),n=0,i=0;for(let a of e){if(o-n<=s)break;if(!F(j(a.full,".lock")))try{Ye(a.full,{recursive:!0,force:!0}),n+=a.size,i+=1}catch(l){_.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return i>0&&_.info(`[sub-graph cache] evicted ${i} entr(y/ies), freed ${(n/1024/1024).toFixed(1)}MB`),{evicted:i,freedBytes:n,totalBytes:o-n}}catch(t){return _.debug(`[sub-graph cache] evict failed: ${t.message}`),{evicted:0,freedBytes:0}}}var er=2e3,rr=600*1e3,or=new Set(["completed","failed","canceled","timeout"]);function sr(){let r=process.env.PROGRESS_API_URL;if(!r)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 r.replace(/\/executions\/?$/,"")}function nr(){let r=process.env.PROJECT_ID;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return r}function ir(){let r=process.env.PROJECT_API_TOKEN;if(!r)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return r}function ar(){return process.env.EXECUTION_ID||null}function le(r,t){return t==null?r:typeof t=="function"?t(r):typeof t=="string"?t.split(".").reduce((e,o)=>e==null?e:e[o],r):r}async function ue(r,t={}){if(!r||typeof r!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let e=Q(),o=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((e.depth||0)>=o)throw new Error(`dispatchSubgraph('${r}'): sub-graph depth ${e.depth} reached cap of ${o}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!t.async)try{_.debug(`[sub-graph] trying in-process for '${r}'`);let{finalState:g}=await ce(r,{input:t.input,conversationId:t.conversationId,signal:t.signal,parentAgent:t.parentAgent}),m=le(g,t.output);return _.info(`[sub-graph] '${r}' completed in-process`),m}catch(g){if(g instanceof x||g?.fallback)_.info(`[sub-graph] in-process fallback for '${r}': ${g.reason||"unknown"} \u2014 using HTTP`);else throw g}let s=sr(),n=nr(),i=ir(),a=ar(),l=`${s}/projects/${encodeURIComponent(n)}/workflows/${encodeURIComponent(r)}/trigger`,u={input:t.input||{},...a?{parentExecutionId:a}:{},...t.conversationId?{conversationId:t.conversationId}:{}};_.info(`[sub-graph] dispatching '${r}' (${t.async?"async":"sync"}) from parent ${a||"<none>"}`);let p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(u)});if(!p.ok){let g=null,m="";try{g=await p.json(),m=g?.error||g?.message||JSON.stringify(g)}catch{m=await p.text().catch(()=>"")}if(p.status===429){let T=g?.quotaInfo||{},C=new Error(`Sub-graph '${r}' blocked by execution quota (${T.used??"?"}/${T.limit??"?"} on plan ${T.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw C.code="SUBGRAPH_QUOTA_EXCEEDED",C.status=429,C.subgraph=r,C.quotaInfo=T,C}if(p.status===400){let T=new Error(`Sub-graph '${r}' rejected input: ${m}`);throw T.code="SUBGRAPH_INVALID_INPUT",T.status=400,T.subgraph=r,T.validationErrors=g?.validationErrors||null,T.missing=g?.missing||null,T}let P=new Error(`Sub-graph '${r}' trigger rejected (${p.status}): ${m}`);throw P.code="SUBGRAPH_TRIGGER_FAILED",P.status=p.status,P.subgraph=r,P}let c=await p.json(),S=c?.data?.jobId||c?.jobId;if(!S)throw new Error(`Sub-graph '${r}' trigger returned no jobId: ${JSON.stringify(c).slice(0,200)}`);if(t.async)return _.info(`[sub-graph] async dispatch of '${r}' \u2192 jobId=${S} (not waiting)`),{jobId:S,status:"accepted",workflow:r};let h=Number.isFinite(t.timeoutMs)?t.timeoutMs:rr,b=Number.isFinite(t.pollIntervalMs)?t.pollIntervalMs:er,E=`${s}/executions/${encodeURIComponent(S)}`,A=Date.now()+h,I="accepted",d=0;for(;Date.now()<A;){await new Promise(T=>setTimeout(T,b)),d+=1;let g=await fetch(E,{headers:{Authorization:`Bearer ${i}`}});if(!g.ok){if(g.status>=500){_.warn(`[sub-graph] status poll for ${S} returned ${g.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${S}: ${g.status}`)}let m=await g.json(),P=m?.data||m?.execution||m;if(I=P?.status||I,or.has(I)){if(I!=="completed"){let y=new Error(`Sub-graph '${r}' (${S}) ended in status '${I}'`);throw y.subgraphJobId=S,y.subgraphStatus=I,y}let T=P?.finalState||P?.state||{},C=le(T,t.output);return _.info(`[sub-graph] '${r}' (${S}) completed after ${d} polls`),C}}let f=new Error(`Sub-graph '${r}' (${S}) timed out after ${Math.round(h/1e3)}s (last status: ${I})`);throw f.subgraphJobId=S,f.subgraphStatus=I,f}import{existsSync as pe,readFileSync as cr}from"node:fs";import{join as Ot,dirname as de}from"node:path";var lt=class{static async loadContext(t,e,o={}){let s={},n=o.filenames||["CONTEXT.md","AGENTS.md"];if(t){let a=de(Ot(e,t));for(let l of n){let u=await this.findAndMergeContextFiles(l,a,e);if(u){let p=l.replace(/\.[^.]+$/,"").toLowerCase();s[p]=u}}}let i=o.discovery||{};for(let[a,l]of Object.entries(i))try{let u=Ot(e,l);pe(u)&&(s[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return s}static async findAndMergeContextFiles(t,e,o){let s=[],n=e;for(;n.startsWith(o);){let i=Ot(n,t);if(pe(i))try{s.unshift(await this.loadFile(i))}catch(l){console.warn(`[workflow] could not load ${t} from ${i}: ${l.message}`)}let a=de(n);if(a===n)break;n=a}return s.length===0?null:s.every(i=>typeof i=="string")?s.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=cr(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(t).href);return s.default||s}return e}};import{mkdirSync as me,existsSync as
|
|
38
|
+
`):s.every(i=>typeof i=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=cr(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:o}=await import("url"),s=await import(o(t).href);return s.default||s}return e}};import{mkdirSync as me,existsSync as vt,writeFileSync as fe,unlinkSync as lr}from"node:fs";import{join as H,resolve as Se}from"node:path";import{config as ur}from"dotenv";import{zodToJsonSchema as he}from"zod-to-json-schema";import{z as ut}from"zod";import pr from"handlebars";function dr({traceFrom:r,sessionId:t,sessionPath:e,idSource:o,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let i=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${r} pid=${process.pid} ppid=${i} sessionId=${t} source=${o} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let p=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${r}):
|
|
41
|
-
${p}`)}}function fr(){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 hr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Se(String(t).trim())}catch{return String(t).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Sr(r={}){let t=zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function yr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Se(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,i="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Sr(t),i="generated")}n=n??Date.now();let p=t.paths?.output||at;s=H(r,p,Yt,a)}let l=!Ot(s);return l&&me(s,{recursive:!0}),(l||i!=="initialState.sessionPath")&&dr({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:l}),mr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var ge=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,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(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},ue(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},a=new L(i);return a.name=t,this.nodes.set(t,a),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof L?e:new L(e);return s.name=t,this.nodes.set(t,s),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new X({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,n){let i=o;for(let a=t.length-1;a>=0;a--){let l=t[a],u=i;i=()=>l(e,u,s,n)}return i()}serialize(){let t=[],e={};for(let[p,c]of this.nodes){let S=this.nodeTypeMap.get(p)||(c instanceof X?"decision":p);t.push({id:p,type:S,data:{nodeType:S,label:p}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(h.description=b);let E=this.nodePrompts.get(p);if(E)h.prompt=E;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(h.prompt=f,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof ut?.toJSONSchema=="function")try{f=ut.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=he(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let A=(this.resolvedToolsMap||{})[p];A?.toolIds&&(h.tools=A.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(h.skills=[...I]);let d=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;d&&d.length>0&&(h.stores=d.map(f=>f&&typeof f=="object"?{...f}:f)),Object.keys(h).length>0&&(e[p]=h)}let o=[];for(let[p,c]of this.edges)if(typeof c=="string")o.push({source:p,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(p)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{};for(let E of h){let A={source:p,target:E,data:{conditionalCode:S}};b[E]&&(A.label=b[E]),o.push(A)}}let s=p=>{if(!p)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(p)}catch{}try{return he(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let n=0;for(let p of o)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:p,target:c})}let i=this._runtimeSchema(),a=s(i||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:a,inputSchema:l,contextSchema:u}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(o))!==null;){let u=i[2]!==void 0?i[2]:i[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(e&&typeof e=="object")for(let u of Object.keys(e))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=u.exec(o))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},n=t.required||[];for(let[i,a]of Object.entries(s)){let l=e?`${e}.${i}`:i;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!n.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,a=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();ur({path:H(i,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let w=H(i,".zibby.config.js");Ot(w)&&(a=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=e.agentType;if(!l){let w=a?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let w=p.safeParse(e);if(!w.success){let N=w.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}k.step("State validated against schema")}let c=hr(),S=e.sessionPath||c;S||gr();let{sessionPath:h,sessionTimestamp:b,sessionId:E}=yr({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:S,sessionTimestamp:e.sessionTimestamp}});k.step(`Session ${E}`);let A=await lt.loadContext(e.specPath||"",i,u);Object.keys(A).length>0&&k.step(`Context loaded: ${Object.keys(A).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let d=new st({...e,config:a,agentType:l,outputPath:I,sessionPath:h,sessionTimestamp:b,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:g}=await Promise.resolve().then(()=>(yt(),Vt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},P=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),T=w=>{for(let N of P)if(N.id===w)return N;return g(w)},B=new Set;for(let[,w]of this.nodes)for(let N of w.config?.skills||[])B.add(N);for(let w of B){let N=T(w);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(w,R)}catch{}}let y=this.entryPoint,tt=[],kt=a?.recursionLimit??100,ye=0;try{for(;y&&y!=="END";){if(++ye>kt)throw new Error(`Workflow exceeded recursion limit (${kt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(h,Zt);if(Ot(N)){try{lr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};let R=this.nodes.get(y);if(!R)throw new Error(`Node '${y}' not found in graph`);let xt=JSON.stringify({sessionPath:h,sessionTimestamp:b,currentNode:y,createdAt:new Date().toISOString(),config:d.get("config")}),_e=H(h,Z);fe(_e,xt,"utf-8");let Pt=d.get("config")?.paths?.output||at,we=H(i,Pt,Z);me(H(i,Pt),{recursive:!0});try{fe(we,xt,"utf-8")}catch{}let Nt=e.onPipelineProgress;if(typeof Nt=="function")try{Nt({cwd:i,sessionPath:h,sessionId:E,outputBase:d.get("config")?.paths?.output||at,currentNode:y})}catch{}let Ie=(this.resolvedToolsMap||{})[y]||null;d.set("_currentNodeTools",Ie);let Ee=d.get("nodeConfigs")||{};d.set("_currentNodeConfig",Ee[y]||{}),k.nodeStart(y);let Rt=Date.now(),et=this.nodePrompts.get(y);if(!this._invokeAgent){let
|
|
41
|
+
${p}`)}}function fr(){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 hr(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let t=process.env.ZIBBY_SESSION_PATH;if(!(t==null||String(t).trim()===""))try{return Se(String(t).trim())}catch{return String(t).trim()}}function gr(){fr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function mr({sessionPath:r,sessionId:t}){r&&typeof r=="string"&&(process.env.ZIBBY_SESSION_PATH=r),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function Sr(r={}){let t=zt.map(n=>process.env[n]).find(Boolean),e=Math.random().toString(36).slice(2,6),o=t||`${Date.now()}_${e}`,s=r.paths?.sessionPrefix;return s?`${s}_${o}`:o}function yr({cwd:r=process.cwd(),config:t={},initialState:e={},traceFrom:o="resolveWorkflowSession"}={}){let s=e.sessionPath,n=e.sessionTimestamp,i="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let u=Se(String(process.env.ZIBBY_SESSION_PATH));u&&(s=u,i="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,i="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,i="config.sessionId"):(a=Sr(t),i="generated")}n=n??Date.now();let p=t.paths?.output||at;s=H(r,p,Yt,a)}let l=!vt(s);return l&&me(s,{recursive:!0}),(l||i!=="initialState.sessionPath")&&dr({traceFrom:o,sessionId:a,sessionPath:s,idSource:i,mkdirFresh:l}),mr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:n}}var ge=class{constructor(t={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(t.middleware)?[...t.middleware]:[],t.nodeMiddleware&&this.middleware.push(t.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=t.stateSchema||null,this.inputSchema=t.inputSchema||null,this.contextSchema=t.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=t.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(t){return this.inputSchema=t,this}setContextSchema(t){return this.contextSchema=t,this}setStateSchema(t){return this.stateSchema=t,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(t,e,o={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,i={name:t,_isCustomCode:!0,retries:n.retries,onComplete:n.onComplete,execute:async l=>{let u=l?.state&&typeof l.state.getAll=="function"?l.state.getAll():l,p;return typeof n.input=="function"?p=n.input(u):n.input&&typeof n.input=="object"?p=n.input:p={},ue(n.workflow,{input:p,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(u):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:u?._signal,parentAgent:l?.agent})}},a=new L(i);return a.name=t,this.nodes.set(t,a),o.prompt&&this.nodePrompts.set(t,o.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}let s=e instanceof L?e:new L(e);return s.name=t,this.nodes.set(t,s),o.prompt?this.nodePrompts.set(t,o.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(o).length>0&&this.nodeOptions.set(t,o),this}addConditionalNode(t,e){return this.nodes.set(t,new X({...e,name:t})),this}addEdge(t,e){return this.edges.set(t,e),this}setNodeType(t,e){return this.nodeTypeMap.set(t,e),this}addConditionalEdges(t,e,{labels:o}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:o}),typeof e=="function"&&this.conditionalCodeMap.set(t,e.toString()),this}setEntryPoint(t){return this.entryPoint=t,this}use(t){return typeof t=="function"&&this.middleware.push(t),this}_composeMiddleware(t,e,o,s,n){let i=o;for(let a=t.length-1;a>=0;a--){let l=t[a],u=i;i=()=>l(e,u,s,n)}return i()}serialize(){let t=[],e={};for(let[p,c]of this.nodes){let S=this.nodeTypeMap.get(p)||(c instanceof X?"decision":p);t.push({id:p,type:S,data:{nodeType:S,label:p}});let h={};c._isCustomCode&&typeof c.execute=="function"&&(h.customCode=c.execute.toString());let b=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;b&&(h.description=b);let E=this.nodePrompts.get(p);if(E)h.prompt=E;else if(typeof c.prompt=="function")try{let f=c.prompt({});typeof f=="string"&&f.trim()&&(h.prompt=f,h.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(h.executeCode=c.customExecute.toString()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let f=null;if(typeof ut?.toJSONSchema=="function")try{f=ut.toJSONSchema(c.outputSchema)}catch{}if(!f)try{f=he(c.outputSchema,{target:"openApi3"})}catch{}h.outputSchema=f?{jsonSchema:f,variables:this._flattenJsonSchemaToVariables(f)}:{schema:c.outputSchema}}else h.outputSchema={schema:c.outputSchema};let A=(this.resolvedToolsMap||{})[p];A?.toolIds&&(h.tools=A.toolIds);let I=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;I&&I.length>0&&(h.skills=[...I]);let d=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;d&&d.length>0&&(h.stores=d.map(f=>f&&typeof f=="object"?{...f}:f)),Object.keys(h).length>0&&(e[p]=h)}let o=[];for(let[p,c]of this.edges)if(typeof c=="string")o.push({source:p,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(p)||c.routes.toString(),h=this._inferConditionalTargets(c.routes,c.labels),b=c.labels||{};for(let E of h){let A={source:p,target:E,data:{conditionalCode:S}};b[E]&&(A.label=b[E]),o.push(A)}}let s=p=>{if(!p)return null;if(typeof ut?.toJSONSchema=="function")try{return ut.toJSONSchema(p)}catch{}try{return he(p,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),o.unshift({source:"START",target:this.entryPoint}));let n=0;for(let p of o)if(p.target==="END"){n+=1;let c=`END__${n}`;p.target=c,t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let p of this.nodes.keys())if(!this.edges.has(p)){n+=1;let c=`END__${n}`;t.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),o.push({source:p,target:c})}let i=this._runtimeSchema(),a=s(i||this.stateSchema),l=s(this.inputSchema),u=s(this.contextSchema);return{nodes:t,edges:o,nodeConfigs:e,stateSchema:a,inputSchema:l,contextSchema:u}}_inferConditionalTargets(t,e){let o=t.toString(),s=new Set,n=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,i;for(;(i=n.exec(o))!==null;){let u=i[2]!==void 0?i[2]:i[3];u!==void 0&&u!==""&&s.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(e&&typeof e=="object")for(let u of Object.keys(e))a.add(u);let l=new Set;for(let u of s)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,p;for(;(p=u.exec(o))!==null;)l.add(p[1])}return[...l]}_flattenJsonSchemaToVariables(t,e=""){let o=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");o=t.definitions[s]||t}return this._flattenSchema(o,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let o=[],s=t.properties||{},n=t.required||[];for(let[i,a]of Object.entries(s)){let l=e?`${e}.${i}`:i;o.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(i),optional:!n.includes(i)}),a.type==="object"&&a.properties&&o.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&o.push(...this._flattenSchema(a.items,`${l}[]`))}return o}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let o=[];e.success!==void 0&&o.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,n]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof n=="string"&&n.length<=80)o.push(`${s}: ${n}`);else if(Array.isArray(n)){let i=n.length,a=n.filter(u=>u?.passed===!0).length,l=n.some(u=>u?.passed!==void 0);o.push(l?`${s}: ${a}/${i} passed${i-a?`, ${i-a} failed`:""}`:`${s}: ${i} items`)}if(o.length>=4)break}return o}async run(t,e={},o={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let s=new AbortController;o.signal&&(o.signal.aborted?s.abort():o.signal.addEventListener("abort",()=>s.abort(),{once:!0}));let n=o.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,i=e.cwd||process.cwd();ur({path:H(i,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let w=H(i,".zibby.config.js");vt(w)&&(a=(await import(w)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=e.agentType;if(!l){let w=a?.agent;w?.provider?l=w.provider:w?.gemini?l="gemini":w?.claude?l="claude":w?.cursor?l="cursor":w?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let u=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},p=this._runtimeSchema();if(p){let w=p.safeParse(e);if(!w.success){let N=w.error.issues.map(R=>`${R.path.join(".")}: ${R.message}`);throw console.error("\u274C Initial state validation failed:"),N.forEach(R=>console.error(` - ${R}`)),new Error(`State validation failed: ${N.join(", ")}`)}k.step("State validated against schema")}let c=hr(),S=e.sessionPath||c;S||gr();let{sessionPath:h,sessionTimestamp:b,sessionId:E}=yr({cwd:i,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:S,sessionTimestamp:e.sessionTimestamp}});k.step(`Session ${E}`);let A=await lt.loadContext(e.specPath||"",i,u);Object.keys(A).length>0&&k.step(`Context loaded: ${Object.keys(A).join(", ")}`);let I=e.outputPath;!I&&e.specPath&&(t?.calculateOutputPath?I=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let d=new st({...e,config:a,agentType:l,outputPath:I,sessionPath:h,sessionTimestamp:b,context:A,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:g}=await Promise.resolve().then(()=>(yt(),Vt)),m=a.skills&&typeof a.skills=="object"?a.skills:{},P=Object.values(m).filter(w=>w&&typeof w=="object"&&typeof w.id=="string"),T=w=>{for(let N of P)if(N.id===w)return N;return g(w)},C=new Set;for(let[,w]of this.nodes)for(let N of w.config?.skills||[])C.add(N);for(let w of C){let N=T(w);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(w,R)}catch{}}let y=this.entryPoint,tt=[],kt=a?.recursionLimit??100,ye=0;try{for(;y&&y!=="END";){if(++ye>kt)throw new Error(`Workflow exceeded recursion limit (${kt}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let N=H(h,Zt);if(vt(N)){try{lr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};let R=this.nodes.get(y);if(!R)throw new Error(`Node '${y}' not found in graph`);let xt=JSON.stringify({sessionPath:h,sessionTimestamp:b,currentNode:y,createdAt:new Date().toISOString(),config:d.get("config")}),_e=H(h,Z);fe(_e,xt,"utf-8");let Pt=d.get("config")?.paths?.output||at,we=H(i,Pt,Z);me(H(i,Pt),{recursive:!0});try{fe(we,xt,"utf-8")}catch{}let Nt=e.onPipelineProgress;if(typeof Nt=="function")try{Nt({cwd:i,sessionPath:h,sessionId:E,outputBase:d.get("config")?.paths?.output||at,currentNode:y})}catch{}let Ie=(this.resolvedToolsMap||{})[y]||null;d.set("_currentNodeTools",Ie);let Ee=d.get("nodeConfigs")||{};d.set("_currentNodeConfig",Ee[y]||{}),k.nodeStart(y);let Rt=Date.now(),et=this.nodePrompts.get(y);if(!this._invokeAgent){let O=await Promise.resolve().then(()=>(It(),wt));this._invokeAgent=O.invokeAgent}let be=this._invokeAgent,pt={},$e=R.config?.skills||[];for(let O of $e){let B=T(O);if(typeof B?.invokeAgentOptions=="function")try{let $=B.invokeAgentOptions(d.getAll(),{agentType:d.get("agentType"),nodeName:y});$&&typeof $=="object"&&(pt={...pt,...$})}catch($){console.warn(`[graph] skill '${O}' invokeAgentOptions threw: ${$.message}`)}}let Ct=async(O,B,$={})=>{let M=be(O,B,{...pt,...$,signal:s.signal});return M.catch(()=>{}),s.signal.aborted?M:Promise.race([M,new Promise((J,Y)=>{let D=()=>{setTimeout(()=>{let K=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${n}ms`);K.name="AbortError",Y(K)},n)};s.signal.addEventListener("abort",D,{once:!0})})])},Te=async(O={},B={})=>{let $=B.prompt||"";if(et){let M=this._compiledPrompts.get(y);M||(M=pr.compile(et,{noEscape:!0}),this._compiledPrompts.set(y,M));try{$=M(O)}catch(J){throw console.error(`\u274C Template rendering failed for node '${y}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!$)throw new Error(`No prompt template configured for node '${y}' and no prompt provided in options`);return Ct($,{state:d.getAll(),images:B.images||[]},{model:B.model||d.get("model"),workspace:d.get("workspace"),schema:B.schema,...B,signal:s.signal})},Bt=d.getAll(),Ae=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let O of Ae)Object.prototype.hasOwnProperty.call(Bt,O)&&console.warn(`[workflow] node "${y}": state key "${O}" is shadowed by the engine context prop; read it via context.state.get('${O}')`);let Mt={...Bt,state:d,invokeAgent:Te,_coreInvokeAgent:Ct,agent:t,nodeId:y,promptTemplate:et,getPromptTemplate:()=>et};try{let O=(R.config?.skills||[]).map(D=>f.get(D)).filter(Boolean),B=[...this.middleware,...O],$;B.length>0?$=await this._composeMiddleware(B,y,async()=>R.execute(Mt,d),d.getAll(),d):$=await R.execute(Mt,d);let M=Date.now()-Rt;if(tt.push({node:y,success:$.success,duration:M,timestamp:new Date().toISOString()}),!$.success){if(s.signal.aborted)return k.step("Workflow stopped externally"),{success:!0,state:d.getAll(),executionLog:tt,stoppedExternally:!0};d.append("errors",{node:y,error:$.error});let D=R.config?.retries||0,K=`${y}_retries`,rt=d.getAll()[K]||0;if(rt<D){k.stepInfo(`Retrying (attempt ${rt+1}/${D})`),d.update({[K]:rt+1,[`${y}_raw`]:$.raw});continue}throw k.nodeFailed(y,$.error,{duration:M}),new Error(`Node '${y}' failed after ${rt} attempts: ${$.error}`)}d.update({[y]:$.output});let J=this._summarizeNodeOutput(y,$.output);k.nodeComplete(y,{duration:M,details:J});let Y=this.edges.get(y);if(!Y)y="END";else if(Y.conditional){let D=Y.routes(d.getAll());k.route(y,D),y=D}else y=Y}catch(O){throw k.isInsideNode&&k.nodeFailed(y,O.message,{duration:Date.now()-Rt}),d.set("failed",!0),d.set("failedAt",y),O}}k.graphComplete();let w={success:!0,state:d.getAll(),executionLog:tt};return t&&typeof t.onComplete=="function"&&await t.onComplete(w),w}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(w){console.warn(`[workflow] agent.cleanup() failed: ${w.message}`)}}}};export{ge as WorkflowGraph,gr as clearInheritedSessionEnvForFreshRun,Sr as generateWorkflowSessionId,hr as readPinnedSessionPathFromEnv,yr as resolveWorkflowSession,fr as shouldTrustInheritedSessionEnv,mr as syncProcessEnvToSession};
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { WorkflowState } from "./state.js";
|
|
|
3
3
|
export { ContextLoader } from "./context-loader.js";
|
|
4
4
|
export { AgentStrategy } from "./agents/base.js";
|
|
5
5
|
export { setLogger } from "./logger.js";
|
|
6
|
-
export { WorkflowGraph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
|
|
6
|
+
export { WorkflowGraph, WorkflowGraph as Graph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
|
|
7
7
|
export { Node, ConditionalNode } from "./node.js";
|
|
8
8
|
export { OutputParser, SchemaTypes } from "./output-parser.js";
|
|
9
9
|
export { compileGraph, validateGraphConfig, extractSteps, CompilationError } from "./graph-compiler.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var io=Object.defineProperty;var $e=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var nt=(t,e)=>{for(var o in e)io(t,o,{get:e[o],enumerable:!0})};function lo(t){
|
|
1
|
+
var io=Object.defineProperty;var $e=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require<"u"?require:e)[o]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var nt=(t,e)=>{for(var o in e)io(t,o,{get:e[o],enumerable:!0})};function lo(t){re.impl={...st,...t}}var rt,st,re,I,F=ge(()=>{rt=()=>{},st={debug:rt,info:rt,warn:(...t)=>console.warn("[workflow]",...t),error:(...t)=>console.error("[workflow]",...t)},re={impl:st};I={debug:(...t)=>re.impl.debug?.(...t),info:(...t)=>re.impl.info?.(...t),warn:(...t)=>re.impl.warn?.(...t),error:(...t)=>re.impl.error?.(...t)}});var Ne,Oe=ge(()=>{Ne=class{constructor(e,o,n=0){this.name=e,this.description=o,this.priority=n}async invoke(e,o={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var _t={};nt(_t,{clearSkills:()=>wt,getAllSkills:()=>St,getSkill:()=>q,hasSkill:()=>mt,listSkillIds:()=>yt,registerSkill:()=>gt});function gt(t){if(!t||typeof t.id!="string")throw new Error("Skill definition must include a string id");V.set(t.id,Object.freeze({...t}))}function q(t){return V.get(t)||null}function mt(t){return V.has(t)}function St(){return new Map(V)}function yt(){return Array.from(V.keys())}function wt(){V.clear()}var Ce,V,ae=ge(()=>{Ce=Symbol.for("@zibby/agent-workflow.skills");globalThis[Ce]||(globalThis[Ce]=new Map);V=globalThis[Ce]});var ce={};nt(ce,{getAgentStrategy:()=>Re,invokeAgent:()=>$t,listStrategies:()=>It,registerStrategy:()=>Et});function Et(t){if(!t||typeof t.getName!="function"||typeof t.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=W.findIndex(o=>o.getName()===t.getName());e>=0?W[e]=t:W.push(t)}function It(){return W.map(t=>t.getName())}function Re(t={}){let{state:e={},preferredAgent:o=null}=t,n=o||e.agentType||process.env.AGENT_TYPE;if(!n){let r=W.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${r}`)}I.debug(`[workflow] agent selection: requested=${n}`);let i=W.find(r=>r.getName()===n);if(!i){let r=W.map(s=>s.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${n}'. Available: ${r}`)}if(!i.canHandle(t))throw new Error(`Agent '${n}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${i.getName()}`),i}async function $t(t,e={},o={}){let n=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:n},r=Re(i),s=n.config||o.config||{},a=s.models||{},c=o.nodeName&&a[o.nodeName]||null,u=a.default||null,d=s.agent?.[r.name]?.model||null,l=c||u||d||o.model||null,p={...o,model:l,workspace:n.workspace||o.workspace,schema:o.schema||e.schema,images:o.images||e.images||[],skills:o.skills||e.skills||[],config:s},f=t,S=p.skills||[];if(S.length>0&&!o.skipPromptFragments){let E=S.map(h=>{let g=q(h)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);E.length>0&&(f+=`
|
|
2
2
|
|
|
3
3
|
${E.join(`
|
|
4
4
|
|
|
@@ -14,9 +14,9 @@ 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
|
${$}
|
|
17
|
-
`),I.debug(`[workflow] prompt length: ${f.length} chars`),r.invoke(f,p)}var Pe,W,X=ge(()=>{Oe();F();
|
|
17
|
+
`),I.debug(`[workflow] prompt length: ${f.length} chars`),r.invoke(f,p)}var Pe,W,X=ge(()=>{Oe();F();ae();Pe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Pe]||(globalThis[Pe]=[]);W=globalThis[Pe]});var ao=new Set(["__proto__","constructor","prototype"]);function Te(t){if(ao.has(t))throw new Error(`Invalid state key: "${t}"`)}var oe=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,o){Te(e),this._history.push({...this._state}),this._state[e]=o}update(e){let o=Object.getOwnPropertyNames(e);for(let n of o)Te(n);this._history.push({...this._state});for(let n of o)this._state[n]=e[n]}append(e,o){Te(e),this._history.push({...this._state}),Array.isArray(this._state[e])||(this._state[e]=[]),this._state[e].push(o)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}};import H from"handlebars";var ne=class{constructor(e){this.schema=e}parse(e){let o=e.match(/```json\s*([\s\S]*?)\s*```/);if(o)return this.validate(JSON.parse(o[1]));let n=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(i=>i[0]);for(let i of n)try{return this.validate(JSON.parse(i))}catch(r){if(!(r instanceof SyntaxError))throw r}return this.validate({result:e.trim()})}validate(e){let o=[];for(let[n,i]of Object.entries(this.schema)){if(i.required&&!(n in e)&&o.push(`Missing required field: ${n}`),n in e&&i.type){let r=typeof e[n];r!==i.type&&o.push(`Field '${n}' expected ${i.type}, got ${r}`)}if(i.validate&&n in e){let r=i.validate(e[n]);r&&o.push(`Field '${n}': ${r}`)}}if(o.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${o.join(`
|
|
19
|
-
`)}`);return e}},co={string:(t=!0)=>({type:"string",required:t}),number:(t=!0)=>({type:"number",required:t}),boolean:(t=!0)=>({type:"boolean",required:t}),array:(t=!0)=>({type:"object",required:t,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(t,e=!0)=>({type:"string",required:e,validate:o=>t.includes(o)?null:`must be one of: ${t.join(", ")}`})};F();import{writeFileSync as Be,readFileSync as Tt,existsSync as bt,mkdirSync as mo}from"node:fs";import{join as
|
|
19
|
+
`)}`);return e}},co={string:(t=!0)=>({type:"string",required:t}),number:(t=!0)=>({type:"number",required:t}),boolean:(t=!0)=>({type:"boolean",required:t}),array:(t=!0)=>({type:"object",required:t,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(t,e=!0)=>({type:"string",required:e,validate:o=>t.includes(o)?null:`must be one of: ${t.join(", ")}`})};F();import{writeFileSync as Be,readFileSync as Tt,existsSync as bt,mkdirSync as mo}from"node:fs";import{join as De,dirname as So}from"node:path";import x from"chalk";var ft="__WORKFLOW_GRAPH_LOG__",se=x.gray("\u2502"),uo=x.gray("\u250C"),it=x.gray("\u2514"),be=x.green("\u25C6"),at=x.hex("#c084fc")("\u25C6"),ct=x.hex("#2dd4bf")("\u25C6"),Ae=x.red("\u25C6"),lt=`${se} `,ut=2;function dt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function pt(t,e){return(o,n,i)=>{if(typeof o!="string")return t(o,n,i);let r=process.stdout.columns||120,s="";for(let a=0;a<o.length;a++){let c=o[a];e.lineStart&&(s+=lt,e.col=ut,e.lineStart=!1),c===`
|
|
20
20
|
`?(s+=c,e.lineStart=!0,e.col=0,e.inEsc=!1):c==="\x1B"?(e.inEsc=!0,s+=c):e.inEsc?(s+=c,(c>="A"&&c<="Z"||c>="a"&&c<="z")&&(e.inEsc=!1)):(e.col++,s+=c,e.col>=r&&(s+=`
|
|
21
21
|
${lt}`,e.col=ut))}return t(s,n,i)}}var me=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},o={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=o,process.stdout.write=pt(this._origStdoutWrite,e),process.stderr.write=pt(this._origStderrWrite,o)}_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(`
|
|
@@ -25,21 +25,21 @@ ${lt}`,e.col=ut))}return t(s,n,i)}}var me=class{constructor(){this._currentNode=
|
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(o):process.stdout.write(o)}_writeDot(e,o){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${o}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${o}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(be,e):process.stdout.write.bind(process.stdout)(`${
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(at,e):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(e){let o=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${uo} ${e}`),this._startIntercepting()}nodeComplete(e,o={}){this._stopIntercepting();let{duration:n,details:i}=o;if(i)for(let s of i)this._rawWrite(`${be} ${s}`);let r=n?
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(be,e):process.stdout.write.bind(process.stdout)(`${se} ${be} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(at,e):process.stdout.write.bind(process.stdout)(`${se} ${at} ${e}
|
|
30
|
+
`)}stepMemory(e){let o=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(ct,o):process.stdout.write.bind(process.stdout)(`${se} ${ct} ${o}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(Ae,x.red(e)):process.stdout.write.bind(process.stdout)(`${se} ${Ae} ${x.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${uo} ${e}`),this._startIntercepting()}nodeComplete(e,o={}){this._stopIntercepting();let{duration:n,details:i}=o;if(i)for(let s of i)this._rawWrite(`${be} ${s}`);let r=n?x.dim(` ${dt(n)}`):"";this._rawWrite(`${it} ${x.green("done")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,o,n={}){this._stopIntercepting();let{duration:i}=n,r=i?x.dim(` ${dt(i)}`):"";this._rawWrite(`${Ae} ${x.red(o)}`),this._rawWrite(`${it} ${x.red("failed")}${r}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,o){this._rawWrite(x.dim(` ${e} \u2192 ${o}`)),this._rawWrite("")}graphComplete(){}},k=new me;var ie=".zibby/output",ve="sessions",U=".session-info.json",ke=".zibby-stop",po="result.json",fo="raw_stream_output.txt",ho="events.json",ht={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"},go=Object.freeze([ht.CODEBASE_MEMORY]),xe=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",t=>Number(t)+1);H.helpers.json||H.registerHelper("json",t=>JSON.stringify(t,null,2));H.helpers.eq||H.registerHelper("eq",(t,e)=>t===e);var j=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new ne(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,o){let n=()=>o&&typeof o.getAll=="function"?o.getAll():e,i=l=>o&&typeof o.get=="function"?o.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 r;typeof this.prompt=="function"?r=this.prompt(n()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),r=this._compiledPrompt(n())):r=this.prompt;let s=i("_skillHints");s&&(r=`${s}
|
|
33
33
|
|
|
34
|
-
${r}`);let a=n(),c=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let l=Me(u,U);if(bt(l)){let f=JSON.parse(Tt(l,"utf-8"));f.currentNode=this.name,Be(l,JSON.stringify(f,null,2),"utf-8")}let p=Me(u,"..",U);if(bt(p))try{let f=JSON.parse(Tt(p,"utf-8"));f.currentNode=this.name,Be(p,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let d=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let p=n().config||{},f=p.agents||{},S=this.config.agent??f[this.name]??null,w={state:n()};S&&(w.preferredAgent=S);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:p,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let h=await E(r,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let y=Me(u,this.name,"raw_stream_output.txt");mo(So(y),{recursive:!0}),Be(y,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(y){I.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let y=m;if(typeof this.onComplete=="function")try{y=await this.onComplete(n(),m)}catch(O){I.warn(`[workflow] onComplete hook failed: ${O.message}`)}return{success:!0,output:y,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(y){throw new Error(`onComplete failed: ${y.message}`,{cause:y})}if(this.parser){let y=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(y,null,2)}`),x.step("Output parsed"),{success:!0,output:y,raw:g}}return{success:!0,output:g,raw:g}}catch(p){d=p,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:d.message,raw:null}}},Q=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){let n=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(n)},raw:null}}};F();F();import{mkdirSync as _o,existsSync as Y,statSync as Ct,readdirSync as Pt,rmSync as Eo}from"node:fs";import{spawn as Ot}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Io}from"node:url";import{AsyncLocalStorage as yo}from"node:async_hooks";var Le=new yo;function ce(){let t=Le.getStore();return t||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function At(t,e){let o=Le.getStore()||ce(),n=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??o.executionId??null,depth:(o.depth||0)+(t.executionId!==o.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:o.conversationId??null,dispatchMode:t.dispatchMode??null});return Le.run(n,e)}var De=new Map,je=new Map,vt=new Map;function xt(t,e,o={}){if(!t||typeof t!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");De.set(t,e),je.set(t,"ready"),vt.set(t,{...o,cachedAt:Date.now()})}function kt(t,e){je.set(t,"failed"),vt.set(t,{error:e?.message||String(e),failedAt:Date.now()}),De.delete(t)}function Nt(t){return je.get(t)==="ready"?De.get(t):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $o(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,o){super(`in-process sub-graph fallback: ${e}${o?` (${o})`:""}`),this.fallback=!0,this.reason=e,this.detail=o||null,this.name="SubgraphFallback"}};function To(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),o=t||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!o||!n||!i)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:o,projectId:n,authToken:i}}async function bo({apiBase:t,authToken:e,body:o}){let n;try{n=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)})}catch(r){throw new N("network",`begin fetch failed: ${r.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let r=new Error(`Sub-graph child '${o.childWorkflowType}' not found in project`);throw r.code="SUBGRAPH_NOT_FOUND",r.status=404,r}if(n.status===429){let r=i?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${r.used??"?"}/${r.limit??"?"} on ${r.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=r,s}if(n.status===400&&i?.validationErrors){let r=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw r.code="SUBGRAPH_INVALID_INPUT",r.status=400,r.validationErrors=i.validationErrors,r.missing=i.missing,r}throw new N("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:t,authToken:e,payload:o}){try{let n=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${o.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Ao(t,e){let o=G(e,".ready"),n=G(e,"graph.mjs");if(Y(o)&&Y(n))return;_o(e,{recursive:!0});let i=G(e,".lock"),r=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),c=s(i,"wx");a(c),r=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!r){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(o)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,u)=>{let d=Ot("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),l=Ot("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(l.stdin);let p,f,S=()=>{if(p!==void 0&&f!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(f!==0)return u(new Error(`tar exited ${f}`));c()}};d.on("close",w=>{p=w,S()}),l.on("close",w=>{f=w,S()}),d.on("error",u),l.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(o,"");try{a(i)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new N("bundle-extract-failed",s.message)}}async function vo(t){let e=G(t,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${t}`);let o;try{o=await import(Io(e).href)}catch(i){throw new N("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=o.default||Object.values(o).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function Rt(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let o=ce(),n;try{n=To()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${t}' parent=${o.executionId||"<root>"}`);let i=await bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:o.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:r,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:c,workflowVersion:u,workflowUuid:d,bundleReady:l}=i,p=$o();if(s&&s!==p)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",error:{message:`runtimeTag mismatch: parent=${p} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${p} vs ${s}`);if(!l||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,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 f=Nt(t);if(!f){let m=G(Se,`${d}@${u||"0"}`);try{await Ao(a,m);try{ko()}catch{}}catch(y){throw y.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{f=await vo(m),xt(t,f,{workflowUuid:d,version:u,runtimeTag:s,cacheDir:m})}catch(y){throw kt(t,y),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let S=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await At({executionId:r,parentExecutionId:o.executionId,conversationId:e.conversationId!==void 0?e.conversationId:o.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-S}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",finalState:g,durationMs:Date.now()-S}});let m=new Error(`Sub-graph '${t}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=r,m}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"completed",finalState:g,durationMs:Date.now()-S}}),{finalState:g,executionId:r}}function xo(t){let e=0,o=[t];for(;o.length;){let n=o.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let r;try{r=Pt(n)}catch{continue}for(let s of r)o.push(G(n,s))}else e+=i.size}return e}function ko({cap:t=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(Se))return{evicted:0,freedBytes:0};let e=Pt(Se),o=[],n=0;for(let a of e){let c=G(Se,a),u;try{u=Ct(c)}catch{continue}let d=u.isDirectory()?xo(c):u.size;n+=d,o.push({name:a,full:c,size:d,mtimeMs:u.mtimeMs})}if(n<=t)return{evicted:0,freedBytes:0,totalBytes:n};o.sort((a,c)=>a.mtimeMs-c.mtimeMs);let i=Math.floor(t*.7),r=0,s=0;for(let a of o){if(n-r<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),r+=a.size,s+=1}catch(c){I.debug(`[sub-graph cache] evict skip ${a.name}: ${c.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(r/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:r,totalBytes:n-r}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var No=2e3,Oo=600*1e3,Co=new Set(["completed","failed","canceled","timeout"]);function Po(){let t=process.env.PROGRESS_API_URL;if(!t)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return t.replace(/\/executions\/?$/,"")}function Ro(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function Bo(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function Mo(){return process.env.EXECUTION_ID||null}function Bt(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((o,n)=>o==null?o:o[n],t):t}async function Fe(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let o=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((o.depth||0)>=n)throw new Error(`dispatchSubgraph('${t}'): sub-graph depth ${o.depth} reached cap of ${n}. 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 '${t}'`);let{finalState:m}=await Rt(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),y=Bt(m,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),y}catch(m){if(m instanceof N||m?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Po(),r=Ro(),s=Bo(),a=Mo(),c=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(t)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)});if(!d.ok){let m=null,y="";try{m=await d.json(),y=m?.error||m?.message||JSON.stringify(m)}catch{y=await d.text().catch(()=>"")}if(d.status===429){let A=m?.quotaInfo||{},R=new Error(`Sub-graph '${t}' 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=t,R.quotaInfo=A,R}if(d.status===400){let A=new Error(`Sub-graph '${t}' rejected input: ${y}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=t,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let O=new Error(`Sub-graph '${t}' trigger rejected (${d.status}): ${y}`);throw O.code="SUBGRAPH_TRIGGER_FAILED",O.status=d.status,O.subgraph=t,O}let l=await d.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:t};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:Oo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:No,w=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(A=>setTimeout(A,S)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let y=await m.json(),O=y?.data||y?.execution||y;if(E=O?.status||E,Co.has(E)){if(E!=="completed"){let _=new Error(`Sub-graph '${t}' (${p}) ended in status '${E}'`);throw _.subgraphJobId=p,_.subgraphStatus=E,_}let A=O?.finalState||O?.state||{},R=Bt(A,e.output);return I.info(`[sub-graph] '${t}' (${p}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${t}' (${p}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=p,g.subgraphStatus=E,g}import{existsSync as Mt,readFileSync as Lo}from"node:fs";import{join as Ge,dirname as Lt}from"node:path";var le=class{static async loadContext(e,o,n={}){let i={},r=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Lt(Ge(o,e));for(let c of r){let u=await this.findAndMergeContextFiles(c,a,o);if(u){let d=c.replace(/\.[^.]+$/,"").toLowerCase();i[d]=u}}}let s=n.discovery||{};for(let[a,c]of Object.entries(s))try{let u=Ge(o,c);Mt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${c}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,o,n){let i=[],r=o;for(;r.startsWith(n);){let s=Ge(r,e);if(Mt(s))try{i.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=Lt(r);if(a===r)break;r=a}return i.length===0?null:i.every(s=>typeof s=="string")?i.join(`
|
|
34
|
+
${r}`);let a=n(),c=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let l=De(u,U);if(bt(l)){let f=JSON.parse(Tt(l,"utf-8"));f.currentNode=this.name,Be(l,JSON.stringify(f,null,2),"utf-8")}let p=De(u,"..",U);if(bt(p))try{let f=JSON.parse(Tt(p,"utf-8"));f.currentNode=this.name,Be(p,JSON.stringify(f,null,2),"utf-8")}catch{}}}catch(l){I.debug(`[workflow] could not update session info: ${l.message}`)}let d=null;for(let l=0;l<=this.retries;l++)try{I.debug(`[workflow] node '${this.name}' attempt ${l}`);let p=n().config||{},f=p.agents||{},S=this.config.agent??f[this.name]??null,w={state:n()};S&&(w.preferredAgent=S);let $={workspace:c,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:u,config:p,nodeName:this.name,timeout:this.config?.timeout||3e5},E=e?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let h=await E(r,w,$),g,m;if(typeof h=="string"?(g=h,m=null):h.structured?(g=h.raw||JSON.stringify(h.structured,null,2),m=h.structured):(g=h.raw||JSON.stringify(h,null,2),m=h.extracted||null),u)try{let y=De(u,this.name,"raw_stream_output.txt");mo(So(y),{recursive:!0}),Be(y,typeof g=="string"?g:JSON.stringify(g),"utf-8")}catch(y){I.debug(`[workflow] could not save raw output: ${y.message}`)}if(this.isZodSchema&&m){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(m,null,2)}`);let y=m;if(typeof this.onComplete=="function")try{y=await this.onComplete(n(),m)}catch(O){I.warn(`[workflow] onComplete hook failed: ${O.message}`)}return{success:!0,output:y,raw:g}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:g}),raw:g}}catch(y){throw new Error(`onComplete failed: ${y.message}`,{cause:y})}if(this.parser){let y=this.parser.parse(g);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(y,null,2)}`),k.step("Output parsed"),{success:!0,output:y,raw:g}}return{success:!0,output:g,raw:g}}catch(p){d=p,l<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${l+1}/${this.retries})\u2026`)}return{success:!1,error:d.message,raw:null}}},Q=class extends j{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){let n=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(n)},raw:null}}};F();F();import{mkdirSync as _o,existsSync as Y,statSync as Ct,readdirSync as Pt,rmSync as Eo}from"node:fs";import{spawn as Ot}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as Io}from"node:url";import{AsyncLocalStorage as yo}from"node:async_hooks";var Me=new yo;function le(){let t=Me.getStore();return t||Object.freeze({executionId:process.env.EXECUTION_ID||null,parentExecutionId:process.env.PARENT_EXECUTION_ID||null,depth:0,conversationId:process.env.ZIBBY_CONVERSATION_ID||null,dispatchMode:process.env.DISPATCH_MODE||null})}function At(t,e){let o=Me.getStore()||le(),n=Object.freeze({executionId:t.executionId,parentExecutionId:t.parentExecutionId??o.executionId??null,depth:(o.depth||0)+(t.executionId!==o.executionId?1:0),conversationId:t.conversationId!==void 0?t.conversationId:o.conversationId??null,dispatchMode:t.dispatchMode??null});return Me.run(n,e)}var Le=new Map,je=new Map,vt=new Map;function kt(t,e,o={}){if(!t||typeof t!="string")throw new Error("subgraph-registry.register: name required");if(typeof e!="function")throw new Error("subgraph-registry.register: factory must be a function");Le.set(t,e),je.set(t,"ready"),vt.set(t,{...o,cachedAt:Date.now()})}function xt(t,e){je.set(t,"failed"),vt.set(t,{error:e?.message||String(e),failedAt:Date.now()}),Le.delete(t)}function Nt(t){return je.get(t)==="ready"?Le.get(t):null}var Se=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function $o(){return`node${(process.versions?.node||"").split(".")[0]||"unknown"}-${process.platform}-${process.arch}`}var N=class extends Error{constructor(e,o){super(`in-process sub-graph fallback: ${e}${o?` (${o})`:""}`),this.fallback=!0,this.reason=e,this.detail=o||null,this.name="SubgraphFallback"}};function To(){let t=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),o=t||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!o||!n||!i)throw new N("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:o,projectId:n,authToken:i}}async function bo({apiBase:t,authToken:e,body:o}){let n;try{n=await fetch(`${t}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)})}catch(r){throw new N("network",`begin fetch failed: ${r.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let r=new Error(`Sub-graph child '${o.childWorkflowType}' not found in project`);throw r.code="SUBGRAPH_NOT_FOUND",r.status=404,r}if(n.status===429){let r=i?.quotaInfo||{},s=new Error(`Sub-graph blocked by quota (${r.used??"?"}/${r.limit??"?"} on ${r.planId||"plan"})`);throw s.code="SUBGRAPH_QUOTA_EXCEEDED",s.status=429,s.quotaInfo=r,s}if(n.status===400&&i?.validationErrors){let r=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw r.code="SUBGRAPH_INVALID_INPUT",r.status=400,r.validationErrors=i.validationErrors,r.missing=i.missing,r}throw new N("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:t,authToken:e,payload:o}){try{let n=await fetch(`${t}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)});n.ok||I.warn(`[in-process subgraph] finalize returned ${n.status} for ${o.childExecutionId}`)}catch(n){I.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function Ao(t,e){let o=G(e,".ready"),n=G(e,"graph.mjs");if(Y(o)&&Y(n))return;_o(e,{recursive:!0});let i=G(e,".lock"),r=!1;try{let{openSync:s,closeSync:a}=await import("node:fs"),c=s(i,"wx");a(c),r=!0}catch(s){if(s.code!=="EEXIST")throw s}if(!r){let s=Date.now()+3e4;for(;Date.now()<s;){if(Y(o)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new N("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((c,u)=>{let d=Ot("curl",["-fsSL",t],{stdio:["ignore","pipe","inherit"]}),l=Ot("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});d.stdout.pipe(l.stdin);let p,f,S=()=>{if(p!==void 0&&f!==void 0){if(p!==0)return u(new Error(`curl exited ${p}`));if(f!==0)return u(new Error(`tar exited ${f}`));c()}};d.on("close",w=>{p=w,S()}),l.on("close",w=>{f=w,S()}),d.on("error",u),l.on("error",u)});let{writeFileSync:s,unlinkSync:a}=await import("node:fs");s(o,"");try{a(i)}catch{}}catch(s){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new N("bundle-extract-failed",s.message)}}async function vo(t){let e=G(t,"graph.mjs");if(!Y(e))throw new N("entry-missing",`graph.mjs missing under ${t}`);let o;try{o=await import(Io(e).href)}catch(i){throw new N("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=o.default||Object.values(o).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new N("entry-class-missing","no buildGraph() class export found");return n}async function Rt(t,e={}){if(!t||typeof t!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let o=le(),n;try{n=To()}catch(m){throw m}I.debug(`[in-process subgraph] begin '${t}' parent=${o.executionId||"<root>"}`);let i=await bo({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:o.executionId,childWorkflowType:t,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:r,runtimeTag:s,bundlePresignedUrl:a,sourcesPresignedUrl:c,workflowVersion:u,workflowUuid:d,bundleReady:l}=i,p=$o();if(s&&s!==p)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",error:{message:`runtimeTag mismatch: parent=${p} child=${s}`,code:"RUNTIME_MISMATCH"}}}),new N("runtime-mismatch",`${p} vs ${s}`);if(!l||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,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 f=Nt(t);if(!f){let m=G(Se,`${d}@${u||"0"}`);try{await Ao(a,m);try{xo()}catch{}}catch(y){throw y.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason}}}),y}try{f=await vo(m),kt(t,f,{workflowUuid:d,version:u,runtimeTag:s,cacheDir:m})}catch(y){throw xt(t,y),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:y.message,code:y.reason||"IMPORT_FAILED"}}}),y.fallback?y:new N("import-failed",y.message)}}let S=Date.now(),$=await(typeof f=="function"&&f.prototype?.buildGraph?new f:f).buildGraph(),E={...e.input||{}},h,g;try{h=await At({executionId:r,parentExecutionId:o.executionId,conversationId:e.conversationId!==void 0?e.conversationId:o.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,E,{signal:e.signal})),g=h&&typeof h=="object"&&"state"in h?h.state:h}catch(m){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"failed",error:{message:m.message,code:m.code||"CHILD_THREW",stack:m.stack},durationMs:Date.now()-S}}),m}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"canceled",finalState:g,durationMs:Date.now()-S}});let m=new Error(`Sub-graph '${t}' canceled by parent abort`);throw m.code="SUBGRAPH_CANCELED",m.subgraphJobId=r,m}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:r,status:"completed",finalState:g,durationMs:Date.now()-S}}),{finalState:g,executionId:r}}function ko(t){let e=0,o=[t];for(;o.length;){let n=o.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let r;try{r=Pt(n)}catch{continue}for(let s of r)o.push(G(n,s))}else e+=i.size}return e}function xo({cap:t=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(Se))return{evicted:0,freedBytes:0};let e=Pt(Se),o=[],n=0;for(let a of e){let c=G(Se,a),u;try{u=Ct(c)}catch{continue}let d=u.isDirectory()?ko(c):u.size;n+=d,o.push({name:a,full:c,size:d,mtimeMs:u.mtimeMs})}if(n<=t)return{evicted:0,freedBytes:0,totalBytes:n};o.sort((a,c)=>a.mtimeMs-c.mtimeMs);let i=Math.floor(t*.7),r=0,s=0;for(let a of o){if(n-r<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),r+=a.size,s+=1}catch(c){I.debug(`[sub-graph cache] evict skip ${a.name}: ${c.message}`)}}return s>0&&I.info(`[sub-graph cache] evicted ${s} entr(y/ies), freed ${(r/1024/1024).toFixed(1)}MB`),{evicted:s,freedBytes:r,totalBytes:n-r}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var No=2e3,Oo=600*1e3,Co=new Set(["completed","failed","canceled","timeout"]);function Po(){let t=process.env.PROGRESS_API_URL;if(!t)throw new Error("Sub-graph dispatch requires PROGRESS_API_URL env var (set automatically on cloud runs). Sub-graphs are not supported in local in-process runs yet \u2014 deploy the parent and child to cloud.");return t.replace(/\/executions\/?$/,"")}function Ro(){let t=process.env.PROJECT_ID;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return t}function Bo(){let t=process.env.PROJECT_API_TOKEN;if(!t)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return t}function Do(){return process.env.EXECUTION_ID||null}function Bt(t,e){return e==null?t:typeof e=="function"?e(t):typeof e=="string"?e.split(".").reduce((o,n)=>o==null?o:o[n],t):t}async function Fe(t,e={}){if(!t||typeof t!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let o=le(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((o.depth||0)>=n)throw new Error(`dispatchSubgraph('${t}'): sub-graph depth ${o.depth} reached cap of ${n}. 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 '${t}'`);let{finalState:m}=await Rt(t,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),y=Bt(m,e.output);return I.info(`[sub-graph] '${t}' completed in-process`),y}catch(m){if(m instanceof N||m?.fallback)I.info(`[sub-graph] in-process fallback for '${t}': ${m.reason||"unknown"} \u2014 using HTTP`);else throw m}let i=Po(),r=Ro(),s=Bo(),a=Do(),c=`${i}/projects/${encodeURIComponent(r)}/workflows/${encodeURIComponent(t)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${t}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)});if(!d.ok){let m=null,y="";try{m=await d.json(),y=m?.error||m?.message||JSON.stringify(m)}catch{y=await d.text().catch(()=>"")}if(d.status===429){let A=m?.quotaInfo||{},R=new Error(`Sub-graph '${t}' 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=t,R.quotaInfo=A,R}if(d.status===400){let A=new Error(`Sub-graph '${t}' rejected input: ${y}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=t,A.validationErrors=m?.validationErrors||null,A.missing=m?.missing||null,A}let O=new Error(`Sub-graph '${t}' trigger rejected (${d.status}): ${y}`);throw O.code="SUBGRAPH_TRIGGER_FAILED",O.status=d.status,O.subgraph=t,O}let l=await d.json(),p=l?.data?.jobId||l?.jobId;if(!p)throw new Error(`Sub-graph '${t}' trigger returned no jobId: ${JSON.stringify(l).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${t}' \u2192 jobId=${p} (not waiting)`),{jobId:p,status:"accepted",workflow:t};let f=Number.isFinite(e.timeoutMs)?e.timeoutMs:Oo,S=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:No,w=`${i}/executions/${encodeURIComponent(p)}`,$=Date.now()+f,E="accepted",h=0;for(;Date.now()<$;){await new Promise(A=>setTimeout(A,S)),h+=1;let m=await fetch(w,{headers:{Authorization:`Bearer ${s}`}});if(!m.ok){if(m.status>=500){I.warn(`[sub-graph] status poll for ${p} returned ${m.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${p}: ${m.status}`)}let y=await m.json(),O=y?.data||y?.execution||y;if(E=O?.status||E,Co.has(E)){if(E!=="completed"){let _=new Error(`Sub-graph '${t}' (${p}) ended in status '${E}'`);throw _.subgraphJobId=p,_.subgraphStatus=E,_}let A=O?.finalState||O?.state||{},R=Bt(A,e.output);return I.info(`[sub-graph] '${t}' (${p}) completed after ${h} polls`),R}}let g=new Error(`Sub-graph '${t}' (${p}) timed out after ${Math.round(f/1e3)}s (last status: ${E})`);throw g.subgraphJobId=p,g.subgraphStatus=E,g}import{existsSync as Dt,readFileSync as Mo}from"node:fs";import{join as Ge,dirname as Mt}from"node:path";var ue=class{static async loadContext(e,o,n={}){let i={},r=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Mt(Ge(o,e));for(let c of r){let u=await this.findAndMergeContextFiles(c,a,o);if(u){let d=c.replace(/\.[^.]+$/,"").toLowerCase();i[d]=u}}}let s=n.discovery||{};for(let[a,c]of Object.entries(s))try{let u=Ge(o,c);Dt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${c}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,o,n){let i=[],r=o;for(;r.startsWith(n);){let s=Ge(r,e);if(Dt(s))try{i.unshift(await this.loadFile(s))}catch(c){console.warn(`[workflow] could not load ${e} from ${s}: ${c.message}`)}let a=Mt(r);if(a===r)break;r=a}return i.length===0?null:i.every(s=>typeof s=="string")?i.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):i.every(s=>typeof s=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let o=
|
|
38
|
+
`):i.every(s=>typeof s=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let o=Mo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(o);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:n}=await import("url"),i=await import(n(e).href);return i.default||i}return o}};import{mkdirSync as Ft,existsSync as Ue,writeFileSync as Lt,unlinkSync as Lo}from"node:fs";import{join as z,resolve as Gt}from"node:path";import{config as jo}from"dotenv";import{zodToJsonSchema as jt}from"zod-to-json-schema";import{z as ye}from"zod";import Fo from"handlebars";function Go({traceFrom:t,sessionId:e,sessionPath:o,idSource:n,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let s=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${t} pid=${process.pid} ppid=${s} sessionId=${e} source=${n} mkdir=${i?"yes":"no"} path=${o}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let d=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${t}):
|
|
41
|
-
${d}`)}}function Ut(){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 Wt(){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 Gt(String(e).trim())}catch{return String(e).trim()}}function Ht(){Ut()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Jt({sessionPath:t,sessionId:e}){t&&typeof t=="string"&&(process.env.ZIBBY_SESSION_PATH=t),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Yt(t={}){let e=ke.map(r=>process.env[r]).find(Boolean),o=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${o}`,i=t.paths?.sessionPrefix;return i?`${i}_${n}`:n}function zt({cwd:t=process.cwd(),config:e={},initialState:o={},traceFrom:n="resolveWorkflowSession"}={}){let i=o.sessionPath,r=o.sessionTimestamp,s="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Gt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Yt(e),s="generated")}r=r??Date.now();let d=e.paths?.output||se;i=z(t,d,ve,a)}let c=!Ue(i);return c&&Ft(i,{recursive:!0}),(c||s!=="initialState.sessionPath")&&Go({traceFrom:n,sessionId:a,sessionPath:i,idSource:s,mkdirFresh:c}),Jt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:r}}var ue=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,o,n={}){if(!(o instanceof j)&&o&&typeof o=="object"&&typeof o.workflow=="string"){let r=o,s={name:e,_isCustomCode:!0,retries:r.retries,onComplete:r.onComplete,execute:async c=>{let u=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,d;return typeof r.input=="function"?d=r.input(u):r.input&&typeof r.input=="object"?d=r.input:d={},Fe(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(u):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:u?._signal,parentAgent:c?.agent})}},a=new j(s);return a.name=e,this.nodes.set(e,a),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=o instanceof j?o:new j(o);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof o?.prompt=="string"&&o.prompt.trim()&&this.nodePrompts.set(e,o.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addConditionalNode(e,o){return this.nodes.set(e,new Q({...o,name:e})),this}addEdge(e,o){return this.edges.set(e,o),this}setNodeType(e,o){return this.nodeTypeMap.set(e,o),this}addConditionalEdges(e,o,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:o,labels:n}),typeof o=="function"&&this.conditionalCodeMap.set(e,o.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,o,n,i,r){let s=n;for(let a=e.length-1;a>=0;a--){let c=e[a],u=s;s=()=>c(o,u,i,r)}return s()}serialize(){let e=[],o={};for(let[d,l]of this.nodes){let p=this.nodeTypeMap.get(d)||(l instanceof Q?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};l._isCustomCode&&typeof l.execute=="function"&&(f.customCode=l.execute.toString());let S=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;S&&(f.description=S);let w=this.nodePrompts.get(d);if(w)f.prompt=w;else if(typeof l.prompt=="function")try{let g=l.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(f.executeCode=l.customExecute.toString()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let g=null;if(typeof ye?.toJSONSchema=="function")try{g=ye.toJSONSchema(l.outputSchema)}catch{}if(!g)try{g=jt(l.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:l.outputSchema}}else f.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(o[d]=f)}let n=[];for(let[d,l]of this.edges)if(typeof l=="string")n.push({source:d,target:l});else if(l.conditional){let p=this.conditionalCodeMap.get(d)||l.routes.toString(),f=this._inferConditionalTargets(l.routes,l.labels),S=l.labels||{};for(let w of f){let $={source:d,target:w,data:{conditionalCode:p}};S[w]&&($.label=S[w]),n.push($)}}let i=d=>{if(!d)return null;if(typeof ye?.toJSONSchema=="function")try{return ye.toJSONSchema(d)}catch{}try{return jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let r=0;for(let d of n)if(d.target==="END"){r+=1;let l=`END__${r}`;d.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){r+=1;let l=`END__${r}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:l})}let s=this._runtimeSchema(),a=i(s||this.stateSchema),c=i(this.inputSchema),u=i(this.contextSchema);return{nodes:e,edges:n,nodeConfigs:o,stateSchema:a,inputSchema:c,contextSchema:u}}_inferConditionalTargets(e,o){let n=e.toString(),i=new Set,r=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=r.exec(n))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&i.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(o&&typeof o=="object")for(let u of Object.keys(o))a.add(u);let c=new Set;for(let u of i)a.has(u)&&c.add(u);if(c.size===0){let u=/return\s+['"]([^'"]+)['"]/g,d;for(;(d=u.exec(n))!==null;)c.add(d[1])}return[...c]}_flattenJsonSchemaToVariables(e,o=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,o)}_flattenSchema(e,o=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},r=e.required||[];for(let[s,a]of Object.entries(i)){let c=o?`${o}.${s}`:s;n.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!r.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${c}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,o=>o.toUpperCase()).trim()}_summarizeNodeOutput(e,o){if(!o||typeof o!="object")return[];let n=[];o.success!==void 0&&n.push(`Result: ${o.success?"passed":"failed"}`);for(let[i,r]of Object.entries(o))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof r=="string"&&r.length<=80)n.push(`${i}: ${r}`);else if(Array.isArray(r)){let s=r.length,a=r.filter(u=>u?.passed===!0).length,c=r.some(u=>u?.passed!==void 0);n.push(c?`${i}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${i}: ${s} items`)}if(n.length>=4)break}return n}async run(e,o={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let r=n.strategyAbortTimeoutMs??o.config?.strategyAbortTimeoutMs??5e3,s=o.cwd||process.cwd();jo({path:z(s,".env")});let a=o.config||{};if(!a||Object.keys(a).length===0)try{let T=z(s,".zibby.config.js");Ue(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=o.agentType;if(!c){let T=a?.agent;T?.provider?c=T.provider:T?.gemini?c="gemini":T?.claude?c="claude":T?.cursor?c="cursor":T?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let u=o.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},d=this._runtimeSchema();if(d){let T=d.safeParse(o);if(!T.success){let C=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`);throw console.error("\u274C Initial state validation failed:"),C.forEach(P=>console.error(` - ${P}`)),new Error(`State validation failed: ${C.join(", ")}`)}x.step("State validated against schema")}let l=Wt(),p=o.sessionPath||l;p||Ht();let{sessionPath:f,sessionTimestamp:S,sessionId:w}=zt({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:p,sessionTimestamp:o.sessionTimestamp}});x.step(`Session ${w}`);let $=await le.loadContext(o.specPath||"",s,u);Object.keys($).length>0&&x.step(`Context loaded: ${Object.keys($).join(", ")}`);let E=o.outputPath;!E&&o.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(o.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${o.specPath})`));let h=new te({...o,config:a,agentType:c,outputPath:E,sessionPath:f,sessionTimestamp:S,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(ie(),_t)),y=a.skills&&typeof a.skills=="object"?a.skills:{},O=Object.values(y).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let C of O)if(C.id===T)return C;return m(T)},R=new Set;for(let[,T]of this.nodes)for(let C of T.config?.skills||[])R.add(C);for(let T of R){let C=A(T);if(typeof C?.middleware=="function")try{let P=await C.middleware();typeof P=="function"&&g.set(T,P)}catch{}}let _=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,qt=0;try{for(;_&&_!=="END";){if(++qt>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let C=z(f,xe);if(Ue(C)){try{Do(C)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
41
|
+
${d}`)}}function Ut(){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 Wt(){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 Gt(String(e).trim())}catch{return String(e).trim()}}function Ht(){Ut()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Jt({sessionPath:t,sessionId:e}){t&&typeof t=="string"&&(process.env.ZIBBY_SESSION_PATH=t),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function Yt(t={}){let e=xe.map(r=>process.env[r]).find(Boolean),o=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${o}`,i=t.paths?.sessionPrefix;return i?`${i}_${n}`:n}function zt({cwd:t=process.cwd(),config:e={},initialState:o={},traceFrom:n="resolveWorkflowSession"}={}){let i=o.sessionPath,r=o.sessionTimestamp,s="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Gt(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,s="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),r==null&&(r=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,s="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(a=l,s="config.sessionId"):(a=Yt(e),s="generated")}r=r??Date.now();let d=e.paths?.output||ie;i=z(t,d,ve,a)}let c=!Ue(i);return c&&Ft(i,{recursive:!0}),(c||s!=="initialState.sessionPath")&&Go({traceFrom:n,sessionId:a,sessionPath:i,idSource:s,mkdirFresh:c}),Jt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:r}}var ee=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,o,n={}){if(!(o instanceof j)&&o&&typeof o=="object"&&typeof o.workflow=="string"){let r=o,s={name:e,_isCustomCode:!0,retries:r.retries,onComplete:r.onComplete,execute:async c=>{let u=c?.state&&typeof c.state.getAll=="function"?c.state.getAll():c,d;return typeof r.input=="function"?d=r.input(u):r.input&&typeof r.input=="object"?d=r.input:d={},Fe(r.workflow,{input:d,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(u):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:u?._signal,parentAgent:c?.agent})}},a=new j(s);return a.name=e,this.nodes.set(e,a),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=o instanceof j?o:new j(o);return i.name=e,this.nodes.set(e,i),n.prompt?this.nodePrompts.set(e,n.prompt):typeof o?.prompt=="string"&&o.prompt.trim()&&this.nodePrompts.set(e,o.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addConditionalNode(e,o){return this.nodes.set(e,new Q({...o,name:e})),this}addEdge(e,o){return this.edges.set(e,o),this}setNodeType(e,o){return this.nodeTypeMap.set(e,o),this}addConditionalEdges(e,o,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:o,labels:n}),typeof o=="function"&&this.conditionalCodeMap.set(e,o.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,o,n,i,r){let s=n;for(let a=e.length-1;a>=0;a--){let c=e[a],u=s;s=()=>c(o,u,i,r)}return s()}serialize(){let e=[],o={};for(let[d,l]of this.nodes){let p=this.nodeTypeMap.get(d)||(l instanceof Q?"decision":d);e.push({id:d,type:p,data:{nodeType:p,label:d}});let f={};l._isCustomCode&&typeof l.execute=="function"&&(f.customCode=l.execute.toString());let S=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;S&&(f.description=S);let w=this.nodePrompts.get(d);if(w)f.prompt=w;else if(typeof l.prompt=="function")try{let g=l.prompt({});typeof g=="string"&&g.trim()&&(f.prompt=g,f.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(f.executeCode=l.customExecute.toString()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let g=null;if(typeof ye?.toJSONSchema=="function")try{g=ye.toJSONSchema(l.outputSchema)}catch{}if(!g)try{g=jt(l.outputSchema,{target:"openApi3"})}catch{}f.outputSchema=g?{jsonSchema:g,variables:this._flattenJsonSchemaToVariables(g)}:{schema:l.outputSchema}}else f.outputSchema={schema:l.outputSchema};let $=(this.resolvedToolsMap||{})[d];$?.toolIds&&(f.tools=$.toolIds);let E=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;E&&E.length>0&&(f.skills=[...E]);let h=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;h&&h.length>0&&(f.stores=h.map(g=>g&&typeof g=="object"?{...g}:g)),Object.keys(f).length>0&&(o[d]=f)}let n=[];for(let[d,l]of this.edges)if(typeof l=="string")n.push({source:d,target:l});else if(l.conditional){let p=this.conditionalCodeMap.get(d)||l.routes.toString(),f=this._inferConditionalTargets(l.routes,l.labels),S=l.labels||{};for(let w of f){let $={source:d,target:w,data:{conditionalCode:p}};S[w]&&($.label=S[w]),n.push($)}}let i=d=>{if(!d)return null;if(typeof ye?.toJSONSchema=="function")try{return ye.toJSONSchema(d)}catch{}try{return jt(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let r=0;for(let d of n)if(d.target==="END"){r+=1;let l=`END__${r}`;d.target=l,e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){r+=1;let l=`END__${r}`;e.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:d,target:l})}let s=this._runtimeSchema(),a=i(s||this.stateSchema),c=i(this.inputSchema),u=i(this.contextSchema);return{nodes:e,edges:n,nodeConfigs:o,stateSchema:a,inputSchema:c,contextSchema:u}}_inferConditionalTargets(e,o){let n=e.toString(),i=new Set,r=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,s;for(;(s=r.exec(n))!==null;){let u=s[2]!==void 0?s[2]:s[3];u!==void 0&&u!==""&&i.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(o&&typeof o=="object")for(let u of Object.keys(o))a.add(u);let c=new Set;for(let u of i)a.has(u)&&c.add(u);if(c.size===0){let u=/return\s+['"]([^'"]+)['"]/g,d;for(;(d=u.exec(n))!==null;)c.add(d[1])}return[...c]}_flattenJsonSchemaToVariables(e,o=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,o)}_flattenSchema(e,o=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},r=e.required||[];for(let[s,a]of Object.entries(i)){let c=o?`${o}.${s}`:s;n.push({path:c,type:a.type||"unknown",label:a.description||this._formatLabel(s),optional:!r.includes(s)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,c)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${c}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,o=>o.toUpperCase()).trim()}_summarizeNodeOutput(e,o){if(!o||typeof o!="object")return[];let n=[];o.success!==void 0&&n.push(`Result: ${o.success?"passed":"failed"}`);for(let[i,r]of Object.entries(o))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof r=="string"&&r.length<=80)n.push(`${i}: ${r}`);else if(Array.isArray(r)){let s=r.length,a=r.filter(u=>u?.passed===!0).length,c=r.some(u=>u?.passed!==void 0);n.push(c?`${i}: ${a}/${s} passed${s-a?`, ${s-a} failed`:""}`:`${i}: ${s} items`)}if(n.length>=4)break}return n}async run(e,o={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let r=n.strategyAbortTimeoutMs??o.config?.strategyAbortTimeoutMs??5e3,s=o.cwd||process.cwd();jo({path:z(s,".env")});let a=o.config||{};if(!a||Object.keys(a).length===0)try{let T=z(s,".zibby.config.js");Ue(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let c=o.agentType;if(!c){let T=a?.agent;T?.provider?c=T.provider:T?.gemini?c="gemini":T?.claude?c="claude":T?.cursor?c="cursor":T?.codex?c="codex":c=process.env.AGENT_TYPE||"cursor"}let u=o.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},d=this._runtimeSchema();if(d){let T=d.safeParse(o);if(!T.success){let C=T.error.issues.map(P=>`${P.path.join(".")}: ${P.message}`);throw console.error("\u274C Initial state validation failed:"),C.forEach(P=>console.error(` - ${P}`)),new Error(`State validation failed: ${C.join(", ")}`)}k.step("State validated against schema")}let l=Wt(),p=o.sessionPath||l;p||Ht();let{sessionPath:f,sessionTimestamp:S,sessionId:w}=zt({cwd:s,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:p,sessionTimestamp:o.sessionTimestamp}});k.step(`Session ${w}`);let $=await ue.loadContext(o.specPath||"",s,u);Object.keys($).length>0&&k.step(`Context loaded: ${Object.keys($).join(", ")}`);let E=o.outputPath;!E&&o.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(o.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${o.specPath})`));let h=new oe({...o,config:a,agentType:c,outputPath:E,sessionPath:f,sessionTimestamp:S,context:$,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),g=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(ae(),_t)),y=a.skills&&typeof a.skills=="object"?a.skills:{},O=Object.values(y).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let C of O)if(C.id===T)return C;return m(T)},R=new Set;for(let[,T]of this.nodes)for(let C of T.config?.skills||[])R.add(C);for(let T of R){let C=A(T);if(typeof C?.middleware=="function")try{let P=await C.middleware();typeof P=="function"&&g.set(T,P)}catch{}}let _=this.entryPoint,pe=[],Ke=a?.recursionLimit??100,qt=0;try{for(;_&&_!=="END";){if(++qt>Ke)throw new Error(`Workflow exceeded recursion limit (${Ke}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let C=z(f,ke);if(Ue(C)){try{Lo(C)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),k.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};let P=this.nodes.get(_);if(!P)throw new Error(`Node '${_}' not found in graph`);let Ve=JSON.stringify({sessionPath:f,sessionTimestamp:S,currentNode:_,createdAt:new Date().toISOString(),config:h.get("config")}),Xt=z(f,U);Lt(Xt,Ve,"utf-8");let qe=h.get("config")?.paths?.output||ie,Qt=z(s,qe,U);Ft(z(s,qe),{recursive:!0});try{Lt(Qt,Ve,"utf-8")}catch{}let Xe=o.onPipelineProgress;if(typeof Xe=="function")try{Xe({cwd:s,sessionPath:f,sessionId:w,outputBase:h.get("config")?.paths?.output||ie,currentNode:_})}catch{}let eo=(this.resolvedToolsMap||{})[_]||null;h.set("_currentNodeTools",eo);let to=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",to[_]||{}),k.nodeStart(_);let Qe=Date.now(),fe=this.nodePrompts.get(_);if(!this._invokeAgent){let v=await Promise.resolve().then(()=>(X(),ce));this._invokeAgent=v.invokeAgent}let oo=this._invokeAgent,Ie={},no=P.config?.skills||[];for(let v of no){let B=A(v);if(typeof B?.invokeAgentOptions=="function")try{let b=B.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:_});b&&typeof b=="object"&&(Ie={...Ie,...b})}catch(b){console.warn(`[graph] skill '${v}' invokeAgentOptions threw: ${b.message}`)}}let et=async(v,B,b={})=>{let D=oo(v,B,{...Ie,...b,signal:i.signal});return D.catch(()=>{}),i.signal.aborted?D:Promise.race([D,new Promise((Z,K)=>{let L=()=>{setTimeout(()=>{let te=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${r}ms`);te.name="AbortError",K(te)},r)};i.signal.addEventListener("abort",L,{once:!0})})])},ro=async(v={},B={})=>{let b=B.prompt||"";if(fe){let D=this._compiledPrompts.get(_);D||(D=Fo.compile(fe,{noEscape:!0}),this._compiledPrompts.set(_,D));try{b=D(v)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${_}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!b)throw new Error(`No prompt template configured for node '${_}' and no prompt provided in options`);return et(b,{state:h.getAll(),images:B.images||[]},{model:B.model||h.get("model"),workspace:h.get("workspace"),schema:B.schema,...B,signal:i.signal})},tt=h.getAll(),so=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let v of so)Object.prototype.hasOwnProperty.call(tt,v)&&console.warn(`[workflow] node "${_}": state key "${v}" is shadowed by the engine context prop; read it via context.state.get('${v}')`);let ot={...tt,state:h,invokeAgent:ro,_coreInvokeAgent:et,agent:e,nodeId:_,promptTemplate:fe,getPromptTemplate:()=>fe};try{let v=(P.config?.skills||[]).map(L=>g.get(L)).filter(Boolean),B=[...this.middleware,...v],b;B.length>0?b=await this._composeMiddleware(B,_,async()=>P.execute(ot,h),h.getAll(),h):b=await P.execute(ot,h);let D=Date.now()-Qe;if(pe.push({node:_,success:b.success,duration:D,timestamp:new Date().toISOString()}),!b.success){if(i.signal.aborted)return k.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:pe,stoppedExternally:!0};h.append("errors",{node:_,error:b.error});let L=P.config?.retries||0,te=`${_}_retries`,he=h.getAll()[te]||0;if(he<L){k.stepInfo(`Retrying (attempt ${he+1}/${L})`),h.update({[te]:he+1,[`${_}_raw`]:b.raw});continue}throw k.nodeFailed(_,b.error,{duration:D}),new Error(`Node '${_}' failed after ${he} attempts: ${b.error}`)}h.update({[_]:b.output});let Z=this._summarizeNodeOutput(_,b.output);k.nodeComplete(_,{duration:D,details:Z});let K=this.edges.get(_);if(!K)_="END";else if(K.conditional){let L=K.routes(h.getAll());k.route(_,L),_=L}else _=K}catch(v){throw k.isInsideNode&&k.nodeFailed(_,v.message,{duration:Date.now()-Qe}),h.set("failed",!0),h.set("failedAt",_),v}}k.graphComplete();let T={success:!0,state:h.getAll(),executionLog:pe};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 We=Symbol.for("@zibby/agent-workflow.nodes");globalThis[We]||(globalThis[We]=new Map);var de=globalThis[We];function Zt(t,e){de.set(t,e)}function He(t){return de.get(t)}function we(t){return de.has(t)}function Uo(){return Array.from(de.keys())}function Je(t){let e=de.get(t);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Zt("ai_agent",{name:"ai_agent",factory:!0,create:(t,e={})=>({name:t,_isCustomCode:!0,execute:async o=>{let n=o?._coreInvokeAgent;n||(n=(await Promise.resolve().then(()=>(X(),ce))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",r=Wo(i,o),s=await n(r,{cwd:o.workspace||process.cwd(),model:o.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:s,nodeId:t},raw:typeof s=="string"?s:s.raw}}})});function Wo(t,e){let o=/@([\w.]+)/g,n=new Set,i;for(;(i=o.exec(t))!==null;)n.add(i[1]);if(n.size===0)return t;let r=[],s=new Set;for(let a of n){let c=a.split(".")[0];if(s.has(c))continue;let u=a.split(".").reduce((p,f)=>p?.[f],e);if(u===void 0)continue;let d=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),l=a.replace(/_/g," ").replace(/\b\w/g,p=>p.toUpperCase());r.push(`## ${l}
|
|
43
43
|
${d}`),a.includes(".")||s.add(c)}return r.length===0?t:`${t}
|
|
44
44
|
|
|
45
45
|
---
|
|
@@ -47,7 +47,7 @@ ${d}`),a.includes(".")||s.add(c)}return r.length===0?t:`${t}
|
|
|
47
47
|
|
|
48
48
|
${r.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}
|
|
50
|
+
`)}`}ae();F();var _e={};function ze(t,e){if(Array.isArray(e))return Ye(e);let o=_e[t];return!o||o.length===0?null:Ye(o)}function Ye(t){if(!Array.isArray(t)||t.length===0)return null;let e=[],o={},n=[];for(let i of t){let r=q(i);if(!r){I.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}n.push(i);for(let s of r.tools||[])e.push({name:s.name,description:s.description,input_schema:s.input_schema||{type:"object",properties:{}}});if(!o[r.serverName])if(typeof r.resolve=="function"){let s=r.resolve();s&&(o[r.serverName]={...s,toolPrefix:i})}else{let s={};for(let a of r.envKeys||[]){let c=process.env[a];c&&(s[a]=c)}o[r.serverName]={command:r.command,args:[...r.args||[]],env:s,toolPrefix:i}}}return n.length===0?null:{toolIds:n,claudeTools:e,mcpServers:o}}F();function Ho(t,e={}){let{nodes:o,edges:n,nodeConfigs:i={}}=t;if(!Array.isArray(o)||o.length===0)throw new M("Graph must have at least one node");if(!Array.isArray(n))throw new M("Graph edges must be an array");let r=new ee(e);e.stateSchema&&r.setStateSchema(e.stateSchema);let s=new Set,a=new Map,c={};for(let p of o){let f=Ee(p);a.set(p.id,{...p,resolvedType:f}),f==="decision"&&s.add(p.id)}for(let[p,f]of a){if(s.has(p))continue;let S=f.resolvedType,w=i[p]||{},$=ze(S,w.tools);$&&(c[p]=$);let E={};w.prompt&&(E.prompt=w.prompt);let h=we(S);if(I.debug(`[workflow] compiler: node "${p}" type="${S}" registered=${h}`),w.customCode&&!h)r.addNode(p,Kt(p,w.customCode,w),E),r.setNodeType(p,S);else if(h){let g=He(S);g.factory?r.addNode(p,g.create(p,{...w,resolvedTools:$}),E):r.addNode(p,g,E),r.setNodeType(p,S)}else if(w.executeCode)r.addNode(p,Kt(p,w.executeCode,w),E),r.setNodeType(p,S);else throw new M(`Unknown node type "${S}" for node "${p}". Did you forget to register it?`)}r.resolvedToolsMap=c;let u=new Set;for(let p of n)s.has(p.target)||u.add(p.target);let d=o.find(p=>!s.has(p.id)&&!u.has(p.id));if(!d)throw new M("Could not determine entry point: no node without incoming edges found");r.setEntryPoint(d.id);let l=zo(n,"source");for(let p of n)if(!s.has(p.source))if(s.has(p.target)){let f=p.target,S=l.get(f)||[];if(S.length===0)throw new M(`Decision node "${f}" has no outgoing edges`);let w=Zo(f,S,s);r.addConditionalEdges(p.source,w)}else r.addEdge(p.source,p.target);return r}function Jo(t){let e=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(t.nodes)||t.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(t.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let o=t.nodeConfigs||{};for(let a of t.nodes){let c=Ee(a);if(c==="decision"||we(c))continue;let u=o[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${c}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let n=new Set(t.nodes.map(a=>a.id));for(let a of t.edges)n.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),n.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let i=new Set(t.nodes.filter(a=>Ee(a)==="decision").map(a=>a.id)),r=new Set;for(let a of t.edges)i.has(a.target)||r.add(a.target);let s=t.nodes.filter(a=>!i.has(a.id)&&!r.has(a.id));s.length===0?e.push("No entry point found (every node has incoming edges)"):s.length>1&&e.push(`Multiple entry points found: ${s.map(a=>a.id).join(", ")}`);for(let a of i){let c=t.edges.filter(d=>d.source===a);c.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),c.some(d=>d.data?.conditionalCode||d.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Yo(t){return!t||!Array.isArray(t.nodes)?[]:t.nodes.filter(e=>Ee(e)!=="decision").map(e=>e.id)}function Ee(t){let e=t.data?.nodeType||t.data?.type||t.type;return e==="workflowNode"||e==="custom"||e==="default"?t.id:e}function zo(t,e){let o=new Map;for(let n of t){let i=n[e];o.has(i)||o.set(i,[]),o.get(i).push(n)}return o}function Zo(t,e,o){let n=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!n)throw new M(`Decision node "${t}" has no conditionalCode on its outgoing edges`);let i=n.data?.conditionalCode||n.conditionalCode,r=new Set(e.map(a=>a.target).filter(a=>!o.has(a))),s;try{let c=new Function(`return (${i})`)();s=u=>{let d=c(u);return r.has(d)||I.warn(`[workflow] conditional route from "${t}" returned "${d}" which is not in valid targets: ${[...r].join(", ")}`),d}}catch(a){throw new M(`Failed to compile conditionalCode for "${t}": ${a.message}`)}return s}function Kt(t,e,o={}){let n;try{n=new Function("invokeAgent","require","console",`return (${e})`)}catch(s){throw new M(`Failed to compile customCode for node "${t}": ${s.message}`)}let i=n(async(...s)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),ce));return a(...s)},typeof $e<"u"?$e:void 0,console),r=null;return o.outputSchema&&(r=o.outputSchema.jsonSchema||o.outputSchema),{name:t,_isCustomCode:!0,outputSchema:r,execute:async s=>{try{let a=await i(s);return typeof a=="object"&&"success"in a?a:{success:!0,output:a,raw:null}}catch(a){return{success:!1,error:a.message,raw:null}}}}}var M=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ae();var Ze=/^[a-z][a-z0-9_]{0,40}$/;function Ko(t){if(t==null)return[];if(!Array.isArray(t))return["stores must be an array of { name, description } objects"];let e=[],o=new Map;return t.forEach((n,i)=>{if(n==null||typeof n!="object"||Array.isArray(n)){e.push(`stores[${i}] must be an object { name, description }`);return}let{name:r}=n;if(typeof r!="string"||r.length===0){e.push(`stores[${i}] is missing a string "name"`);return}Ze.test(r)||e.push(`stores[${i}] name "${r}" is invalid \u2014 must match ${Ze} (lowercase letter first, then up to 40 of [a-z0-9_])`),o.has(r)?e.push(`stores[${i}] duplicate store name "${r}" (also at index ${o.get(r)}) \u2014 store names must be unique within a workflow`):o.set(r,i)}),e}Oe();X();function Vo(t,e={}){let{nodes:o,edges:n,nodeConfigs:i={}}=t,r=new Set,s=[],a=new Map;for(let $ of o){let E=$.data?.nodeType||$.type;a.set($.id,E),E==="decision"?r.add($.id):s.push({id:$.id,nodeType:E,label:$.data?.label||$.id})}let c=s.some($=>{let E=i[$.id]||{};return!E.customCode&&!E.executeCode}),{toolsPerNode:u,toolIdsByVar:d}=rn(s,i),{simpleEdges:l,conditionalEdges:p}=sn(n,r),f=an(s,n,r),S=[],w=e.workflowType||"workflow";return S.push(Xo(e)),S.push(Qo(w,{usesRegisteredNodes:c})),S.push(en(d)),S.push(tn(w)),S.push(on(s,i)),S.push(nn(s,f,l,p,u,w)),S.filter(Boolean).join(`
|
|
51
51
|
`)}function qo(t){let e={};for(let[o,n]of Object.entries(t)){let{tools:i,...r}=n;Object.keys(r).length>0&&(e[o]=r)}return e}function Xo(t){let e=t.workflowType||"workflow";return["// Generated workflow",`// ${t.projectId?`Project: ${t.projectId} | `:""}Type: ${e} | Version: ${t.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
52
|
`)}function Qo(t,{usesRegisteredNodes:e=!0}={}){let o=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&o.push("// import './register-nodes.js'; // register custom node types here"),o.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),o.join(`
|
|
53
53
|
`)}function en(t){if(t.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[o,n]of t)e.push(`const ${o} = getResolvedToolDefinitions(${JSON.stringify(n)}); // ${n.join(", ")}`);return e.push(""),e.join(`
|
|
@@ -56,4 +56,4 @@ ${r.join(`
|
|
|
56
56
|
`)}function nn(t,e,o,n,i,r){let s=["// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];s.push("export function buildGraph(options = {}) {"),s.push(" const graph = new WorkflowGraph(options);",""),s.push(" // Nodes");for(let c of t){let u=Vt(c.id);s.push(` graph.addNode('${c.id}', { name: '${c.id}', execute: ${u}_execute });`),s.push(` graph.setNodeType('${c.id}', '${c.nodeType}');`)}s.push("",` graph.setEntryPoint('${e}');`,""),(o.length>0||n.length>0)&&s.push(" // Edges");for(let c of o)s.push(` graph.addEdge('${c.source}', '${c.target}');`);for(let c of n){let u=c.code.split(`
|
|
57
57
|
`).map((d,l)=>l===0?d:` ${d}`).join(`
|
|
58
58
|
`);s.push(` graph.addConditionalEdges('${c.source}', ${u});`)}let a=[];for(let c of t){let u=i.get(c.id);u&&a.push(` '${c.id}': ${u},`)}return a.length>0&&s.push(""," graph.resolvedToolsMap = {",...a," };"),s.push(""," return graph;","}",""),s.push("export { nodeConfigs };",""),s.join(`
|
|
59
|
-
`)}function rn(t,e){let o=new Map,n=new Map;for(let i of t){let r=e[i.id]?.tools,s;if(Array.isArray(r)&&r.length>0)s=[...r].sort();else{let a=_e[i.nodeType];a?.length>0&&(s=[...a].sort())}if(s){let a=`${s.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,a),n.has(a)||n.set(a,s)}}return{toolsPerNode:o,toolIdsByVar:n}}function sn(t,e){let o=[],n=[],i=new Map,r=new Set;for(let s of t)i.has(s.source)||i.set(s.source,[]),i.get(s.source).push(s);for(let s of t)if(!e.has(s.source))if(e.has(s.target)){if(r.has(s.target))continue;r.add(s.target);let c=(i.get(s.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);c&&n.push({source:s.source,code:c.data?.conditionalCode||c.conditionalCode})}else o.push({source:s.source,target:s.target});return{simpleEdges:o,conditionalEdges:n}}function an(t,e,o){let n=new Set;for(let r of e)o.has(r.target)||n.add(r.target);let i=t.find(r=>!n.has(r.id));return i?i.id:t[0]?.id}function Vt(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}F();export{Ne as AgentStrategy,
|
|
59
|
+
`)}function rn(t,e){let o=new Map,n=new Map;for(let i of t){let r=e[i.id]?.tools,s;if(Array.isArray(r)&&r.length>0)s=[...r].sort();else{let a=_e[i.nodeType];a?.length>0&&(s=[...a].sort())}if(s){let a=`${s.map(c=>c.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;o.set(i.id,a),n.has(a)||n.set(a,s)}}return{toolsPerNode:o,toolIdsByVar:n}}function sn(t,e){let o=[],n=[],i=new Map,r=new Set;for(let s of t)i.has(s.source)||i.set(s.source,[]),i.get(s.source).push(s);for(let s of t)if(!e.has(s.source))if(e.has(s.target)){if(r.has(s.target))continue;r.add(s.target);let c=(i.get(s.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);c&&n.push({source:s.source,code:c.data?.conditionalCode||c.conditionalCode})}else o.push({source:s.source,target:s.target});return{simpleEdges:o,conditionalEdges:n}}function an(t,e,o){let n=new Set;for(let r of e)o.has(r.target)||n.add(r.target);let i=t.find(r=>!n.has(r.id));return i?i.id:t[0]?.id}function Vt(t){return t.replace(/[^a-zA-Z0-9]/g,"_")}F();export{Ne as AgentStrategy,xe as CI_ENV_VARS,M as CompilationError,Q as ConditionalNode,ue as ContextLoader,ie as DEFAULT_OUTPUT_BASE,ho as EVENTS_FILE,ee as Graph,_e as NODE_DEFAULT_TOOLS,go as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,j as Node,ne as OutputParser,fo as RAW_OUTPUT_FILE,po as RESULT_FILE,ve as SESSIONS_DIR,U as SESSION_INFO_FILE,ht as SKILLS,ke as STOP_REQUEST_FILE,Ze as STORE_NAME_REGEX,co as SchemaTypes,me as Timeline,ft as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,ee as WorkflowGraph,oe as WorkflowState,Ht as clearInheritedSessionEnvForFreshRun,wt as clearSkills,Ho as compileGraph,Fe as dispatchSubgraph,Yo as extractSteps,qo as generateNodeConfigsJson,Vo as generateWorkflowCode,Yt as generateWorkflowSessionId,Re as getAgentStrategy,St as getAllSkills,He as getNodeImpl,Je as getNodeTemplate,Ye as getResolvedToolDefinitions,q as getSkill,we as hasNode,mt as hasSkill,$t as invokeAgent,Uo as listNodeTypes,yt as listSkillIds,It as listStrategies,Wt as readPinnedSessionPathFromEnv,Zt as registerNode,gt as registerSkill,Et as registerStrategy,ze as resolveNodeTools,zt as resolveWorkflowSession,lo as setLogger,Ut as shouldTrustInheritedSessionEnv,Jt as syncProcessEnvToSession,k as timeline,Jo as validateGraphConfig,Ko as validateStoreDefs};
|
package/dist/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ct=Object.defineProperty;var A=(r,t)=>()=>(r&&(t=r(r=0)),t);var lt=(r,t)=>{for(var e in t)ct(r,e,{get:t[e],enumerable:!0})};var H,ut,
|
|
1
|
+
var ct=Object.defineProperty;var A=(r,t)=>()=>(r&&(t=r(r=0)),t);var lt=(r,t)=>{for(var e in t)ct(r,e,{get:t[e],enumerable:!0})};var H,ut,k,u,L=A(()=>{H=()=>{},ut={debug:H,info:H,warn:(...r)=>console.warn("[workflow]",...r),error:(...r)=>console.error("[workflow]",...r)},k={impl:ut},u={debug:(...r)=>k.impl.debug?.(...r),info:(...r)=>k.impl.info?.(...r),warn:(...r)=>k.impl.warn?.(...r),error:(...r)=>k.impl.error?.(...r)}});var X=A(()=>{});function Q(r){return ft.get(r)||null}var P,ft,tt=A(()=>{P=Symbol.for("@zibby/agent-workflow.skills");globalThis[P]||(globalThis[P]=new Map);ft=globalThis[P]});var rt={};lt(rt,{getAgentStrategy:()=>et,invokeAgent:()=>_t,listStrategies:()=>gt,registerStrategy:()=>mt});function mt(r){if(!r||typeof r.getName!="function"||typeof r.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let t=y.findIndex(e=>e.getName()===r.getName());t>=0?y[t]=r:y.push(r)}function gt(){return y.map(r=>r.getName())}function et(r={}){let{state:t={},preferredAgent:e=null}=r,o=e||t.agentType||process.env.AGENT_TYPE;if(!o){let i=y.map(c=>c.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${i}`)}u.debug(`[workflow] agent selection: requested=${o}`);let a=y.find(i=>i.getName()===o);if(!a){let i=y.map(c=>c.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${o}'. Available: ${i}`)}if(!a.canHandle(r))throw new Error(`Agent '${o}' is not available in this environment. Check credentials/environment.`);return u.debug(`[workflow] using agent: ${a.getName()}`),a}async function _t(r,t={},e={}){let o=t.state&&typeof t.state.getAll=="function"?t.state.getAll():t.state||{},a={...t,state:o},i=et(a),c=o.config||e.config||{},_=c.models||{},d=e.nodeName&&_[e.nodeName]||null,S=_.default||null,N=c.agent?.[i.name]?.model||null,s=d||S||N||e.model||null,m={...e,model:s,workspace:o.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:c},h=r,I=m.skills||[];if(I.length>0&&!e.skipPromptFragments){let E=I.map(f=>{let n=Q(f)?.promptFragment;return typeof n=="function"?n():n}).filter(Boolean);E.length>0&&(h+=`
|
|
2
2
|
|
|
3
3
|
${E.join(`
|
|
4
4
|
|
|
@@ -14,9 +14,9 @@ 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
|
${b}
|
|
17
|
-
`),u.debug(`[workflow] prompt length: ${h.length} chars`),i.invoke(h,m)}var
|
|
17
|
+
`),u.debug(`[workflow] prompt length: ${h.length} chars`),i.invoke(h,m)}var D,y,ot=A(()=>{X();L();tt();D=Symbol.for("@zibby/agent-workflow.strategies");globalThis[D]||(globalThis[D]=[]);y=globalThis[D]});import O from"handlebars";var R=class{constructor(t){this.schema=t}parse(t){let e=t.match(/```json\s*([\s\S]*?)\s*```/);if(e)return this.validate(JSON.parse(e[1]));let o=[t.match(/\{[\s\S]*?\}/),t.match(/\{[\s\S]*\}/)].filter(Boolean).map(a=>a[0]);for(let a of o)try{return this.validate(JSON.parse(a))}catch(i){if(!(i instanceof SyntaxError))throw i}return this.validate({result:t.trim()})}validate(t){let e=[];for(let[o,a]of Object.entries(this.schema)){if(a.required&&!(o in t)&&e.push(`Missing required field: ${o}`),o in t&&a.type){let i=typeof t[o];i!==a.type&&e.push(`Field '${o}' expected ${a.type}, got ${i}`)}if(a.validate&&o in t){let i=a.validate(t[o]);i&&e.push(`Field '${o}': ${i}`)}}if(e.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${e.join(`
|
|
19
|
-
`)}`);return t}};L();import{writeFileSync as
|
|
19
|
+
`)}`);return t}};L();import{writeFileSync as G,readFileSync as it,existsSync as st,mkdirSync as St}from"node:fs";import{join as M,dirname as wt}from"node:path";import p from"chalk";var pt="__WORKFLOW_GRAPH_LOG__",$=p.gray("\u2502"),dt=p.gray("\u250C"),K=p.gray("\u2514"),W=p.green("\u25C6"),U=p.hex("#c084fc")("\u25C6"),J=p.hex("#2dd4bf")("\u25C6"),x=p.red("\u25C6"),Y=`${$} `,V=2;function Z(r){return r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function z(r,t){return(e,o,a)=>{if(typeof e!="string")return r(e,o,a);let i=process.stdout.columns||120,c="";for(let _=0;_<e.length;_++){let d=e[_];t.lineStart&&(c+=Y,t.col=V,t.lineStart=!1),d===`
|
|
20
20
|
`?(c+=d,t.lineStart=!0,t.col=0,t.inEsc=!1):d==="\x1B"?(t.inEsc=!0,c+=d):t.inEsc?(c+=d,(d>="A"&&d<="Z"||d>="a"&&d<="z")&&(t.inEsc=!1)):(t.col++,c+=d,t.col>=i&&(c+=`
|
|
21
21
|
${Y}`,t.col=V))}return r(c,o,a)}}var C=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let t={lineStart:!0,col:0,inEsc:!1},e={lineStart:!0,col:0,inEsc:!1};this._outState=t,this._errState=e,process.stdout.write=z(this._origStdoutWrite,t),process.stderr.write=z(this._origStderrWrite,e)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
@@ -29,6 +29,6 @@ ${Y}`,t.col=V))}return r(c,o,a)}}var C=class{constructor(){this._currentNode=nul
|
|
|
29
29
|
`)}stepInfo(t){this.step(t)}stepTool(t){this._origStdoutWrite?this._writeDot(U,t):process.stdout.write.bind(process.stdout)(`${$} ${U} ${t}
|
|
30
30
|
`)}stepMemory(t){let e=p.hex("#2dd4bf")(t);this._origStdoutWrite?this._writeDot(J,e):process.stdout.write.bind(process.stdout)(`${$} ${J} ${e}
|
|
31
31
|
`)}stepFail(t){this._origStdoutWrite?this._writeDot(x,p.red(t)):process.stdout.write.bind(process.stdout)(`${$} ${x} ${p.red(t)}
|
|
32
|
-
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${dt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:a}=e;if(a)for(let c of a)this._rawWrite(`${W} ${c}`);let i=o?p.dim(` ${Z(o)}`):"";this._rawWrite(`${K} ${p.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:a}=o,i=a?p.dim(` ${Z(a)}`):"";this._rawWrite(`${x} ${p.red(e)}`),this._rawWrite(`${K} ${p.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(p.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},q=new C;var v=".session-info.json";var ht={BROWSER:"browser",JIRA:"jira",GITHUB:"github",GITLAB:"gitlab",FIGMA:"figma",OPEN_DESIGN:"open-design",GIT:"git",GIT_WRITE:"git-write",SLACK:"slack",LARK:"lark",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",LINEAR:"linear",PLANE:"plane",CODEBASE_MEMORY:"codebase-memory",DATASET_STORE:"dataset-store",LINKEDIN:"linkedin",CIRCLECI:"circleci",TRIGGER_AGENT:"trigger-agent"},Nt=Object.freeze([ht.CODEBASE_MEMORY]);
|
|
32
|
+
`)}nodeStart(t){this._currentNode=t,this._emitGraphLogMarker({phase:"node_begin",node:t}),this._rawWrite(`${dt} ${t}`),this._startIntercepting()}nodeComplete(t,e={}){this._stopIntercepting();let{duration:o,details:a}=e;if(a)for(let c of a)this._rawWrite(`${W} ${c}`);let i=o?p.dim(` ${Z(o)}`):"";this._rawWrite(`${K} ${p.green("done")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}nodeFailed(t,e,o={}){this._stopIntercepting();let{duration:a}=o,i=a?p.dim(` ${Z(a)}`):"";this._rawWrite(`${x} ${p.red(e)}`),this._rawWrite(`${K} ${p.red("failed")}${i}`),this._emitGraphLogMarker({phase:"node_end",node:t}),this._rawWrite("")}route(t,e){this._rawWrite(p.dim(` ${t} \u2192 ${e}`)),this._rawWrite("")}graphComplete(){}},q=new C;var v=".session-info.json";var ht={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"},Nt=Object.freeze([ht.CODEBASE_MEMORY]);O.helpers.inc||O.registerHelper("inc",r=>Number(r)+1);O.helpers.json||O.registerHelper("json",r=>JSON.stringify(r,null,2));O.helpers.eq||O.registerHelper("eq",(r,t)=>r===t);var F=class{constructor(t){if(this.config=t,this.name=t.name,this.prompt=t.prompt,this.outputSchema=t.outputSchema,!this.outputSchema&&!t._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=t.outputSchema&&!this.isZodSchema?new R(t.outputSchema):null,this.retries=t.retries||0,this.onComplete=t.onComplete,this.customExecute=t.execute}async execute(t,e){let o=()=>e&&typeof e.getAll=="function"?e.getAll():t,a=s=>e&&typeof e.get=="function"?e.get(s):t?.[s];if(typeof this.customExecute=="function"){u.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let s=await this.customExecute(t);return typeof s=="object"&&s!==null&&s.success===!1?{success:!1,error:s.error||"Node execution failed",raw:s.raw||null}:this.isZodSchema?(u.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(s),raw:null}):{success:!0,output:s,raw:null}}catch(s){return u.error(`[workflow] node '${this.name}' failed: ${s.message}`),s.name==="ZodError"&&u.error(`Schema errors: ${JSON.stringify(s.issues||s.errors,null,2)}`),{success:!1,error:s.message,raw:null}}}let i;typeof this.prompt=="function"?i=this.prompt(o()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=O.compile(this.prompt,{noEscape:!0})),i=this._compiledPrompt(o())):i=this.prompt;let c=a("_skillHints");c&&(i=`${c}
|
|
33
33
|
|
|
34
|
-
${i}`);let _=o(),d=_.cwd||process.cwd(),S=_.sessionPath;try{if(S){let s=
|
|
34
|
+
${i}`);let _=o(),d=_.cwd||process.cwd(),S=_.sessionPath;try{if(S){let s=M(S,v);if(st(s)){let h=JSON.parse(it(s,"utf-8"));h.currentNode=this.name,G(s,JSON.stringify(h,null,2),"utf-8")}let m=M(S,"..",v);if(st(m))try{let h=JSON.parse(it(m,"utf-8"));h.currentNode=this.name,G(m,JSON.stringify(h,null,2),"utf-8")}catch{}}}catch(s){u.debug(`[workflow] could not update session info: ${s.message}`)}let N=null;for(let s=0;s<=this.retries;s++)try{u.debug(`[workflow] node '${this.name}' attempt ${s}`);let m=o().config||{},h=m.agents||{},I=this.config.agent??h[this.name]??null,w={state:o()};I&&(w.preferredAgent=I);let b={workspace:d,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:S,config:m,nodeName:this.name,timeout:this.config?.timeout||3e5},E=t?._coreInvokeAgent;E||(E=(await Promise.resolve().then(()=>(ot(),rt))).invokeAgent);let f=await E(i,w,b),n,g;if(typeof f=="string"?(n=f,g=null):f.structured?(n=f.raw||JSON.stringify(f.structured,null,2),g=f.structured):(n=f.raw||JSON.stringify(f,null,2),g=f.extracted||null),S)try{let l=M(S,this.name,"raw_stream_output.txt");St(wt(l),{recursive:!0}),G(l,typeof n=="string"?n:JSON.stringify(n),"utf-8")}catch(l){u.debug(`[workflow] could not save raw output: ${l.message}`)}if(this.isZodSchema&&g){u.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(g,null,2)}`);let l=g;if(typeof this.onComplete=="function")try{l=await this.onComplete(o(),g)}catch(T){u.warn(`[workflow] onComplete hook failed: ${T.message}`)}return{success:!0,output:l,raw:n}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(o(),{raw:n}),raw:n}}catch(l){throw new Error(`onComplete failed: ${l.message}`,{cause:l})}if(this.parser){let l=this.parser.parse(n);return u.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(l,null,2)}`),q.step("Output parsed"),{success:!0,output:l,raw:n}}return{success:!0,output:n,raw:n}}catch(m){N=m,s<this.retries&&u.info(`[workflow] node '${this.name}' failed, retrying (${s+1}/${this.retries})\u2026`)}return{success:!1,error:N.message,raw:null}}},nt=class extends F{constructor(t){super({...t,_isCustomCode:!0}),this.condition=t.condition}async execute(t,e){let o=e&&typeof e.getAll=="function"?e.getAll():t;return{success:!0,output:{nextNode:this.condition(o)},raw:null}}};export{nt as ConditionalNode,F as Node};
|