@zibby/agent-workflow 0.4.32 β 0.4.34
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 +22 -10
- package/dist/compose-knowledge.d.ts +27 -0
- package/dist/compose-knowledge.js +70 -0
- package/dist/graph-compiler.js +1 -1
- package/dist/graph.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +97 -28
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
|
|
10
10
|
π **Full docs:** [docs.zibby.app](https://docs.zibby.app) Β· [Get Started](https://docs.zibby.app/get-started/install) Β· [Concepts](https://docs.zibby.app/concepts/graph) Β· [CLI Reference](https://docs.zibby.app/cli-reference) Β· [Cloud](https://docs.zibby.app/cloud/triggering)
|
|
11
11
|
|
|
12
|
-
> **The cloud pipeline for Claude Code,
|
|
12
|
+
> **The cloud pipeline for Claude Code, Codex, and Gemini.** Compose them into structured workflows with Zod-validated handoff between nodes. Vendor-neutral, JavaScript-first, runs locally or in our cloud.
|
|
13
13
|
|
|
14
14
|
```
|
|
15
15
|
ββββββββββββ ββββββββββββ ββββββββββββ
|
|
16
16
|
trigger β β plan β β β implementβ β β verify β β result
|
|
17
|
-
β (claude) β β (
|
|
17
|
+
β (claude) β β (codex) β β (gemini) β
|
|
18
18
|
ββββββββββββ ββββββββββββ ββββββββββββ
|
|
19
19
|
β β β
|
|
20
20
|
Zod out Zod out Zod out
|
|
@@ -22,16 +22,16 @@
|
|
|
22
22
|
|
|
23
23
|
Each node hands off to a complete agent. The agent does its own tool calls, file edits, and multi-turn reasoning. Your graph defines *what* agent runs *when*, *what schema* it has to return, and *what state* flows between them.
|
|
24
24
|
|
|
25
|
-
Mix and match agents per node β Claude for planning,
|
|
25
|
+
Mix and match agents per node β Claude for planning, Codex for implementation, Gemini for verification. Or stick with one. Your call:
|
|
26
26
|
|
|
27
27
|
```js
|
|
28
28
|
graph
|
|
29
29
|
.addNode('plan', { prompt, outputSchema: Plan, agent: 'claude' })
|
|
30
|
-
.addNode('implement', { prompt, outputSchema: Diff, agent: '
|
|
31
|
-
.addNode('verify', { prompt, outputSchema: Result, agent: '
|
|
30
|
+
.addNode('implement', { prompt, outputSchema: Diff, agent: 'codex' })
|
|
31
|
+
.addNode('verify', { prompt, outputSchema: Result, agent: 'gemini' });
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
Each agent reads its own credential env var (`ANTHROPIC_API_KEY`, `
|
|
34
|
+
Each agent reads its own credential env var (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`). In **Zibby Cloud** you can set those per-workflow β different keys per pipeline, no global state β see [Per-workflow env vars](https://docs.zibby.app/cloud/env-vars). Per-node `model` overrides come from `.zibby.config.mjs` (`models: { node_id: 'claude-opus-4.6' }`), which the CLI ships to cloud as part of the deploy bundle.
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
@@ -140,11 +140,11 @@ See [`examples/`](./examples/) for runnable demos of each pattern.
|
|
|
140
140
|
|
|
141
141
|
| | What it does | Why this is different |
|
|
142
142
|
|---|---|---|
|
|
143
|
-
| **LangGraph** | Python-first graph runtime over LangChain β nodes are LangChain agents or LLM calls, state is shared via the graph. | Our nodes hand off to **external coding-agent CLIs** (Claude Code,
|
|
143
|
+
| **LangGraph** | Python-first graph runtime over LangChain β nodes are LangChain agents or LLM calls, state is shared via the graph. | Our nodes hand off to **external coding-agent CLIs** (Claude Code, OpenAI Codex, Gemini CLI) β independent processes that own their own tool use, multi-turn loops, and file edits. JS-first, no Python interop, no LangChain assembly. |
|
|
144
144
|
| **n8n / Zapier** | Visual workflow editor β wire SaaS APIs together. | Code-first, no UI. Built around composing coding-agent CLIs against your repo, not connecting SaaS APIs. |
|
|
145
145
|
| **CrewAI / AutoGen** | Multi-agent role-play β agents converse to solve a task. | No agent debate. Each node is a discrete, schema-validated invocation. Deterministic edges, retry-friendly. |
|
|
146
146
|
|
|
147
|
-
If you want to compose Claude Code +
|
|
147
|
+
If you want to compose Claude Code + Codex + Gemini into one pipeline with structured handoff between them β JS, no Python, no LangChain β this is that.
|
|
148
148
|
|
|
149
149
|
---
|
|
150
150
|
|
|
@@ -238,7 +238,7 @@ Examples 01β03 and 05 use a fake agent β no API key required.
|
|
|
238
238
|
|
|
239
239
|
## Why graph-of-agents
|
|
240
240
|
|
|
241
|
-
Real coding agents (Claude Code,
|
|
241
|
+
Real coding agents (Claude Code, OpenAI Codex, Gemini CLI) are themselves capable runtimes β they edit files, run shells, call MCP tools, handle multi-turn. But on their own they have no memory across runs and no way to verify their own output.
|
|
242
242
|
|
|
243
243
|
A graph gives you:
|
|
244
244
|
|
|
@@ -258,13 +258,25 @@ You're not replacing the agent. You're giving it a job description, a contract,
|
|
|
258
258
|
| Package | What it adds |
|
|
259
259
|
|---|---|
|
|
260
260
|
| [`@zibby/cli`](https://www.npmjs.com/package/@zibby/cli) | `zibby` command β scaffold, dev server, deploy, trigger, logs. |
|
|
261
|
-
| [`@zibby/core`](https://www.npmjs.com/package/@zibby/core) | Built-in agent strategies (Claude /
|
|
261
|
+
| [`@zibby/core`](https://www.npmjs.com/package/@zibby/core) | Built-in agent strategies (Claude / Codex / Gemini / OpenAI Assistant), MCP client, runtime. |
|
|
262
262
|
| [`@zibby/skills`](https://www.npmjs.com/package/@zibby/skills) | Pre-built skills (browser via Playwright MCP, GitHub, Jira, Slack, memory). |
|
|
263
263
|
|
|
264
264
|
Workflow itself ships **zero agent strategies and zero skills** β bring your own, or `npm install @zibby/core @zibby/skills` for the batteries-included experience.
|
|
265
265
|
|
|
266
266
|
---
|
|
267
267
|
|
|
268
|
+
## Self-hosted Zibby (single VM)
|
|
269
|
+
|
|
270
|
+
Run the **full Zibby platform** β control plane + agents + marketplace β on your own box:
|
|
271
|
+
|
|
272
|
+
```bash
|
|
273
|
+
curl -fsSL https://dl.zibby.app/selfhosted/latest/install.sh | bash
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Requirements: Docker + ~8 GB RAM. The installer downloads the release bundle, `docker load`s the images locally (**no registry login needed**), generates secrets, brings the stack up, and prints your dashboard URL + access token. Free tier: up to 10 deployed agents.
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
268
280
|
## Status
|
|
269
281
|
|
|
270
282
|
`0.1.x`. The public protocol surface is stable and consumed by Zibby Studio + tooling:
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* compose-knowledge.js β the CANONICAL, single-source COMPOSE knowledge.
|
|
3
|
+
*
|
|
4
|
+
* "Compose" = chaining independently-deployed marketplace agents (bricks) with
|
|
5
|
+
* a small project-private WRAPPER workflow, via this engine's sub-workflow
|
|
6
|
+
* primitives (`workflow:` nodes / dispatchSubgraph). The rules below are
|
|
7
|
+
* platform truths that every composing surface must agree on, so they live
|
|
8
|
+
* HERE β next to the primitives they describe β and are IMPORTED by all three
|
|
9
|
+
* consumers instead of being hand-copied:
|
|
10
|
+
*
|
|
11
|
+
* 1. the Copilot chat-ops skill (@zibby/skills-internal zibby-control-plane
|
|
12
|
+
* promptFragment β the COMPOSE bullet),
|
|
13
|
+
* 2. the agent-builder marketplace template (generate node's authoring
|
|
14
|
+
* knowledge block),
|
|
15
|
+
* 3. the `zibby init` CLAUDE.md Β§10 (stamped between managed markers by
|
|
16
|
+
* packages/scripts/sync-compose-knowledge.mjs).
|
|
17
|
+
*
|
|
18
|
+
* Each consumer may ADD its own surface-specific glue (delegation mechanics,
|
|
19
|
+
* CLI commands, self-host caveats) but must not restate these rules. Editing
|
|
20
|
+
* policy: change the text here, bump this package, let the consumers re-sync
|
|
21
|
+
* β never edit a consumer's copy in place.
|
|
22
|
+
*
|
|
23
|
+
* The text is audience-neutral markdown addressed to "the wrapper author" β
|
|
24
|
+
* an AI builder agent, a local Claude/Codex session, or a human.
|
|
25
|
+
*/
|
|
26
|
+
export const COMPOSE_KNOWLEDGE: "## Composing deployed agents (wrapper over marketplace bricks)\n\n**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER\nmodify a brick template's source and never rebuild its logic from scratch.\nThe composition is a small project-private WRAPPER workflow that dispatches\nalready-DEPLOYED bricks as sub-workflows. A forked/edited brick falls off the\nupgrade path.\n\n**Reuse policy \u2014 ask, never silently choose.** If a needed brick is already\ndeployed in the project, the user decides: reuse that instance (runs + config\nare shared with its standalone use) or deploy a dedicated instance under a\ncustom name (config isolation).\n\n**Sub-workflow node.** Declare a child dispatch by giving addNode a config\nwith a `workflow:` field \u2014 the DEPLOYED slug in the SAME project (the row's\nworkflowType, not the marketplace slug, when they differ):\n\n graph.addNode('review', {\n workflow: 'gitlab-code-review', // deployed slug\n input: (state) => ({ projectId: state.projectId, mrIid: state.mrIid }),\n timeoutMs: 15 * 60 * 1000,\n });\n\nThe engine runs the child in-process (same worker) when possible and the\nchild's FINAL state \u2014 whichever End it exited \u2014 lands at `state[nodeName]`.\nOptions: `workflow` (required), `input` (object or `(state) => object`),\n`output` (dot-path or `(finalState) => any` to extract just what's needed),\n`async: true` (fire-and-forget \u2192 `{ jobId }`), `timeoutMs`, `retries`.\nFor PARALLEL fan-out call `dispatchSubgraph(slug, { input })` (exported by\n@zibby/agent-workflow) inside one custom execute node with\n`Promise.allSettled` \u2014 one brick failing must not kill its siblings.\n\n**Chain conditions are EXPLICIT decision nodes.** Bricks are full multi-exit\ngraphs, so branch on the child's RETURNED state between dispatches \u2014 and model\nthe branch so the graph SHOWS it: a router node\n(`graph.addNode('<id>', { description })` \u2014 no execute/prompt/outputSchema;\nrenders as the Condition diamond) routed with\n`graph.addConditionalEdges('<id>', routeFn, { labels })`. Never an unlabeled\ndispatch\u2192End edge. Note the child's own node outputs are NESTED\n(`state.review.review.posted` = the child's `review` node output), e.g. only\nmeter when `state.review?.review?.posted === true && state.review?.trigger\n!== 'comment_reply'`.\n\n**Input mapping is the wrapper's job \u2014 use the brick's CANONICAL structured\nfields.** In-process children run the brick's graph directly and SKIP any\nconvenience normalization its class run() does on cold starts (e.g.\ngitlab-code-review parses mrUrl \u2192 projectId+mrIid only on cold runs \u2014 pass\nprojectId/mrIid yourself).\n\n**Credentials/config: children use their OWN row's env** (engine \u22650.4.32 +\nmatching backend). A brick's per-workflow env (Env tab / envSecret) applies to\nits in-process wrapped runs too \u2014 the child's value wins, the wrapper's env is\nonly the fallback for keys the brick doesn't define. So the wrapper needs ZERO\ncredential duplication: leave each brick's creds (e.g.\nCLAUDE_CODE_OAUTH_TOKEN) on the brick itself and give the wrapper none.\n(Env-carrying children serialize when dispatched in parallel; env-less ones\nkeep full parallelism. On older engines children inherit only the wrapper env\n\u2014 symptom: authentication_failed inside the child.) A brick's saved per-node\ncustom prompts (nodeConfigOverrides.<node>.extraPromptInstructions) apply\nin-process since \u22650.4.30, and its stores bindings ride along since \u22650.4.32.\n\n**Triggers \u2014 INHERIT the entry brick's events, read not invent.** The\nwrapper's trigger is AGENT-DRIVEN, never hardcoded: for webhook compositions\nthe wrapper's workflow.json `triggers.events` is a verbatim COPY of whatever\nthe ENTRY brick declares \u2014 read it from the brick's deployed row (or its\ntemplate workflow.json) and paste the exact array. The platform then\nautomatically SUPPRESSES the wrapped members' own subscriptions (any workflow\nlisted in a deployed wrapper's composedOf stops receiving standalone webhook\nevents), so the same event never double-fires a brick inside AND outside the\nwrapper. Cron / manual / chat-triggered compositions need nothing special.";
|
|
27
|
+
export default COMPOSE_KNOWLEDGE;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
var e=`## Composing deployed agents (wrapper over marketplace bricks)
|
|
2
|
+
|
|
3
|
+
**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
|
|
4
|
+
modify a brick template's source and never rebuild its logic from scratch.
|
|
5
|
+
The composition is a small project-private WRAPPER workflow that dispatches
|
|
6
|
+
already-DEPLOYED bricks as sub-workflows. A forked/edited brick falls off the
|
|
7
|
+
upgrade path.
|
|
8
|
+
|
|
9
|
+
**Reuse policy \u2014 ask, never silently choose.** If a needed brick is already
|
|
10
|
+
deployed in the project, the user decides: reuse that instance (runs + config
|
|
11
|
+
are shared with its standalone use) or deploy a dedicated instance under a
|
|
12
|
+
custom name (config isolation).
|
|
13
|
+
|
|
14
|
+
**Sub-workflow node.** Declare a child dispatch by giving addNode a config
|
|
15
|
+
with a \`workflow:\` field \u2014 the DEPLOYED slug in the SAME project (the row's
|
|
16
|
+
workflowType, not the marketplace slug, when they differ):
|
|
17
|
+
|
|
18
|
+
graph.addNode('review', {
|
|
19
|
+
workflow: 'gitlab-code-review', // deployed slug
|
|
20
|
+
input: (state) => ({ projectId: state.projectId, mrIid: state.mrIid }),
|
|
21
|
+
timeoutMs: 15 * 60 * 1000,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
The engine runs the child in-process (same worker) when possible and the
|
|
25
|
+
child's FINAL state \u2014 whichever End it exited \u2014 lands at \`state[nodeName]\`.
|
|
26
|
+
Options: \`workflow\` (required), \`input\` (object or \`(state) => object\`),
|
|
27
|
+
\`output\` (dot-path or \`(finalState) => any\` to extract just what's needed),
|
|
28
|
+
\`async: true\` (fire-and-forget \u2192 \`{ jobId }\`), \`timeoutMs\`, \`retries\`.
|
|
29
|
+
For PARALLEL fan-out call \`dispatchSubgraph(slug, { input })\` (exported by
|
|
30
|
+
@zibby/agent-workflow) inside one custom execute node with
|
|
31
|
+
\`Promise.allSettled\` \u2014 one brick failing must not kill its siblings.
|
|
32
|
+
|
|
33
|
+
**Chain conditions are EXPLICIT decision nodes.** Bricks are full multi-exit
|
|
34
|
+
graphs, so branch on the child's RETURNED state between dispatches \u2014 and model
|
|
35
|
+
the branch so the graph SHOWS it: a router node
|
|
36
|
+
(\`graph.addNode('<id>', { description })\` \u2014 no execute/prompt/outputSchema;
|
|
37
|
+
renders as the Condition diamond) routed with
|
|
38
|
+
\`graph.addConditionalEdges('<id>', routeFn, { labels })\`. Never an unlabeled
|
|
39
|
+
dispatch\u2192End edge. Note the child's own node outputs are NESTED
|
|
40
|
+
(\`state.review.review.posted\` = the child's \`review\` node output), e.g. only
|
|
41
|
+
meter when \`state.review?.review?.posted === true && state.review?.trigger
|
|
42
|
+
!== 'comment_reply'\`.
|
|
43
|
+
|
|
44
|
+
**Input mapping is the wrapper's job \u2014 use the brick's CANONICAL structured
|
|
45
|
+
fields.** In-process children run the brick's graph directly and SKIP any
|
|
46
|
+
convenience normalization its class run() does on cold starts (e.g.
|
|
47
|
+
gitlab-code-review parses mrUrl \u2192 projectId+mrIid only on cold runs \u2014 pass
|
|
48
|
+
projectId/mrIid yourself).
|
|
49
|
+
|
|
50
|
+
**Credentials/config: children use their OWN row's env** (engine \u22650.4.32 +
|
|
51
|
+
matching backend). A brick's per-workflow env (Env tab / envSecret) applies to
|
|
52
|
+
its in-process wrapped runs too \u2014 the child's value wins, the wrapper's env is
|
|
53
|
+
only the fallback for keys the brick doesn't define. So the wrapper needs ZERO
|
|
54
|
+
credential duplication: leave each brick's creds (e.g.
|
|
55
|
+
CLAUDE_CODE_OAUTH_TOKEN) on the brick itself and give the wrapper none.
|
|
56
|
+
(Env-carrying children serialize when dispatched in parallel; env-less ones
|
|
57
|
+
keep full parallelism. On older engines children inherit only the wrapper env
|
|
58
|
+
\u2014 symptom: authentication_failed inside the child.) A brick's saved per-node
|
|
59
|
+
custom prompts (nodeConfigOverrides.<node>.extraPromptInstructions) apply
|
|
60
|
+
in-process since \u22650.4.30, and its stores bindings ride along since \u22650.4.32.
|
|
61
|
+
|
|
62
|
+
**Triggers \u2014 INHERIT the entry brick's events, read not invent.** The
|
|
63
|
+
wrapper's trigger is AGENT-DRIVEN, never hardcoded: for webhook compositions
|
|
64
|
+
the wrapper's workflow.json \`triggers.events\` is a verbatim COPY of whatever
|
|
65
|
+
the ENTRY brick declares \u2014 read it from the brick's deployed row (or its
|
|
66
|
+
template workflow.json) and paste the exact array. The platform then
|
|
67
|
+
automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
|
|
68
|
+
listed in a deployed wrapper's composedOf stops receiving standalone webhook
|
|
69
|
+
events), so the same event never double-fires a brick inside AND outside the
|
|
70
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`,t=e;export{e as COMPOSE_KNOWLEDGE,t as default};
|
package/dist/graph-compiler.js
CHANGED
|
@@ -38,7 +38,7 @@ ${s}`);let i=r(),u=i.cwd||process.cwd(),d=i.sessionPath;try{if(d){let l=Te(d,K);
|
|
|
38
38
|
`):a.every(n=>typeof n=="object")?Object.assign({},...a):a[a.length-1]}static async loadFile(e){let t=Eo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),a=await import(r(e).href);return a.default||a}return t}};import{mkdirSync as bt,existsSync as Ne,writeFileSync as It,unlinkSync as bo}from"node:fs";import{join as Y,resolve as $t}from"node:path";import{config as $o}from"dotenv";import{zodToJsonSchema as Et}from"zod-to-json-schema";import{z as he}from"zod";import vo from"handlebars";function To({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:a}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",i=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${a?"yes":"no"} path=${t}`;if(console.log(i),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let h=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${h}`)}}function Ao(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function ko(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return $t(String(e).trim())}catch{return String(e).trim()}}function xo(){Ao()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Oo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function No(o={}){let e=et.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function Po({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=$t(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,n="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,n="config.sessionId"):(i=No(e),n="generated")}s=s??Date.now();let h=e.paths?.output||ue;a=Y(o,h,Xe,i)}let u=!Ne(a);return u&&bt(a,{recursive:!0}),(u||n!=="initialState.sessionPath")&&To({traceFrom:r,sessionId:i,sessionPath:a,idSource:n,mkdirFresh:u}),Oo({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:s}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},yt(n.workflow,{input:l,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,s){let n=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=n;n=()=>u(t,d,a,s)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Et(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(S.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(S.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!E){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of S){let y={source:g,target:f,data:{conditionalCode:m}};_[f]&&(y.label=_[f]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return Et(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of r)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),h=a(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&s.has(l.target)&&(n.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>s.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),h.push(a.get(l));for(let c of n.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!i.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},s=e.required||[];for(let[n,i]of Object.entries(a)){let u=t?`${t}.${n}`:n;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(n),optional:!s.includes(n)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,s]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${a}: ${s}`);else if(Array.isArray(s)){let n=s.length,i=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${n} passed${n-i?`, ${n-i} failed`:""}`:`${a}: ${n} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();$o({path:Y(n,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let $=Y(n,".zibby.config.js");Ne($)&&(i=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let $=i?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let P=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=ko(),c=t.sessionPath||l;c||xo();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=Po({cwd:n,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),p=i.skills&&typeof i.skills=="object"?i.skills:{},b=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),A=$=>{for(let P of b)if(P.id===$)return P;return y($)},R=new Set;for(let[,$]of this.nodes)for(let P of $.config?.skills||[])R.add(P);for(let $ of R){let P=A($);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,xt=0;try{for(;w&&w!=="END";){if(++xt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{bo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
|
|
41
|
+
${h}`)}}function Ao(){return process.env.ZIBBY_TRUST_SESSION_ENV==="1"||process.env.ZIBBY_TRUST_SESSION_ENV==="true"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function ko(){if(!(process.env.ZIBBY_PIN_SESSION_PATH==="1"||process.env.ZIBBY_PIN_SESSION_PATH==="true"))return;let e=process.env.ZIBBY_SESSION_PATH;if(!(e==null||String(e).trim()===""))try{return $t(String(e).trim())}catch{return String(e).trim()}}function xo(){Ao()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Oo({sessionPath:o,sessionId:e}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function No(o={}){let e=et.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,a=o.paths?.sessionPrefix;return a?`${a}_${r}`:r}function Po({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let a=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!a&&process.env.ZIBBY_SESSION_PATH)try{let d=$t(String(process.env.ZIBBY_SESSION_PATH));d&&(a=d,n="ZIBBY_SESSION_PATH")}catch{}let i;if(a)i=String(a).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)i=d,n="ZIBBY_SESSION_ID";else{let l=e.sessionId!=null?String(e.sessionId).trim():"";l&&l!=="last"?(i=l,n="config.sessionId"):(i=No(e),n="generated")}s=s??Date.now();let h=e.paths?.output||ue;a=Y(o,h,Xe,i)}let u=!Ne(a);return u&&bt(a,{recursive:!0}),(u||n!=="initialState.sessionPath")&&To({traceFrom:r,sessionId:i,sessionPath:a,idSource:n,mkdirFresh:u}),Oo({sessionPath:a,sessionId:i}),{sessionPath:a,sessionId:i,sessionTimestamp:s}}var ge=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,i={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async d=>{let h=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,l;return typeof n.input=="function"?l=n.input(h):n.input&&typeof n.input=="object"?l=n.input:l={},yt(n.workflow,{input:l,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(h):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:h?._signal,parentAgent:d?.agent})}},u=new L(i);return u.name=e,this.nodes.set(e,u),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let a=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(a?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,a,s){let n=r;for(let i=e.length-1;i>=0;i--){let u=e[i],d=n;n=()=>u(t,d,a,s)}return n()}serialize(){let e=[],t={};for(let[l,c]of this.nodes){let m=this.nodeTypeMap.get(l)||(c?.config?._isRouter===!0?"decision":l);e.push({id:l,type:m,data:{nodeType:m,label:l}});let S={};c._isCustomCode&&typeof c.execute=="function"&&(S.customCode=c.execute.toString());let _=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;_&&(S.description=_);let v=this.nodePrompts.get(l);if(v)S.prompt=v;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(S.prompt=p,S.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(S.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(S.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof he?.toJSONSchema=="function")try{p=he.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Et(c.outputSchema,{target:"openApi3"})}catch{}S.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else S.outputSchema={schema:c.outputSchema};let E=(this.resolvedToolsMap||{})[l];E?.toolIds&&(S.tools=E.toolIds);let g=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;g&&g.length>0&&(S.skills=[...g]);let f=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;f&&f.length>0&&(S.plugins=f.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(S.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(S).length>0&&(t[l]=S)}let r=[];for(let[l,c]of this.edges)if(typeof c=="string")r.push({source:l,target:c});else if(c.conditional){let m=this.conditionalCodeMap.get(l)||c.routes.toString(),S=this._inferConditionalTargets(c.routes,c.labels),_=c.labels||{},v=this.nodes.get(l),E=v?.config?._isRouter===!0||this.nodeTypeMap.get(l)==="decision"||!v,g=l;if(!E){let f=`${l}__branch`;e.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:l,target:f}),g=f}for(let f of S){let y={source:g,target:f,data:{conditionalCode:m}};_[f]&&(y.label=_[f]),r.push(y)}}let a=l=>{if(!l)return null;if(typeof he?.toJSONSchema=="function")try{return he.toJSONSchema(l)}catch{}try{return Et(l,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let s=0;for(let l of r)if(l.target==="END"){s+=1;let c=`END__${s}`;l.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let l of this.nodes.keys())if(!this.edges.has(l)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:l,target:c})}let n=this._topoOrderNodes(e,r),i=this._runtimeSchema(),u=a(i||this.stateSchema),d=a(this.inputSchema),h=a(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:u,inputSchema:d,contextSchema:h}}_topoOrderNodes(e,t){let r=new Map(e.map((l,c)=>[l.id,c])),a=new Map(e.map(l=>[l.id,l])),s=new Map(e.map(l=>[l.id,0])),n=new Map(e.map(l=>[l.id,[]]));for(let l of t)n.has(l.source)&&s.has(l.target)&&(n.get(l.source).push(l.target),s.set(l.target,s.get(l.target)+1));let i=new Set,u=new Set(r.keys()),d=[...u].filter(l=>s.get(l)===0),h=[];for(;h.length<e.length;){let l;if(d.length>0){if(d.sort((c,m)=>r.get(c)-r.get(m)),l=d.shift(),i.has(l))continue}else l=[...u].sort((c,m)=>r.get(c)-r.get(m))[0];i.add(l),u.delete(l),h.push(a.get(l));for(let c of n.get(l)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!i.has(c)&&d.push(c)}return h}_inferConditionalTargets(e,t){let r=e.toString(),a=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let d=n[2]!==void 0?n[2]:n[3];d!==void 0&&d!==""&&a.add(d)}let i=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())i.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))i.add(d);let u=new Set;for(let d of a)i.has(d)&&u.add(d);if(u.size===0){let d=/return\s+['"]([^'"]+)['"]/g,h;for(;(h=d.exec(r))!==null;)u.add(h[1])}return[...u]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let a=e.$ref.replace("#/definitions/","");r=e.definitions[a]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],a=e.properties||{},s=e.required||[];for(let[n,i]of Object.entries(a)){let u=t?`${t}.${n}`:n;r.push({path:u,type:i.type||"unknown",label:i.description||this._formatLabel(n),optional:!s.includes(n)}),i.type==="object"&&i.properties&&r.push(...this._flattenSchema(i,u)),i.type==="array"&&i.items?.type==="object"&&i.items.properties&&r.push(...this._flattenSchema(i.items,`${u}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[a,s]of Object.entries(t))if(!(a==="success"||a==="raw"||a==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${a}: ${s}`);else if(Array.isArray(s)){let n=s.length,i=s.filter(d=>d?.passed===!0).length,u=s.some(d=>d?.passed!==void 0);r.push(u?`${a}: ${i}/${n} passed${n-i?`, ${n-i} failed`:""}`:`${a}: ${n} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let a=new AbortController;r.signal&&(r.signal.aborted?a.abort():r.signal.addEventListener("abort",()=>a.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();$o({path:Y(n,".env")});let i=t.config||{};if(!i||Object.keys(i).length===0)try{let $=Y(n,".zibby.config.js");Ne($)&&(i=(await import($)).default||{})}catch{}process.env.EXECUTION_ID&&!i.agent?.strictMode&&(i.agent={...i.agent,strictMode:!0});let u=t.agentType;if(!u){let $=i?.agent;$?.provider?u=$.provider:$?.gemini?u="gemini":$?.claude?u="claude":$?.cursor?u="cursor":$?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||i?.context||{},h=this._runtimeSchema();if(h){let $=h.safeParse(t);if(!$.success){let P=$.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}O.step("State validated against schema")}let l=ko(),c=t.sessionPath||l;c||xo();let{sessionPath:m,sessionTimestamp:S,sessionId:_}=Po({cwd:n,config:i,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});O.step(`Session ${_}`);let v=await fe.loadContext(t.specPath||"",n,d);Object.keys(v).length>0&&O.step(`Context loaded: ${Object.keys(v).join(", ")}`);let E=t.outputPath;!E&&t.specPath&&(e?.calculateOutputPath?E=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let g=new ae({...t,config:i,agentType:u,outputPath:E,sessionPath:m,sessionTimestamp:S,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:a.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(de(),ot)),p=i.skills&&typeof i.skills=="object"?i.skills:{},b=Object.values(p).filter($=>$&&typeof $=="object"&&typeof $.id=="string"),A=$=>{for(let P of b)if(P.id===$)return P;return y($)},R=new Set;for(let[,$]of this.nodes)for(let P of $.config?.skills||[])R.add(P);for(let $ of R){let P=A($);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&f.set($,C)}catch{}}let w=this.entryPoint,re=[],Be=i?.recursionLimit??100,xt=0;try{for(;w&&w!=="END";){if(++xt>Be)throw new Error(`Workflow exceeded recursion limit (${Be}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=Y(m,Qe);if(Ne(P)){try{bo(P)}catch{}a.abort()}if(a.signal.aborted)return console.warn(`
|
|
42
42
|
\u{1F6D1} External stop requested \u2014 ending workflow.`),O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};let C=this.nodes.get(w);if(!C)throw new Error(`Node '${w}' not found in graph`);let Me=JSON.stringify({sessionPath:m,sessionTimestamp:S,currentNode:w,createdAt:new Date().toISOString(),config:g.get("config")}),Ot=Y(m,K);It(Ot,Me,"utf-8");let De=g.get("config")?.paths?.output||ue,Nt=Y(n,De,K);bt(Y(n,De),{recursive:!0});try{It(Nt,Me,"utf-8")}catch{}let je=t.onPipelineProgress;if(typeof je=="function")try{je({cwd:n,sessionPath:m,sessionId:_,outputBase:g.get("config")?.paths?.output||ue,currentNode:w})}catch{}let Pt=(this.resolvedToolsMap||{})[w]||null;g.set("_currentNodeTools",Pt);let Ct=g.get("nodeConfigs")||{};g.set("_currentNodeConfig",Ct[w]||{}),O.nodeStart(w);let Le=Date.now(),ne=this.nodePrompts.get(w);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(te(),ee));this._invokeAgent=k.invokeAgent}let Rt=this._invokeAgent,Se={},Bt=C.config?.skills||[];for(let k of Bt){let B=A(k);if(typeof B?.invokeAgentOptions=="function")try{let T=B.invokeAgentOptions(g.getAll(),{agentType:g.get("agentType"),nodeName:w});T&&typeof T=="object"&&(Se={...Se,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Ue=async(k,B,T={})=>{let M=Rt(k,B,{...Se,...T,signal:a.signal});return M.catch(()=>{}),a.signal.aborted?M:Promise.race([M,new Promise((Z,z)=>{let j=()=>{setTimeout(()=>{let V=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);V.name="AbortError",z(V)},s)};a.signal.addEventListener("abort",j,{once:!0})})])},Mt=async(k={},B={})=>{let T=B.prompt||"";if(ne){let M=this._compiledPrompts.get(w);M||(M=vo.compile(ne,{noEscape:!0}),this._compiledPrompts.set(w,M));try{T=M(k)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${w}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!T)throw new Error(`No prompt template configured for node '${w}' and no prompt provided in options`);return Ue(T,{state:g.getAll(),images:B.images||[]},{model:B.model||g.get("model"),workspace:g.get("workspace"),schema:B.schema,...B,signal:a.signal})},We=g.getAll(),Dt=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of Dt)Object.prototype.hasOwnProperty.call(We,k)&&console.warn(`[workflow] node "${w}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ge={...We,state:g,invokeAgent:Mt,_coreInvokeAgent:Ue,agent:e,nodeId:w,promptTemplate:ne,getPromptTemplate:()=>ne};try{let k=(C.config?.skills||[]).map(j=>f.get(j)).filter(Boolean),B=[...this.middleware,...k],T;B.length>0?T=await this._composeMiddleware(B,w,async()=>C.execute(Ge,g),g.getAll(),g):T=await C.execute(Ge,g);let M=Date.now()-Le;if(re.push({node:w,success:T.success,duration:M,timestamp:new Date().toISOString()}),!T.success){if(a.signal.aborted)return O.step("Workflow stopped externally"),{success:!0,state:g.getAll(),executionLog:re,stoppedExternally:!0};g.append("errors",{node:w,error:T.error});let j=C.config?.retries||0,V=`${w}_retries`,se=g.getAll()[V]||0;if(se<j){O.stepInfo(`Retrying (attempt ${se+1}/${j})`),g.update({[V]:se+1,[`${w}_raw`]:T.raw});continue}throw O.nodeFailed(w,T.error,{duration:M}),new Error(`Node '${w}' failed after ${se} attempts: ${T.error}`)}g.update({[w]:T.output});let Z=this._summarizeNodeOutput(w,T.output);O.nodeComplete(w,{duration:M,details:Z});let z=this.edges.get(w);if(!z)w="END";else if(z.conditional){let j=z.routes(g.getAll());O.route(w,j),w=j}else w=z}catch(k){throw O.isInsideNode&&O.nodeFailed(w,k.message,{duration:Date.now()-Le}),g.set("failed",!0),g.set("failedAt",w),k}}O.graphComplete();let $={success:!0,state:g.getAll(),executionLog:re};return e&&typeof e.onComplete=="function"&&await e.onComplete($),$}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch($){console.warn(`[workflow] agent.cleanup() failed: ${$.message}`)}}}};var Pe=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Pe]||(globalThis[Pe]=new Map);var Ce=globalThis[Pe];function Co(o,e){Ce.set(o,e)}function vt(o){return Ce.get(o)}function Re(o){return Ce.has(o)}Co("ai_agent",{name:"ai_agent",factory:!0,create:(o,e={})=>({name:o,_isCustomCode:!0,execute:async t=>{let r=t?._coreInvokeAgent;r||(r=(await Promise.resolve().then(()=>(te(),ee))).invokeAgent);let a=e.extraPromptInstructions||"Execute the task based on the current state.",s=Ro(a,t),n=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Ro(o,e){let t=/@([\w.]+)/g,r=new Set,a;for(;(a=t.exec(o))!==null;)r.add(a[1]);if(r.size===0)return o;let s=[],n=new Set;for(let i of r){let u=i.split(".")[0];if(n.has(u))continue;let d=i.split(".").reduce((c,m)=>c?.[m],e);if(d===void 0)continue;let h=typeof d=="string"?d:d?.raw??JSON.stringify(d,null,2),l=i.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${l}
|
|
43
43
|
${h}`),i.includes(".")||n.add(u)}return s.length===0?o:`${o}
|
|
44
44
|
|
package/dist/graph.js
CHANGED
|
@@ -38,5 +38,5 @@ ${i}`);let a=r(),u=a.cwd||process.cwd(),p=a.sessionPath;try{if(p){let c=Et(p,Z);
|
|
|
38
38
|
`):s.every(n=>typeof n=="object")?Object.assign({},...s):s[s.length-1]}static async loadFile(t){let e=pr(t,"utf-8");if(t.endsWith(".json"))return JSON.parse(e);if(t.endsWith(".js")||t.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),s=await import(r(t).href);return s.default||s}return e}};import{mkdirSync as Se,existsSync as vt,writeFileSync as he,unlinkSync as dr}from"node:fs";import{join as H,resolve as ye}from"node:path";import{config as fr}from"dotenv";import{zodToJsonSchema as ge}from"zod-to-json-schema";import{z as lt}from"zod";import hr from"handlebars";function gr({traceFrom:o,sessionId:t,sessionPath:e,idSource:r,mkdirFresh:s}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${t} source=${r} mkdir=${s?"yes":"no"} path=${e}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let g=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${g}`)}}function mr(){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 Sr(){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 ye(String(t).trim())}catch{return String(t).trim()}}function yr(){mr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function wr({sessionPath:o,sessionId:t}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function _r(o={}){let t=Zt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),r=t||`${Date.now()}_${e}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function Ir({cwd:o=process.cwd(),config:t={},initialState:e={},traceFrom:r="resolveWorkflowSession"}={}){let s=e.sessionPath,i=e.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=ye(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,n="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,n="config.sessionId"):(a=_r(t),n="generated")}i=i??Date.now();let g=t.paths?.output||it;s=H(o,g,Jt,a)}let u=!vt(s);return u&&Se(s,{recursive:!0}),(u||n!=="initialState.sessionPath")&&gr({traceFrom:r,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:u}),wr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var me=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,r={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,a={name:t,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async p=>{let g=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof n.input=="function"?c=n.input(g):n.input&&typeof n.input=="object"?c=n.input:c={},pe(n.workflow,{input:c,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(g):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:g?._signal,parentAgent:p?.agent})}},u=new L(a);return u.name=t,this.nodes.set(t,u),r.prompt&&this.nodePrompts.set(t,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),this}let s=!(e instanceof L)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof L?e:new L(s?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),r.prompt?this.nodePrompts.set(t,r.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),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:r}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:r}),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,r,s,i){let n=r;for(let a=t.length-1;a>=0;a--){let u=t[a],p=n;n=()=>u(e,p,s,i)}return n()}serialize(){let t=[],e={};for(let[c,l]of this.nodes){let y=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);t.push({id:c,type:y,data:{nodeType:y,label:c}});let w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let $=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;$&&(w.description=$);let v=this.nodePrompts.get(c);if(v)w.prompt=v;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(w.prompt=d,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof lt?.toJSONSchema=="function")try{d=lt.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=ge(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let b=(this.resolvedToolsMap||{})[c];b?.toolIds&&(w.tools=b.toolIds);let h=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;h&&h.length>0&&(w.skills=[...h]);let f=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;f&&f.length>0&&(w.plugins=f.map(d=>d&&typeof d=="object"?{...d}:d));let m=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;m&&m.length>0&&(w.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(w).length>0&&(e[c]=w)}let r=[];for(let[c,l]of this.edges)if(typeof l=="string")r.push({source:c,target:l});else if(l.conditional){let y=this.conditionalCodeMap.get(c)||l.routes.toString(),w=this._inferConditionalTargets(l.routes,l.labels),$=l.labels||{},v=this.nodes.get(c),b=v?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!v,h=c;if(!b){let f=`${c}__branch`;t.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:c,target:f}),h=f}for(let f of w){let m={source:h,target:f,data:{conditionalCode:y}};$[f]&&(m.label=$[f]),r.push(m)}}let s=c=>{if(!c)return null;if(typeof lt?.toJSONSchema=="function")try{return lt.toJSONSchema(c)}catch{}try{return ge(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of r)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:c,target:l})}let n=this._topoOrderNodes(t,r),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),g=s(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:g}}_topoOrderNodes(t,e){let r=new Map(t.map((c,l)=>[c.id,l])),s=new Map(t.map(c=>[c.id,c])),i=new Map(t.map(c=>[c.id,0])),n=new Map(t.map(c=>[c.id,[]]));for(let c of e)n.has(c.source)&&i.has(c.target)&&(n.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(r.keys()),p=[...u].filter(c=>i.get(c)===0),g=[];for(;g.length<t.length;){let c;if(p.length>0){if(p.sort((l,y)=>r.get(l)-r.get(y)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,y)=>r.get(l)-r.get(y))[0];a.add(c),u.delete(c),g.push(s.get(c));for(let l of n.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return g}_inferConditionalTargets(t,e){let r=t.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=i.exec(r))!==null;){let p=n[2]!==void 0?n[2]:n[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,g;for(;(g=p.exec(r))!==null;)u.add(g[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let r=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");r=t.definitions[s]||t}return this._flattenSchema(r,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let r=[],s=t.properties||{},i=t.required||[];for(let[n,a]of Object.entries(s)){let u=e?`${e}.${n}`:n;r.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!i.includes(n)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${u}[]`))}return r}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let r=[];e.success!==void 0&&r.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,i]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let n=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);r.push(u?`${s}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${s}: ${n} items`)}if(r.length>=4)break}return r}async run(t,e={},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 i=r.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();fr({path:H(n,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let E=H(n,".zibby.config.js");vt(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let E=a?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.codex?u="codex":u=process.env.AGENT_TYPE||"cursor"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},g=this._runtimeSchema();if(g){let E=g.safeParse(e);if(!E.success){let N=E.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(", ")}`)}x.step("State validated against schema")}let c=Sr(),l=e.sessionPath||c;l||yr();let{sessionPath:y,sessionTimestamp:w,sessionId:$}=Ir({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});x.step(`Session ${$}`);let v=await ct.loadContext(e.specPath||"",n,p);Object.keys(v).length>0&&x.step(`Context loaded: ${Object.keys(v).join(", ")}`);let b=e.outputPath;!b&&e.specPath&&(t?.calculateOutputPath?b=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let h=new ot({...e,config:a,agentType:u,outputPath:b,sessionPath:y,sessionTimestamp:w,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(St(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(d).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),A=E=>{for(let N of I)if(N.id===E)return N;return m(E)},B=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])B.add(N);for(let E of B){let N=A(E);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(E,R)}catch{}}let S=this.entryPoint,Q=[],kt=a?.recursionLimit??100,we=0;try{for(;S&&S!=="END";){if(++we>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(y,Yt);if(vt(N)){try{dr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
41
|
+
${g}`)}}function mr(){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 Sr(){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 ye(String(t).trim())}catch{return String(t).trim()}}function yr(){mr()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function wr({sessionPath:o,sessionId:t}){o&&typeof o=="string"&&(process.env.ZIBBY_SESSION_PATH=o),t!=null&&String(t).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(t).trim())}function _r(o={}){let t=Zt.map(i=>process.env[i]).find(Boolean),e=Math.random().toString(36).slice(2,6),r=t||`${Date.now()}_${e}`,s=o.paths?.sessionPrefix;return s?`${s}_${r}`:r}function Ir({cwd:o=process.cwd(),config:t={},initialState:e={},traceFrom:r="resolveWorkflowSession"}={}){let s=e.sessionPath,i=e.sessionTimestamp,n="initialState.sessionPath";if(!s&&process.env.ZIBBY_SESSION_PATH)try{let p=ye(String(process.env.ZIBBY_SESSION_PATH));p&&(s=p,n="ZIBBY_SESSION_PATH")}catch{}let a;if(s)a=String(s).split(/[/\\]/).filter(Boolean).pop(),i==null&&(i=Date.now());else{let p=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(p)a=p,n="ZIBBY_SESSION_ID";else{let c=t.sessionId!=null?String(t.sessionId).trim():"";c&&c!=="last"?(a=c,n="config.sessionId"):(a=_r(t),n="generated")}i=i??Date.now();let g=t.paths?.output||it;s=H(o,g,Jt,a)}let u=!vt(s);return u&&Se(s,{recursive:!0}),(u||n!=="initialState.sessionPath")&&gr({traceFrom:r,sessionId:a,sessionPath:s,idSource:n,mkdirFresh:u}),wr({sessionPath:s,sessionId:a}),{sessionPath:s,sessionId:a,sessionTimestamp:i}}var me=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,r={}){if(!(e instanceof L)&&e&&typeof e=="object"&&typeof e.workflow=="string"){let n=e,a={name:t,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async p=>{let g=p?.state&&typeof p.state.getAll=="function"?p.state.getAll():p,c;return typeof n.input=="function"?c=n.input(g):n.input&&typeof n.input=="object"?c=n.input:c={},pe(n.workflow,{input:c,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(g):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:g?._signal,parentAgent:p?.agent})}},u=new L(a);return u.name=t,this.nodes.set(t,u),r.prompt&&this.nodePrompts.set(t,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),this}let s=!(e instanceof L)&&e&&typeof e=="object"&&typeof e.execute!="function"&&e.prompt==null&&e.outputSchema==null&&e._isCustomCode!==!0,i=e instanceof L?e:new L(s?{...e,_isRouter:!0}:e);return i.name=t,this.nodes.set(t,i),r.prompt?this.nodePrompts.set(t,r.prompt):typeof e?.prompt=="string"&&e.prompt.trim()&&this.nodePrompts.set(t,e.prompt),Object.keys(r).length>0&&this.nodeOptions.set(t,r),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:r}={}){return this.edges.set(t,{conditional:!0,routes:e,labels:r}),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,r,s,i){let n=r;for(let a=t.length-1;a>=0;a--){let u=t[a],p=n;n=()=>u(e,p,s,i)}return n()}serialize(){let t=[],e={};for(let[c,l]of this.nodes){let y=this.nodeTypeMap.get(c)||(l?.config?._isRouter===!0?"decision":c);t.push({id:c,type:y,data:{nodeType:y,label:c}});let w={};l._isCustomCode&&typeof l.execute=="function"&&(w.customCode=l.execute.toString());let $=typeof l?.config?.description=="string"&&l.config.description.trim()?l.config.description:typeof l?.description=="string"&&l.description.trim()?l.description:null;$&&(w.description=$);let v=this.nodePrompts.get(c);if(v)w.prompt=v;else if(typeof l.prompt=="function")try{let d=l.prompt({});typeof d=="string"&&d.trim()&&(w.prompt=d,w.promptIsCode=!0)}catch{}if(typeof l.customExecute=="function"&&(w.executeCode=l.customExecute.toString()),typeof l?.config?.dispatchesWorkflow=="string"&&l.config.dispatchesWorkflow.trim()&&(w.dispatchesWorkflow=l.config.dispatchesWorkflow.trim()),l.outputSchema)if(typeof l.outputSchema._def<"u"){let d=null;if(typeof lt?.toJSONSchema=="function")try{d=lt.toJSONSchema(l.outputSchema)}catch{}if(!d)try{d=ge(l.outputSchema,{target:"openApi3"})}catch{}w.outputSchema=d?{jsonSchema:d,variables:this._flattenJsonSchemaToVariables(d)}:{schema:l.outputSchema}}else w.outputSchema={schema:l.outputSchema};let b=(this.resolvedToolsMap||{})[c];b?.toolIds&&(w.tools=b.toolIds);let h=Array.isArray(l?.config?.skills)?l.config.skills:Array.isArray(l?.skills)?l.skills:null;h&&h.length>0&&(w.skills=[...h]);let f=Array.isArray(l?.config?.plugins)?l.config.plugins:Array.isArray(l?.plugins)?l.plugins:null;f&&f.length>0&&(w.plugins=f.map(d=>d&&typeof d=="object"?{...d}:d));let m=Array.isArray(l?.config?.stores)?l.config.stores:Array.isArray(l?.stores)?l.stores:null;m&&m.length>0&&(w.stores=m.map(d=>d&&typeof d=="object"?{...d}:d)),Object.keys(w).length>0&&(e[c]=w)}let r=[];for(let[c,l]of this.edges)if(typeof l=="string")r.push({source:c,target:l});else if(l.conditional){let y=this.conditionalCodeMap.get(c)||l.routes.toString(),w=this._inferConditionalTargets(l.routes,l.labels),$=l.labels||{},v=this.nodes.get(c),b=v?.config?._isRouter===!0||this.nodeTypeMap.get(c)==="decision"||!v,h=c;if(!b){let f=`${c}__branch`;t.push({id:f,type:"decision",data:{nodeType:"decision",label:f}}),r.push({source:c,target:f}),h=f}for(let f of w){let m={source:h,target:f,data:{conditionalCode:y}};$[f]&&(m.label=$[f]),r.push(m)}}let s=c=>{if(!c)return null;if(typeof lt?.toJSONSchema=="function")try{return lt.toJSONSchema(c)}catch{}try{return ge(c,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(t.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let i=0;for(let c of r)if(c.target==="END"){i+=1;let l=`END__${i}`;c.target=l,t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}})}for(let c of this.nodes.keys())if(!this.edges.has(c)){i+=1;let l=`END__${i}`;t.push({id:l,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:c,target:l})}let n=this._topoOrderNodes(t,r),a=this._runtimeSchema(),u=s(a||this.stateSchema),p=s(this.inputSchema),g=s(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:e,stateSchema:u,inputSchema:p,contextSchema:g}}_topoOrderNodes(t,e){let r=new Map(t.map((c,l)=>[c.id,l])),s=new Map(t.map(c=>[c.id,c])),i=new Map(t.map(c=>[c.id,0])),n=new Map(t.map(c=>[c.id,[]]));for(let c of e)n.has(c.source)&&i.has(c.target)&&(n.get(c.source).push(c.target),i.set(c.target,i.get(c.target)+1));let a=new Set,u=new Set(r.keys()),p=[...u].filter(c=>i.get(c)===0),g=[];for(;g.length<t.length;){let c;if(p.length>0){if(p.sort((l,y)=>r.get(l)-r.get(y)),c=p.shift(),a.has(c))continue}else c=[...u].sort((l,y)=>r.get(l)-r.get(y))[0];a.add(c),u.delete(c),g.push(s.get(c));for(let l of n.get(c)||[])i.set(l,i.get(l)-1),i.get(l)<=0&&!a.has(l)&&p.push(l)}return g}_inferConditionalTargets(t,e){let r=t.toString(),s=new Set,i=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=i.exec(r))!==null;){let p=n[2]!==void 0?n[2]:n[3];p!==void 0&&p!==""&&s.add(p)}let a=new Set(["END","START","__end__","__start__"]);for(let p of this.nodes.keys())a.add(p);if(e&&typeof e=="object")for(let p of Object.keys(e))a.add(p);let u=new Set;for(let p of s)a.has(p)&&u.add(p);if(u.size===0){let p=/return\s+['"]([^'"]+)['"]/g,g;for(;(g=p.exec(r))!==null;)u.add(g[1])}return[...u]}_flattenJsonSchemaToVariables(t,e=""){let r=t;if(t.$ref&&t.definitions){let s=t.$ref.replace("#/definitions/","");r=t.definitions[s]||t}return this._flattenSchema(r,e)}_flattenSchema(t,e=""){if(!t||typeof t!="object")return[];let r=[],s=t.properties||{},i=t.required||[];for(let[n,a]of Object.entries(s)){let u=e?`${e}.${n}`:n;r.push({path:u,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!i.includes(n)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,u)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${u}[]`))}return r}_formatLabel(t){return t.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}_summarizeNodeOutput(t,e){if(!e||typeof e!="object")return[];let r=[];e.success!==void 0&&r.push(`Result: ${e.success?"passed":"failed"}`);for(let[s,i]of Object.entries(e))if(!(s==="success"||s==="raw"||s==="nextNode")){if(typeof i=="string"&&i.length<=80)r.push(`${s}: ${i}`);else if(Array.isArray(i)){let n=i.length,a=i.filter(p=>p?.passed===!0).length,u=i.some(p=>p?.passed!==void 0);r.push(u?`${s}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${s}: ${n} items`)}if(r.length>=4)break}return r}async run(t,e={},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 i=r.strategyAbortTimeoutMs??e.config?.strategyAbortTimeoutMs??5e3,n=e.cwd||process.cwd();fr({path:H(n,".env")});let a=e.config||{};if(!a||Object.keys(a).length===0)try{let E=H(n,".zibby.config.js");vt(E)&&(a=(await import(E)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let u=e.agentType;if(!u){let E=a?.agent;E?.provider?u=E.provider:E?.gemini?u="gemini":E?.claude?u="claude":E?.cursor?u="cursor":E?.codex?u="codex":u=process.env.AGENT_TYPE||"claude"}let p=e.contextConfig||t?.config?.contextConfig||t?.config?.context||a?.context||{},g=this._runtimeSchema();if(g){let E=g.safeParse(e);if(!E.success){let N=E.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(", ")}`)}x.step("State validated against schema")}let c=Sr(),l=e.sessionPath||c;l||yr();let{sessionPath:y,sessionTimestamp:w,sessionId:$}=Ir({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:e.sessionTimestamp}});x.step(`Session ${$}`);let v=await ct.loadContext(e.specPath||"",n,p);Object.keys(v).length>0&&x.step(`Context loaded: ${Object.keys(v).join(", ")}`);let b=e.outputPath;!b&&e.specPath&&(t?.calculateOutputPath?b=t.calculateOutputPath(e.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${e.specPath})`));let h=new ot({...e,config:a,agentType:u,outputPath:b,sessionPath:y,sessionTimestamp:w,context:v,resolvedTools:this.resolvedToolsMap||{},_signal:s.signal}),f=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:m}=await Promise.resolve().then(()=>(St(),Kt)),d=a.skills&&typeof a.skills=="object"?a.skills:{},I=Object.values(d).filter(E=>E&&typeof E=="object"&&typeof E.id=="string"),A=E=>{for(let N of I)if(N.id===E)return N;return m(E)},B=new Set;for(let[,E]of this.nodes)for(let N of E.config?.skills||[])B.add(N);for(let E of B){let N=A(E);if(typeof N?.middleware=="function")try{let R=await N.middleware();typeof R=="function"&&f.set(E,R)}catch{}}let S=this.entryPoint,Q=[],kt=a?.recursionLimit??100,we=0;try{for(;S&&S!=="END";){if(++we>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(y,Yt);if(vt(N)){try{dr(N)}catch{}s.abort()}if(s.signal.aborted)return console.warn(`
|
|
42
42
|
\u{1F6D1} External stop requested \u2014 ending workflow.`),x.step("Workflow stopped externally"),{success:!0,state:h.getAll(),executionLog:Q,stoppedExternally:!0};let R=this.nodes.get(S);if(!R)throw new Error(`Node '${S}' not found in graph`);let Ot=JSON.stringify({sessionPath:y,sessionTimestamp:w,currentNode:S,createdAt:new Date().toISOString(),config:h.get("config")}),_e=H(y,Z);he(_e,Ot,"utf-8");let xt=h.get("config")?.paths?.output||it,Ie=H(n,xt,Z);Se(H(n,xt),{recursive:!0});try{he(Ie,Ot,"utf-8")}catch{}let Pt=e.onPipelineProgress;if(typeof Pt=="function")try{Pt({cwd:n,sessionPath:y,sessionId:$,outputBase:h.get("config")?.paths?.output||it,currentNode:S})}catch{}let Ee=(this.resolvedToolsMap||{})[S]||null;h.set("_currentNodeTools",Ee);let be=h.get("nodeConfigs")||{};h.set("_currentNodeConfig",be[S]||{}),x.nodeStart(S);let Nt=Date.now(),tt=this.nodePrompts.get(S);if(!this._invokeAgent){let k=await Promise.resolve().then(()=>(_t(),wt));this._invokeAgent=k.invokeAgent}let $e=this._invokeAgent,ut={},Te=R.config?.skills||[];for(let k of Te){let C=A(k);if(typeof C?.invokeAgentOptions=="function")try{let T=C.invokeAgentOptions(h.getAll(),{agentType:h.get("agentType"),nodeName:S});T&&typeof T=="object"&&(ut={...ut,...T})}catch(T){console.warn(`[graph] skill '${k}' invokeAgentOptions threw: ${T.message}`)}}let Rt=async(k,C,T={})=>{let M=$e(k,C,{...ut,...T,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 ${i}ms`);K.name="AbortError",Y(K)},i)};s.signal.addEventListener("abort",D,{once:!0})})])},Ae=async(k={},C={})=>{let T=C.prompt||"";if(tt){let M=this._compiledPrompts.get(S);M||(M=hr.compile(tt,{noEscape:!0}),this._compiledPrompts.set(S,M));try{T=M(k)}catch(J){throw console.error(`\u274C Template rendering failed for node '${S}':`,J.message),new Error(`Template rendering failed: ${J.message}`,{cause:J})}}else if(!T)throw new Error(`No prompt template configured for node '${S}' and no prompt provided in options`);return Rt(T,{state:h.getAll(),images:C.images||[]},{model:C.model||h.get("model"),workspace:h.get("workspace"),schema:C.schema,...C,signal:s.signal})},Bt=h.getAll(),ve=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let k of ve)Object.prototype.hasOwnProperty.call(Bt,k)&&console.warn(`[workflow] node "${S}": state key "${k}" is shadowed by the engine context prop; read it via context.state.get('${k}')`);let Ct={...Bt,state:h,invokeAgent:Ae,_coreInvokeAgent:Rt,agent:t,nodeId:S,promptTemplate:tt,getPromptTemplate:()=>tt};try{let k=(R.config?.skills||[]).map(D=>f.get(D)).filter(Boolean),C=[...this.middleware,...k],T;C.length>0?T=await this._composeMiddleware(C,S,async()=>R.execute(Ct,h),h.getAll(),h):T=await R.execute(Ct,h);let M=Date.now()-Nt;if(Q.push({node:S,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:Q,stoppedExternally:!0};h.append("errors",{node:S,error:T.error});let D=R.config?.retries||0,K=`${S}_retries`,et=h.getAll()[K]||0;if(et<D){x.stepInfo(`Retrying (attempt ${et+1}/${D})`),h.update({[K]:et+1,[`${S}_raw`]:T.raw});continue}throw x.nodeFailed(S,T.error,{duration:M}),new Error(`Node '${S}' failed after ${et} attempts: ${T.error}`)}h.update({[S]:T.output});let J=this._summarizeNodeOutput(S,T.output);x.nodeComplete(S,{duration:M,details:J});let Y=this.edges.get(S);if(!Y)S="END";else if(Y.conditional){let D=Y.routes(h.getAll());x.route(S,D),S=D}else S=Y}catch(k){throw x.isInsideNode&&x.nodeFailed(S,k.message,{duration:Date.now()-Nt}),h.set("failed",!0),h.set("failedAt",S),k}}x.graphComplete();let E={success:!0,state:h.getAll(),executionLog:Q};return t&&typeof t.onComplete=="function"&&await t.onComplete(E),E}finally{if(t&&typeof t.cleanup=="function")try{await t.cleanup()}catch(E){console.warn(`[workflow] agent.cleanup() failed: ${E.message}`)}}}};export{me as WorkflowGraph,yr as clearInheritedSessionEnvForFreshRun,_r as generateWorkflowSessionId,Sr as readPinnedSessionPathFromEnv,Ir as resolveWorkflowSession,mr as shouldTrustInheritedSessionEnv,wr as syncProcessEnvToSession};
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { WorkflowState } from "./state.js";
|
|
|
4
4
|
export { ContextLoader } from "./context-loader.js";
|
|
5
5
|
export { AgentStrategy } from "./agents/base.js";
|
|
6
6
|
export { setLogger } from "./logger.js";
|
|
7
|
+
export { COMPOSE_KNOWLEDGE } from "./compose-knowledge.js";
|
|
7
8
|
export { WorkflowGraph, WorkflowGraph as Graph, generateWorkflowSessionId, resolveWorkflowSession, shouldTrustInheritedSessionEnv, readPinnedSessionPathFromEnv, clearInheritedSessionEnvForFreshRun, syncProcessEnvToSession } from "./graph.js";
|
|
8
9
|
export { OutputParser, SchemaTypes } from "./output-parser.js";
|
|
9
10
|
export { compileGraph, validateGraphConfig, extractSteps, CompilationError } from "./graph-compiler.js";
|
package/dist/index.js
CHANGED
|
@@ -1,59 +1,128 @@
|
|
|
1
|
-
var ao=Object.defineProperty;var
|
|
1
|
+
var ao=Object.defineProperty;var Ie=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var he=(o,e)=>()=>(o&&(e=o(o=0)),e);var ot=(o,e)=>{for(var t in e)ao(o,t,{get:e[t],enumerable:!0})};function uo(o){re.impl={...nt,...o}}var rt,nt,re,I,F=he(()=>{rt=()=>{},nt={debug:rt,info:rt,warn:(...o)=>console.warn("[workflow]",...o),error:(...o)=>console.error("[workflow]",...o)},re={impl:nt};I={debug:(...o)=>re.impl.debug?.(...o),info:(...o)=>re.impl.info?.(...o),warn:(...o)=>re.impl.warn?.(...o),error:(...o)=>re.impl.error?.(...o)}});var Ne,xe=he(()=>{Ne=class{constructor(e,t,r=0){this.name=e,this.description=t,this.priority=r}async invoke(e,t={}){throw new Error(`${this.constructor.name}.invoke() must be implemented`)}canHandle(e){throw new Error(`${this.constructor.name}.canHandle() must be implemented`)}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}});var St={};ot(St,{clearSkills:()=>wt,getAllSkills:()=>mt,getSkill:()=>q,hasSkill:()=>gt,listSkillIds:()=>yt,registerSkill:()=>ht});function ht(o){if(!o||typeof o.id!="string")throw new Error("Skill definition must include a string id");V.set(o.id,Object.freeze({...o}))}function q(o){return V.get(o)||null}function gt(o){return V.has(o)}function mt(){return new Map(V)}function yt(){return Array.from(V.keys())}function wt(){V.clear()}var Oe,V,ie=he(()=>{Oe=Symbol.for("@zibby/agent-workflow.skills");globalThis[Oe]||(globalThis[Oe]=new Map);V=globalThis[Oe]});var ae={};ot(ae,{getAgentStrategy:()=>Ce,invokeAgent:()=>It,listStrategies:()=>Et,registerStrategy:()=>_t});function _t(o){if(!o||typeof o.getName!="function"||typeof o.invoke!="function")throw new Error("strategy must implement getName() and invoke() (AgentStrategy shape)");let e=W.findIndex(t=>t.getName()===o.getName());e>=0?W[e]=o:W.push(o)}function Et(){return W.map(o=>o.getName())}function Ce(o={}){let{state:e={},preferredAgent:t=null}=o,r=t||e.agentType||process.env.AGENT_TYPE;if(!r){let s=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`No agent specified. Set agentType in state or AGENT_TYPE env var. Available: ${s}`)}I.debug(`[workflow] agent selection: requested=${r}`);let i=W.find(s=>s.getName()===r);if(!i){let s=W.map(n=>n.getName()).join(", ")||"none registered";throw new Error(`Unknown agent '${r}'. Available: ${s}`)}if(!i.canHandle(o))throw new Error(`Agent '${r}' is not available in this environment. Check credentials/environment.`);return I.debug(`[workflow] using agent: ${i.getName()}`),i}async function It(o,e={},t={}){let r=e.state&&typeof e.state.getAll=="function"?e.state.getAll():e.state||{},i={...e,state:r},s=Ce(i),n=r.config||t.config||{},a=n.models||{},l=t.nodeName&&a[t.nodeName]||null,u=a.default||null,f=n.agent?.[s.name]?.model||null,d=l||u||f||t.model||null,c={...t,model:d,workspace:r.workspace||t.workspace,schema:t.schema||e.schema,images:t.images||e.images||[],skills:t.skills||e.skills||[],plugins:t.plugins||e.plugins||[],config:n},y=o,g=c.skills||[];if(g.length>0&&!t.skipPromptFragments){let _=g.map(m=>{let h=q(m)?.promptFragment;return typeof h=="function"?h():h}).filter(Boolean);_.length>0&&(y+=`
|
|
2
2
|
|
|
3
3
|
${_.join(`
|
|
4
4
|
|
|
5
|
-
`)}`)}let
|
|
6
|
-
fields: ${
|
|
5
|
+
`)}`)}let S=r._currentNodeConfig?.stores;if(Array.isArray(S)&&S.length>0&&typeof S[0]=="object"){let _=S.length<=8,m=S.map(h=>{let w=h?.id??h?.storeId??"",p=(h?.name??"").toString().trim()||w,T=h?.type?` \xB7 ${h.type}`:"",k=(h?.description||"").toString().replace(/\s+/g," ").trim(),R=`- ${p} \xB7 ${k||"(no description)"}${T} (id: ${w})`;if(_&&h?.schema&&typeof h.schema=="object"){let E=h.schema.properties&&typeof h.schema.properties=="object"?Object.keys(h.schema.properties):Object.keys(h.schema);E.length&&(R+=`
|
|
6
|
+
fields: ${E.join(", ")}`)}return R});y+=`
|
|
7
7
|
|
|
8
8
|
AVAILABLE STORES (pick a store by its description and pass its NAME to the store tool):
|
|
9
9
|
${m.join(`
|
|
10
|
-
`)}`}let b=
|
|
10
|
+
`)}`}let b=r._currentNodeConfig?.extraPromptInstructions?.trim();return b&&(y+=`
|
|
11
11
|
|
|
12
12
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
13
13
|
PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
|
|
14
14
|
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
|
|
15
15
|
|
|
16
16
|
${b}
|
|
17
|
-
`),
|
|
17
|
+
`),I.debug(`[workflow] prompt length: ${y.length} chars`),s.invoke(y,c)}var Pe,W,X=he(()=>{xe();F();ie();Pe=Symbol.for("@zibby/agent-workflow.strategies");globalThis[Pe]||(globalThis[Pe]=[]);W=globalThis[Pe]});var co=new Set(["__proto__","constructor","prototype"]);function be(o){if(co.has(o))throw new Error(`Invalid state key: "${o}"`)}var te=class{constructor(e={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...e}),this._history=[]}get(e){return this._state[e]}set(e,t){be(e),this._history.push({...this._state}),this._state[e]=t}update(e){let t=Object.getOwnPropertyNames(e);for(let r of t)be(r);this._history.push({...this._state});for(let r of t)this._state[r]=e[r]}append(e,t){be(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 H from"handlebars";var oe=class{constructor(e){this.schema=e}parse(e){let t=e.match(/```json\s*([\s\S]*?)\s*```/);if(t)return this.validate(JSON.parse(t[1]));let r=[e.match(/\{[\s\S]*?\}/),e.match(/\{[\s\S]*\}/)].filter(Boolean).map(i=>i[0]);for(let i of r)try{return this.validate(JSON.parse(i))}catch(s){if(!(s instanceof SyntaxError))throw s}return this.validate({result:e.trim()})}validate(e){let t=[];for(let[r,i]of Object.entries(this.schema)){if(i.required&&!(r in e)&&t.push(`Missing required field: ${r}`),r in e&&i.type){let s=typeof e[r];s!==i.type&&t.push(`Field '${r}' expected ${i.type}, got ${s}`)}if(i.validate&&r in e){let s=i.validate(e[r]);s&&t.push(`Field '${r}': ${s}`)}}if(t.length>0)throw new Error(`Output validation failed:
|
|
18
18
|
${t.join(`
|
|
19
|
-
`)}`);return e}},lo={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};F();import{writeFileSync as Re,readFileSync as bt,existsSync as
|
|
20
|
-
`?(
|
|
21
|
-
${ct}`,e.col=lt))}return o(r,
|
|
19
|
+
`)}`);return e}},lo={string:(o=!0)=>({type:"string",required:o}),number:(o=!0)=>({type:"number",required:o}),boolean:(o=!0)=>({type:"boolean",required:o}),array:(o=!0)=>({type:"object",required:o,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(o,e=!0)=>({type:"string",required:e,validate:t=>o.includes(t)?null:`must be one of: ${o.join(", ")}`})};F();import{writeFileSync as Re,readFileSync as bt,existsSync as Tt,mkdirSync as yo}from"node:fs";import{join as Be,dirname as wo}from"node:path";import x from"chalk";var pt="__WORKFLOW_GRAPH_LOG__",ne=x.gray("\u2502"),po=x.gray("\u250C"),st=x.gray("\u2514"),Te=x.green("\u25C6"),it=x.hex("#c084fc")("\u25C6"),at=x.hex("#2dd4bf")("\u25C6"),ve=x.red("\u25C6"),ct=`${ne} `,lt=2;function dt(o){return o<1e3?`${o}ms`:`${(o/1e3).toFixed(1)}s`}function ut(o,e){return(t,r,i)=>{if(typeof t!="string")return o(t,r,i);let s=process.stdout.columns||120,n="";for(let a=0;a<t.length;a++){let l=t[a];e.lineStart&&(n+=ct,e.col=lt,e.lineStart=!1),l===`
|
|
20
|
+
`?(n+=l,e.lineStart=!0,e.col=0,e.inEsc=!1):l==="\x1B"?(e.inEsc=!0,n+=l):e.inEsc?(n+=l,(l>="A"&&l<="Z"||l>="a"&&l<="z")&&(e.inEsc=!1)):(e.col++,n+=l,e.col>=s&&(n+=`
|
|
21
|
+
${ct}`,e.col=lt))}return o(n,r,i)}}var ge=class{constructor(){this._currentNode=null,this._origStdoutWrite=null,this._origStderrWrite=null,this._emitWorkflowGraphMarkers=String(process.env.ZIBBY_EMIT_GRAPH_MARKERS||"").trim()==="1"||String(process.env.ZIBBY_WORKFLOW_GRAPH_LOG_MARKERS||"").trim()==="1"}get isInsideNode(){return this._currentNode!==null}_startIntercepting(){this._origStdoutWrite=process.stdout.write.bind(process.stdout),this._origStderrWrite=process.stderr.write.bind(process.stderr);let e={lineStart:!0,col:0,inEsc:!1},t={lineStart:!0,col:0,inEsc:!1};this._outState=e,this._errState=t,process.stdout.write=ut(this._origStdoutWrite,e),process.stderr.write=ut(this._origStderrWrite,t)}_stopIntercepting(){this._origStdoutWrite&&(this._outState&&!this._outState.lineStart&&this._origStdoutWrite(`
|
|
22
22
|
`),process.stdout.write=this._origStdoutWrite),this._origStderrWrite&&(this._errState&&!this._errState.lineStart&&this._origStderrWrite(`
|
|
23
23
|
`),process.stderr.write=this._origStderrWrite),this._origStdoutWrite=null,this._origStderrWrite=null}_rawWrite(e){(this._origStdoutWrite||process.stdout.write.bind(process.stdout))(`${e}
|
|
24
24
|
`)}_emitGraphLogMarker(e){if(!this._emitWorkflowGraphMarkers)return;let t=`${pt}${JSON.stringify(e)}
|
|
25
25
|
`;this._origStdoutWrite?this._origStdoutWrite(t):process.stdout.write(t)}_writeDot(e,t){this._origStdoutWrite?(this._outState&&!this._outState.lineStart&&(this._origStdoutWrite(`
|
|
26
26
|
`),this._outState.lineStart=!0,this._outState.col=0),this._origStdoutWrite(`${e} ${t}
|
|
27
27
|
`)):process.stdout.write.bind(process.stdout)(`${e} ${t}
|
|
28
|
-
`)}step(e){this._origStdoutWrite?this._writeDot(
|
|
29
|
-
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(it,e):process.stdout.write.bind(process.stdout)(`${
|
|
30
|
-
`)}stepMemory(e){let t=
|
|
31
|
-
`)}stepFail(e){this._origStdoutWrite?this._writeDot(
|
|
32
|
-
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${po} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:
|
|
28
|
+
`)}step(e){this._origStdoutWrite?this._writeDot(Te,e):process.stdout.write.bind(process.stdout)(`${ne} ${Te} ${e}
|
|
29
|
+
`)}stepInfo(e){this.step(e)}stepTool(e){this._origStdoutWrite?this._writeDot(it,e):process.stdout.write.bind(process.stdout)(`${ne} ${it} ${e}
|
|
30
|
+
`)}stepMemory(e){let t=x.hex("#2dd4bf")(e);this._origStdoutWrite?this._writeDot(at,t):process.stdout.write.bind(process.stdout)(`${ne} ${at} ${t}
|
|
31
|
+
`)}stepFail(e){this._origStdoutWrite?this._writeDot(ve,x.red(e)):process.stdout.write.bind(process.stdout)(`${ne} ${ve} ${x.red(e)}
|
|
32
|
+
`)}nodeStart(e){this._currentNode=e,this._emitGraphLogMarker({phase:"node_begin",node:e}),this._rawWrite(`${po} ${e}`),this._startIntercepting()}nodeComplete(e,t={}){this._stopIntercepting();let{duration:r,details:i}=t;if(i)for(let n of i)this._rawWrite(`${Te} ${n}`);let s=r?x.dim(` ${dt(r)}`):"";this._rawWrite(`${st} ${x.green("done")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}nodeFailed(e,t,r={}){this._stopIntercepting();let{duration:i}=r,s=i?x.dim(` ${dt(i)}`):"";this._rawWrite(`${ve} ${x.red(t)}`),this._rawWrite(`${st} ${x.red("failed")}${s}`),this._emitGraphLogMarker({phase:"node_end",node:e}),this._rawWrite("")}route(e,t){this._rawWrite(x.dim(` ${e} \u2192 ${t}`)),this._rawWrite("")}graphComplete(){}},N=new ge;var se=".zibby/output",$e="sessions",U=".session-info.json",ke=".zibby-stop",fo="result.json",ho="raw_stream_output.txt",go="events.json",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"},mo=Object.freeze([ft.CODEBASE_MEMORY]),Ae=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];H.helpers.inc||H.registerHelper("inc",o=>Number(o)+1);H.helpers.json||H.registerHelper("json",o=>JSON.stringify(o,null,2));H.helpers.eq||H.registerHelper("eq",(o,e)=>o===e);var M=class{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode&&!e._isRouter)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new oe(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,t){if(this.config._isRouter)return I.debug(`[workflow] node '${this.name}': router passthrough (routing happens on its conditional edges)`),{success:!0,output:{},raw:null};let r=()=>t&&typeof t.getAll=="function"?t.getAll():e,i=d=>t&&typeof t.get=="function"?t.get(d):e?.[d];if(typeof this.customExecute=="function"){I.debug(`[workflow] node '${this.name}': custom execute (skipping LLM)`);try{let d=await this.customExecute(e);return typeof d=="object"&&d!==null&&d.success===!1?{success:!1,error:d.error||"Node execution failed",raw:d.raw||null}:this.isZodSchema?(I.debug(`[workflow] node '${this.name}': validating output schema`),{success:!0,output:this.outputSchema.parse(d),raw:null}):{success:!0,output:d,raw:null}}catch(d){return I.error(`[workflow] node '${this.name}' failed: ${d.message}`),d.name==="ZodError"&&I.error(`Schema errors: ${JSON.stringify(d.issues||d.errors,null,2)}`),{success:!1,error:d.message,raw:null}}}let s;typeof this.prompt=="function"?s=this.prompt(r()):typeof this.prompt=="string"&&this.prompt.includes("{{")?(this._compiledPrompt||(this._compiledPrompt=H.compile(this.prompt,{noEscape:!0})),s=this._compiledPrompt(r())):s=this.prompt;let n=i("_skillHints");n&&(s=`${n}
|
|
33
33
|
|
|
34
|
-
${s}`);let a=n(),l=a.cwd||process.cwd(),d=a.sessionPath;try{if(d){let u=Be(d,U);if($t(u)){let S=JSON.parse(bt(u,"utf-8"));S.currentNode=this.name,Re(u,JSON.stringify(S,null,2),"utf-8")}let c=Be(d,"..",U);if($t(c))try{let S=JSON.parse(bt(c,"utf-8"));S.currentNode=this.name,Re(c,JSON.stringify(S,null,2),"utf-8")}catch{}}}catch(u){E.debug(`[workflow] could not update session info: ${u.message}`)}let f=null;for(let u=0;u<=this.retries;u++)try{E.debug(`[workflow] node '${this.name}' attempt ${u}`);let c=n().config||{},S=c.agents||{},g=this.config.agent??S[this.name]??null,w={state:n()};g&&(w.preferredAgent=g);let b={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:d,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let m=await _(s,w,b),h,y;if(typeof m=="string"?(h=m,y=null):m.structured?(h=m.raw||JSON.stringify(m.structured,null,2),y=m.structured):(h=m.raw||JSON.stringify(m,null,2),y=m.extracted||null),d)try{let p=Be(d,this.name,"raw_stream_output.txt");So(yo(p),{recursive:!0}),Re(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){E.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&y){E.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(y,null,2)}`);let p=y;if(typeof this.onComplete=="function")try{p=await this.onComplete(n(),y)}catch($){E.warn(`[workflow] onComplete hook failed: ${$.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(n(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return E.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),x.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(c){f=c,u<this.retries&&E.info(`[workflow] node '${this.name}' failed, retrying (${u+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as Io,existsSync as Y,statSync as Ct,readdirSync as Rt,rmSync as Eo}from"node:fs";import{spawn as Nt}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as bo}from"node:url";import{AsyncLocalStorage as $o}from"node:async_hooks";import{AsyncLocalStorage as wo}from"node:async_hooks";var Me=new wo;function ce(){let o=Me.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 Tt(o,e){let t=Me.getStore()||ce(),n=Object.freeze({executionId:o.executionId,parentExecutionId:o.parentExecutionId??t.executionId??null,depth:(t.depth||0)+(o.executionId!==t.executionId?1:0),conversationId:o.conversationId!==void 0?o.conversationId:t.conversationId??null,dispatchMode:o.dispatchMode??null});return Me.run(n,e)}var je=new Map,De=new Map,vt=new Map;function At(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");je.set(o,e),De.set(o,"ready"),vt.set(o,{...t,cachedAt:Date.now()})}function kt(o,e){De.set(o,"failed"),vt.set(o,{error:e?.message||String(e),failedAt:Date.now()}),je.delete(o)}function xt(o){return De.get(o)==="ready"?je.get(o):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function To(){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"}},Ot=new $o,Pt=Promise.resolve();async function vo(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([r,a])=>typeof r=="string"&&r&&typeof a=="string"):[];if(t.length===0)return e();let n=Ot.getStore()===!0,i=null;if(!n){let r=Pt;Pt=new Promise(a=>{i=a}),await r}let s=new Map;try{for(let[r,a]of t)s.set(r,Object.prototype.hasOwnProperty.call(process.env,r)?process.env[r]:void 0),process.env[r]=a;return E.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${n?" (nested)":""}`),await Ot.run(!0,e)}finally{for(let[r,a]of s)a===void 0?delete process.env[r]:process.env[r]=a;i&&i()}}function Ao(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,n=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!n||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:n,authToken:i}}async function ko({apiBase:o,authToken:e,body:t}){let n;try{n=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await n.json()}catch{}if(!n.ok){if(n.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(n.status===429){let s=i?.quotaInfo||{},r=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw r.code="SUBGRAPH_QUOTA_EXCEEDED",r.status=429,r.quotaInfo=s,r}if(n.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${n.status}`)}return i?.data||i}async function J({apiBase:o,authToken:e,payload:t}){try{let n=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});n.ok||E.warn(`[in-process subgraph] finalize returned ${n.status} for ${t.childExecutionId}`)}catch(n){E.warn(`[in-process subgraph] finalize failed: ${n.message}`)}}async function xo(o,e){let t=G(e,".ready"),n=G(e,"graph.mjs");if(Y(t)&&Y(n))return;Io(e,{recursive:!0});let i=G(e,".lock"),s=!1;try{let{openSync:r,closeSync:a}=await import("node:fs"),l=r(i,"wx");a(l),s=!0}catch(r){if(r.code!=="EEXIST")throw r}if(!s){let r=Date.now()+3e4;for(;Date.now()<r;){if(Y(t)&&Y(n))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,d)=>{let f=Nt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),u=Nt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(u.stdin);let c,S,g=()=>{if(c!==void 0&&S!==void 0){if(c!==0)return d(new Error(`curl exited ${c}`));if(S!==0)return d(new Error(`tar exited ${S}`));l()}};f.on("close",w=>{c=w,g()}),u.on("close",w=>{S=w,g()}),f.on("error",d),u.on("error",d)});let{writeFileSync:r,unlinkSync:a}=await import("node:fs");r(t,"");try{a(i)}catch{}}catch(r){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",r.message)}}async function No(o){let e=G(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(bo(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let n=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!n)throw new O("entry-class-missing","no buildGraph() class export found");return n}async function Bt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ce(),n;try{n=Ao()}catch(p){throw p}E.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await ko({apiBase:n.apiBase,authToken:n.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:r,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:d,workflowUuid:f,bundleReady:u,nodeConfigs:c}=i,S=To();if(r&&r!==S)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${S} child=${r}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${S} vs ${r}`);if(!u||!a)throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let g=xt(o);if(!g){let p=G(me,`${f}@${d||"0"}`);try{await xo(a,p);try{Po()}catch{}}catch($){throw $.fallback&&await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason}}}),$}try{g=await No(p),At(o,g,{workflowUuid:f,version:d,runtimeTag:r,cacheDir:p})}catch($){throw kt(o,$),await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:$.message,code:$.reason||"IMPORT_FAILED"}}}),$.fallback?$:new O("import-failed",$.message)}}let w=Date.now(),b=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},h,y;try{h=await vo(b,async()=>{let $=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return Tt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>$.run(e.parentAgent,m,{signal:e.signal}))}),y=h&&typeof h=="object"&&"state"in h?h.state:h}catch(p){throw await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-w}}),p}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"canceled",finalState:y,durationMs:Date.now()-w}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await J({apiBase:n.apiBase,authToken:n.authToken,payload:{childExecutionId:s,status:"completed",finalState:y,durationMs:Date.now()-w}}),{finalState:y,executionId:s}}function Oo(o){let e=0,t=[o];for(;t.length;){let n=t.pop(),i;try{i=Ct(n)}catch{continue}if(i.isDirectory()){let s;try{s=Rt(n)}catch{continue}for(let r of s)t.push(G(n,r))}else e+=i.size}return e}function Po({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=Rt(me),t=[],n=0;for(let a of e){let l=G(me,a),d;try{d=Ct(l)}catch{continue}let f=d.isDirectory()?Oo(l):d.size;n+=f,t.push({name:a,full:l,size:f,mtimeMs:d.mtimeMs})}if(n<=o)return{evicted:0,freedBytes:0,totalBytes:n};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,r=0;for(let a of t){if(n-s<=i)break;if(!Y(G(a.full,".lock")))try{Eo(a.full,{recursive:!0,force:!0}),s+=a.size,r+=1}catch(l){E.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return r>0&&E.info(`[sub-graph cache] evicted ${r} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:r,freedBytes:s,totalBytes:n-s}}catch(e){return E.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Co=2e3,Ro=600*1e3,Bo=new Set(["completed","failed","canceled","timeout"]);function Mo(){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 jo(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Do(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Lo(){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,n)=>t==null?t:t[n],o):o}async function Le(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ce(),n=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=n)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${n}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{E.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:y}=await Bt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=Mt(y,e.output);return E.info(`[sub-graph] '${o}' completed in-process`),p}catch(y){if(y instanceof O||y?.fallback)E.info(`[sub-graph] in-process fallback for '${o}': ${y.reason||"unknown"} \u2014 using HTTP`);else throw y}let i=Mo(),s=jo(),r=Do(),a=Lo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,d={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};E.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(d)});if(!f.ok){let y=null,p="";try{y=await f.json(),p=y?.error||y?.message||JSON.stringify(y)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let A=y?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${A.used??"?"}/${A.limit??"?"} on plan ${A.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=A,R}if(f.status===400){let A=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw A.code="SUBGRAPH_INVALID_INPUT",A.status=400,A.subgraph=o,A.validationErrors=y?.validationErrors||null,A.missing=y?.missing||null,A}let $=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw $.code="SUBGRAPH_TRIGGER_FAILED",$.status=f.status,$.subgraph=o,$}let u=await f.json(),c=u?.data?.jobId||u?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(u).slice(0,200)}`);if(e.async)return E.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let S=Number.isFinite(e.timeoutMs)?e.timeoutMs:Ro,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Co,w=`${i}/executions/${encodeURIComponent(c)}`,b=Date.now()+S,_="accepted",m=0;for(;Date.now()<b;){await new Promise(A=>setTimeout(A,g)),m+=1;let y=await fetch(w,{headers:{Authorization:`Bearer ${r}`}});if(!y.ok){if(y.status>=500){E.warn(`[sub-graph] status poll for ${c} returned ${y.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${y.status}`)}let p=await y.json(),$=p?.data||p?.execution||p;if(_=$?.status||_,Bo.has(_)){if(_!=="completed"){let I=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw I.subgraphJobId=c,I.subgraphStatus=_,I}let A=$?.finalState||$?.state||{},R=Mt(A,e.output);return E.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),R}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(S/1e3)}s (last status: ${_})`);throw h.subgraphJobId=c,h.subgraphStatus=_,h}import{existsSync as jt,readFileSync as Fo}from"node:fs";import{join as Fe,dirname as Dt}from"node:path";var le=class{static async loadContext(e,t,n={}){let i={},s=n.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Dt(Fe(t,e));for(let l of s){let d=await this.findAndMergeContextFiles(l,a,t);if(d){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=d}}}let r=n.discovery||{};for(let[a,l]of Object.entries(r))try{let d=Fe(t,l);jt(d)&&(i[a]=await this.loadFile(d))}catch(d){console.warn(`[workflow] could not load context '${a}' from '${l}': ${d.message}`)}return i}static async findAndMergeContextFiles(e,t,n){let i=[],s=t;for(;s.startsWith(n);){let r=Fe(s,e);if(jt(r))try{i.unshift(await this.loadFile(r))}catch(l){console.warn(`[workflow] could not load ${e} from ${r}: ${l.message}`)}let a=Dt(s);if(a===s)break;s=a}return i.length===0?null:i.every(r=>typeof r=="string")?i.join(`
|
|
34
|
+
${s}`);let a=r(),l=a.cwd||process.cwd(),u=a.sessionPath;try{if(u){let d=Be(u,U);if(Tt(d)){let y=JSON.parse(bt(d,"utf-8"));y.currentNode=this.name,Re(d,JSON.stringify(y,null,2),"utf-8")}let c=Be(u,"..",U);if(Tt(c))try{let y=JSON.parse(bt(c,"utf-8"));y.currentNode=this.name,Re(c,JSON.stringify(y,null,2),"utf-8")}catch{}}}catch(d){I.debug(`[workflow] could not update session info: ${d.message}`)}let f=null;for(let d=0;d<=this.retries;d++)try{I.debug(`[workflow] node '${this.name}' attempt ${d}`);let c=r().config||{},y=c.agents||{},g=this.config.agent??y[this.name]??null,S={state:r()};g&&(S.preferredAgent=g);let b={workspace:l,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],plugins:this.config.plugins||[],sessionPath:u,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},_=e?._coreInvokeAgent;_||(_=(await Promise.resolve().then(()=>(X(),ae))).invokeAgent);let m=await _(s,S,b),h,w;if(typeof m=="string"?(h=m,w=null):m.structured?(h=m.raw||JSON.stringify(m.structured,null,2),w=m.structured):(h=m.raw||JSON.stringify(m,null,2),w=m.extracted||null),u)try{let p=Be(u,this.name,"raw_stream_output.txt");yo(wo(p),{recursive:!0}),Re(p,typeof h=="string"?h:JSON.stringify(h),"utf-8")}catch(p){I.debug(`[workflow] could not save raw output: ${p.message}`)}if(this.isZodSchema&&w){I.info(`[workflow] node '${this.name}': output validated: ${JSON.stringify(w,null,2)}`);let p=w;if(typeof this.onComplete=="function")try{p=await this.onComplete(r(),w)}catch(T){I.warn(`[workflow] onComplete hook failed: ${T.message}`)}return{success:!0,output:p,raw:h}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(r(),{raw:h}),raw:h}}catch(p){throw new Error(`onComplete failed: ${p.message}`,{cause:p})}if(this.parser){let p=this.parser.parse(h);return I.info(`[workflow] node '${this.name}': parsed output: ${JSON.stringify(p,null,2)}`),N.step("Output parsed"),{success:!0,output:p,raw:h}}return{success:!0,output:h,raw:h}}catch(c){f=c,d<this.retries&&I.info(`[workflow] node '${this.name}' failed, retrying (${d+1}/${this.retries})\u2026`)}return{success:!1,error:f.message,raw:null}}};F();F();import{mkdirSync as Eo,existsSync as Y,statSync as Ct,readdirSync as Rt,rmSync as Io}from"node:fs";import{spawn as xt}from"node:child_process";import{join as G}from"node:path";import{pathToFileURL as bo}from"node:url";import{AsyncLocalStorage as To}from"node:async_hooks";import{AsyncLocalStorage as So}from"node:async_hooks";var je=new So;function ce(){let o=je.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 vt(o,e){let t=je.getStore()||ce(),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 je.run(r,e)}var De=new Map,Le=new Map,$t=new Map;function kt(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");De.set(o,e),Le.set(o,"ready"),$t.set(o,{...t,cachedAt:Date.now()})}function At(o,e){Le.set(o,"failed"),$t.set(o,{error:e?.message||String(e),failedAt:Date.now()}),De.delete(o)}function Nt(o){return Le.get(o)==="ready"?De.get(o):null}var me=process.env.ZIBBY_SUBGRAPH_CACHE_DIR||"/tmp/zibby/subgraphs";function vo(){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"}},Ot=new To,Pt=Promise.resolve();async function $o(o,e){let t=o&&typeof o=="object"&&!Array.isArray(o)?Object.entries(o).filter(([n,a])=>typeof n=="string"&&n&&typeof a=="string"):[];if(t.length===0)return e();let r=Ot.getStore()===!0,i=null;if(!r){let n=Pt;Pt=new Promise(a=>{i=a}),await n}let s=new Map;try{for(let[n,a]of t)s.set(n,Object.prototype.hasOwnProperty.call(process.env,n)?process.env[n]:void 0),process.env[n]=a;return I.debug(`[in-process subgraph] scoped ${t.length} child env var(s)${r?" (nested)":""}`),await Ot.run(!0,e)}finally{for(let[n,a]of s)a===void 0?delete process.env[n]:process.env[n]=a;i&&i()}}function ko(){let o=(process.env.SUBGRAPH_INTERNAL_URL||"").replace(/\/$/,""),e=(process.env.PROGRESS_API_URL||"").replace(/\/executions\/?$/,""),t=o||e,r=process.env.PROJECT_ID,i=process.env.PROJECT_API_TOKEN;if(!t||!r||!i)throw new O("env","SUBGRAPH_INTERNAL_URL/PROGRESS_API_URL/PROJECT_ID/PROJECT_API_TOKEN missing");return{apiBase:t,projectId:r,authToken:i}}async function Ao({apiBase:o,authToken:e,body:t}){let r;try{r=await fetch(`${o}/internal/subgraph/begin`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)})}catch(s){throw new O("network",`begin fetch failed: ${s.message}`)}let i=null;try{i=await r.json()}catch{}if(!r.ok){if(r.status===404){let s=new Error(`Sub-graph child '${t.childWorkflowType}' not found in project`);throw s.code="SUBGRAPH_NOT_FOUND",s.status=404,s}if(r.status===429){let s=i?.quotaInfo||{},n=new Error(`Sub-graph blocked by quota (${s.used??"?"}/${s.limit??"?"} on ${s.planId||"plan"})`);throw n.code="SUBGRAPH_QUOTA_EXCEEDED",n.status=429,n.quotaInfo=s,n}if(r.status===400&&i?.validationErrors){let s=new Error(`Sub-graph rejected input: ${i?.error||i?.message||"validation failed"}`);throw s.code="SUBGRAPH_INVALID_INPUT",s.status=400,s.validationErrors=i.validationErrors,s.missing=i.missing,s}throw new O("begin-status",`begin returned ${r.status}`)}return i?.data||i}async function J({apiBase:o,authToken:e,payload:t}){try{let r=await fetch(`${o}/internal/subgraph/finalize`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(t)});r.ok||I.warn(`[in-process subgraph] finalize returned ${r.status} for ${t.childExecutionId}`)}catch(r){I.warn(`[in-process subgraph] finalize failed: ${r.message}`)}}async function No(o,e){let t=G(e,".ready"),r=G(e,"graph.mjs");if(Y(t)&&Y(r))return;Eo(e,{recursive:!0});let i=G(e,".lock"),s=!1;try{let{openSync:n,closeSync:a}=await import("node:fs"),l=n(i,"wx");a(l),s=!0}catch(n){if(n.code!=="EEXIST")throw n}if(!s){let n=Date.now()+3e4;for(;Date.now()<n;){if(Y(t)&&Y(r))return;await new Promise(a=>setTimeout(a,100))}throw new O("bundle-extract-timeout","sibling extract did not complete within 30s")}try{await new Promise((l,u)=>{let f=xt("curl",["-fsSL",o],{stdio:["ignore","pipe","inherit"]}),d=xt("tar",["-xzf","-","-C",e],{stdio:["pipe","inherit","inherit"]});f.stdout.pipe(d.stdin);let c,y,g=()=>{if(c!==void 0&&y!==void 0){if(c!==0)return u(new Error(`curl exited ${c}`));if(y!==0)return u(new Error(`tar exited ${y}`));l()}};f.on("close",S=>{c=S,g()}),d.on("close",S=>{y=S,g()}),f.on("error",u),d.on("error",u)});let{writeFileSync:n,unlinkSync:a}=await import("node:fs");n(t,"");try{a(i)}catch{}}catch(n){try{let{unlinkSync:a}=await import("node:fs");a(i)}catch{}throw new O("bundle-extract-failed",n.message)}}async function xo(o){let e=G(o,"graph.mjs");if(!Y(e))throw new O("entry-missing",`graph.mjs missing under ${o}`);let t;try{t=await import(bo(e).href)}catch(i){throw new O("import-failed",`${i?.code||i?.name||"unknown"}: ${i.message}`)}let r=t.default||Object.values(t).find(i=>typeof i=="function"&&i.prototype?.buildGraph);if(!r)throw new O("entry-class-missing","no buildGraph() class export found");return r}async function Bt(o,e={}){if(!o||typeof o!="string")throw new Error("runInProcessSubgraph: workflowName (string) is required");let t=ce(),r;try{r=ko()}catch(p){throw p}I.debug(`[in-process subgraph] begin '${o}' parent=${t.executionId||"<root>"}`);let i=await Ao({apiBase:r.apiBase,authToken:r.authToken,body:{parentExecutionId:t.executionId,childWorkflowType:o,input:e.input||{},...e.conversationId?{conversationId:e.conversationId}:{}}}),{childExecutionId:s,runtimeTag:n,bundlePresignedUrl:a,sourcesPresignedUrl:l,workflowVersion:u,workflowUuid:f,bundleReady:d,nodeConfigs:c}=i,y=vo();if(n&&n!==y)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:`runtimeTag mismatch: parent=${y} child=${n}`,code:"RUNTIME_MISMATCH"}}}),new O("runtime-mismatch",`${y} vs ${n}`);if(!d||!a)throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",error:{message:"bundle not ready for in-process; falling back to HTTP",code:"NO_BUNDLE"}}}),new O("no-bundle","workflow bundle not built yet");let g=Nt(o);if(!g){let p=G(me,`${f}@${u||"0"}`);try{await No(a,p);try{Po()}catch{}}catch(T){throw T.fallback&&await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:T.message,code:T.reason}}}),T}try{g=await xo(p),kt(o,g,{workflowUuid:f,version:u,runtimeTag:n,cacheDir:p})}catch(T){throw At(o,T),await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:T.message,code:T.reason||"IMPORT_FAILED"}}}),T.fallback?T:new O("import-failed",T.message)}}let S=Date.now(),b=i.env&&typeof i.env=="object"&&!Array.isArray(i.env)?i.env:null,_=c&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,m={...e.input||{},..._?{nodeConfigs:c}:{}},h,w;try{h=await $o(b,async()=>{let T=await(typeof g=="function"&&g.prototype?.buildGraph?new g:g).buildGraph();return vt({executionId:s,parentExecutionId:t.executionId,conversationId:e.conversationId!==void 0?e.conversationId:t.conversationId,dispatchMode:"inprocess"},()=>T.run(e.parentAgent,m,{signal:e.signal}))}),w=h&&typeof h=="object"&&"state"in h?h.state:h}catch(p){throw await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"failed",error:{message:p.message,code:p.code||"CHILD_THREW",stack:p.stack},durationMs:Date.now()-S}}),p}if(h&&typeof h=="object"&&h.stoppedExternally){await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"canceled",finalState:w,durationMs:Date.now()-S}});let p=new Error(`Sub-graph '${o}' canceled by parent abort`);throw p.code="SUBGRAPH_CANCELED",p.subgraphJobId=s,p}return await J({apiBase:r.apiBase,authToken:r.authToken,payload:{childExecutionId:s,status:"completed",finalState:w,durationMs:Date.now()-S}}),{finalState:w,executionId:s}}function Oo(o){let e=0,t=[o];for(;t.length;){let r=t.pop(),i;try{i=Ct(r)}catch{continue}if(i.isDirectory()){let s;try{s=Rt(r)}catch{continue}for(let n of s)t.push(G(r,n))}else e+=i.size}return e}function Po({cap:o=Number(process.env.ZIBBY_SUBGRAPH_CACHE_CAP_BYTES||2*1024*1024*1024)}={}){try{if(!Y(me))return{evicted:0,freedBytes:0};let e=Rt(me),t=[],r=0;for(let a of e){let l=G(me,a),u;try{u=Ct(l)}catch{continue}let f=u.isDirectory()?Oo(l):u.size;r+=f,t.push({name:a,full:l,size:f,mtimeMs:u.mtimeMs})}if(r<=o)return{evicted:0,freedBytes:0,totalBytes:r};t.sort((a,l)=>a.mtimeMs-l.mtimeMs);let i=Math.floor(o*.7),s=0,n=0;for(let a of t){if(r-s<=i)break;if(!Y(G(a.full,".lock")))try{Io(a.full,{recursive:!0,force:!0}),s+=a.size,n+=1}catch(l){I.debug(`[sub-graph cache] evict skip ${a.name}: ${l.message}`)}}return n>0&&I.info(`[sub-graph cache] evicted ${n} entr(y/ies), freed ${(s/1024/1024).toFixed(1)}MB`),{evicted:n,freedBytes:s,totalBytes:r-s}}catch(e){return I.debug(`[sub-graph cache] evict failed: ${e.message}`),{evicted:0,freedBytes:0}}}var Co=2e3,Ro=600*1e3,Bo=new Set(["completed","failed","canceled","timeout"]);function jo(){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 Do(){let o=process.env.PROJECT_ID;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_ID env var.");return o}function Lo(){let o=process.env.PROJECT_API_TOKEN;if(!o)throw new Error("Sub-graph dispatch requires PROJECT_API_TOKEN env var.");return o}function Mo(){return process.env.EXECUTION_ID||null}function jt(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 Me(o,e={}){if(!o||typeof o!="string")throw new Error("dispatchSubgraph: workflowName (string) is required");let t=ce(),r=Number(process.env.ZIBBY_SUBGRAPH_MAX_DEPTH||10);if((t.depth||0)>=r)throw new Error(`dispatchSubgraph('${o}'): sub-graph depth ${t.depth} reached cap of ${r}. Restructure the graph or raise ZIBBY_SUBGRAPH_MAX_DEPTH.`);if(process.env.ZIBBY_INPROCESS_SUBGRAPH!=="0"&&!e.async)try{I.debug(`[sub-graph] trying in-process for '${o}'`);let{finalState:w}=await Bt(o,{input:e.input,conversationId:e.conversationId,signal:e.signal,parentAgent:e.parentAgent}),p=jt(w,e.output);return I.info(`[sub-graph] '${o}' completed in-process`),p}catch(w){if(w instanceof O||w?.fallback)I.info(`[sub-graph] in-process fallback for '${o}': ${w.reason||"unknown"} \u2014 using HTTP`);else throw w}let i=jo(),s=Do(),n=Lo(),a=Mo(),l=`${i}/projects/${encodeURIComponent(s)}/workflows/${encodeURIComponent(o)}/trigger`,u={input:e.input||{},...a?{parentExecutionId:a}:{},...e.conversationId?{conversationId:e.conversationId}:{}};I.info(`[sub-graph] dispatching '${o}' (${e.async?"async":"sync"}) from parent ${a||"<none>"}`);let f=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(u)});if(!f.ok){let w=null,p="";try{w=await f.json(),p=w?.error||w?.message||JSON.stringify(w)}catch{p=await f.text().catch(()=>"")}if(f.status===429){let k=w?.quotaInfo||{},R=new Error(`Sub-graph '${o}' blocked by execution quota (${k.used??"?"}/${k.limit??"?"} on plan ${k.planId||"unknown"}). Sub-workflow runs count toward the same monthly cap as user-triggered runs.`);throw R.code="SUBGRAPH_QUOTA_EXCEEDED",R.status=429,R.subgraph=o,R.quotaInfo=k,R}if(f.status===400){let k=new Error(`Sub-graph '${o}' rejected input: ${p}`);throw k.code="SUBGRAPH_INVALID_INPUT",k.status=400,k.subgraph=o,k.validationErrors=w?.validationErrors||null,k.missing=w?.missing||null,k}let T=new Error(`Sub-graph '${o}' trigger rejected (${f.status}): ${p}`);throw T.code="SUBGRAPH_TRIGGER_FAILED",T.status=f.status,T.subgraph=o,T}let d=await f.json(),c=d?.data?.jobId||d?.jobId;if(!c)throw new Error(`Sub-graph '${o}' trigger returned no jobId: ${JSON.stringify(d).slice(0,200)}`);if(e.async)return I.info(`[sub-graph] async dispatch of '${o}' \u2192 jobId=${c} (not waiting)`),{jobId:c,status:"accepted",workflow:o};let y=Number.isFinite(e.timeoutMs)?e.timeoutMs:Ro,g=Number.isFinite(e.pollIntervalMs)?e.pollIntervalMs:Co,S=`${i}/executions/${encodeURIComponent(c)}`,b=Date.now()+y,_="accepted",m=0;for(;Date.now()<b;){await new Promise(k=>setTimeout(k,g)),m+=1;let w=await fetch(S,{headers:{Authorization:`Bearer ${n}`}});if(!w.ok){if(w.status>=500){I.warn(`[sub-graph] status poll for ${c} returned ${w.status}, will retry`);continue}throw new Error(`Sub-graph status poll failed for ${c}: ${w.status}`)}let p=await w.json(),T=p?.data||p?.execution||p;if(_=T?.status||_,Bo.has(_)){if(_!=="completed"){let E=new Error(`Sub-graph '${o}' (${c}) ended in status '${_}'`);throw E.subgraphJobId=c,E.subgraphStatus=_,E}let k=T?.finalState||T?.state||{},R=jt(k,e.output);return I.info(`[sub-graph] '${o}' (${c}) completed after ${m} polls`),R}}let h=new Error(`Sub-graph '${o}' (${c}) timed out after ${Math.round(y/1e3)}s (last status: ${_})`);throw h.subgraphJobId=c,h.subgraphStatus=_,h}import{existsSync as Dt,readFileSync as Fo}from"node:fs";import{join as Fe,dirname as Lt}from"node:path";var le=class{static async loadContext(e,t,r={}){let i={},s=r.filenames||["CONTEXT.md","AGENTS.md"];if(e){let a=Lt(Fe(t,e));for(let l of s){let u=await this.findAndMergeContextFiles(l,a,t);if(u){let f=l.replace(/\.[^.]+$/,"").toLowerCase();i[f]=u}}}let n=r.discovery||{};for(let[a,l]of Object.entries(n))try{let u=Fe(t,l);Dt(u)&&(i[a]=await this.loadFile(u))}catch(u){console.warn(`[workflow] could not load context '${a}' from '${l}': ${u.message}`)}return i}static async findAndMergeContextFiles(e,t,r){let i=[],s=t;for(;s.startsWith(r);){let n=Fe(s,e);if(Dt(n))try{i.unshift(await this.loadFile(n))}catch(l){console.warn(`[workflow] could not load ${e} from ${n}: ${l.message}`)}let a=Lt(s);if(a===s)break;s=a}return i.length===0?null:i.every(n=>typeof n=="string")?i.join(`
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
38
|
-
`):i.every(
|
|
38
|
+
`):i.every(n=>typeof n=="object")?Object.assign({},...i):i[i.length-1]}static async loadFile(e){let t=Fo(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(t);if(e.endsWith(".js")||e.endsWith(".mjs")){let{pathToFileURL:r}=await import("url"),i=await import(r(e).href);return i.default||i}return t}};import{mkdirSync as Gt,existsSync as Ge,writeFileSync as Mt,unlinkSync as Go}from"node:fs";import{join as z,resolve as Ut}from"node:path";import{config as Uo}from"dotenv";import{zodToJsonSchema as Ft}from"zod-to-json-schema";import{z as ye}from"zod";import Wo from"handlebars";function Ho({traceFrom:o,sessionId:e,sessionPath:t,idSource:r,mkdirFresh:i}){if(!(process.env.ZIBBY_SESSION_LOG==="1"||process.env.ZIBBY_SESSION_LOG==="true"))return;let n=typeof process.ppid=="number"?process.ppid:"n/a",a=`[zibby:session] from=${o} pid=${process.pid} ppid=${n} sessionId=${e} source=${r} mkdir=${i?"yes":"no"} path=${t}`;if(console.log(a),process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true"){let f=(new Error("session trace").stack||"").split(`
|
|
39
39
|
`).slice(2,14).join(`
|
|
40
40
|
`);console.log(`[zibby:session] stack (${o}):
|
|
41
|
-
${f}`)}}function Wt(){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 Ht(){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 Ut(String(e).trim())}catch{return String(e).trim()}}function Jt(){Wt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Yt({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 zt(o={}){let e=ke.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),n=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${n}`:n}function Zt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:n="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,r="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let d=Ut(String(process.env.ZIBBY_SESSION_PATH));d&&(i=d,r="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let d=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(d)a=d,r="ZIBBY_SESSION_ID";else{let u=e.sessionId!=null?String(e.sessionId).trim():"";u&&u!=="last"?(a=u,r="config.sessionId"):(a=zt(e),r="generated")}s=s??Date.now();let f=e.paths?.output||se;i=z(o,f,ve,a)}let l=!Ge(i);return l&&Gt(i,{recursive:!0}),(l||r!=="initialState.sessionPath")&&Ho({traceFrom:n,sessionId:a,sessionPath:i,idSource:r,mkdirFresh:l}),Yt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,n={}){if(!(t instanceof L)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let r=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:r.workflow,retries:r.retries,onComplete:r.onComplete,execute:async d=>{let f=d?.state&&typeof d.state.getAll=="function"?d.state.getAll():d,u;return typeof r.input=="function"?u=r.input(f):r.input&&typeof r.input=="object"?u=r.input:u={},Le(r.workflow,{input:u,async:r.async===!0,conversationId:typeof r.conversationId=="function"?r.conversationId(f):r.conversationId,output:r.output,timeoutMs:r.timeoutMs,pollIntervalMs:r.pollIntervalMs,signal:f?._signal,parentAgent:d?.agent})}},l=new L(a);return l.name=e,this.nodes.set(e,l),n.prompt&&this.nodePrompts.set(e,n.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}let i=!(t instanceof L)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof L?t:new L(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),n.prompt?this.nodePrompts.set(e,n.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(n).length>0&&this.nodeOptions.set(e,n),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:n}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:n}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,n,i,s){let r=n;for(let a=e.length-1;a>=0;a--){let l=e[a],d=r;r=()=>l(t,d,i,s)}return r()}serialize(){let e=[],t={};for(let[u,c]of this.nodes){let S=this.nodeTypeMap.get(u)||(c?.config?._isRouter===!0?"decision":u);e.push({id:u,type:S,data:{nodeType:S,label:u}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let w=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;w&&(g.description=w);let b=this.nodePrompts.get(u);if(b)g.prompt=b;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof Se?.toJSONSchema=="function")try{p=Se.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ft(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[u];_?.toolIds&&(g.tools=_.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(g.skills=[...m]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(g.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let y=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;y&&y.length>0&&(g.stores=y.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[u]=g)}let n=[];for(let[u,c]of this.edges)if(typeof c=="string")n.push({source:u,target:c});else if(c.conditional){let S=this.conditionalCodeMap.get(u)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),w=c.labels||{},b=this.nodes.get(u),_=b?.config?._isRouter===!0||this.nodeTypeMap.get(u)==="decision"||!b,m=u;if(!_){let h=`${u}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),n.push({source:u,target:h}),m=h}for(let h of g){let y={source:m,target:h,data:{conditionalCode:S}};w[h]&&(y.label=w[h]),n.push(y)}}let i=u=>{if(!u)return null;if(typeof Se?.toJSONSchema=="function")try{return Se.toJSONSchema(u)}catch{}try{return Ft(u,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),n.unshift({source:"START",target:this.entryPoint}));let s=0;for(let u of n)if(u.target==="END"){s+=1;let c=`END__${s}`;u.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let u of this.nodes.keys())if(!this.edges.has(u)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),n.push({source:u,target:c})}let r=this._topoOrderNodes(e,n),a=this._runtimeSchema(),l=i(a||this.stateSchema),d=i(this.inputSchema),f=i(this.contextSchema);return{nodes:r,edges:n,nodeConfigs:t,stateSchema:l,inputSchema:d,contextSchema:f}}_topoOrderNodes(e,t){let n=new Map(e.map((u,c)=>[u.id,c])),i=new Map(e.map(u=>[u.id,u])),s=new Map(e.map(u=>[u.id,0])),r=new Map(e.map(u=>[u.id,[]]));for(let u of t)r.has(u.source)&&s.has(u.target)&&(r.get(u.source).push(u.target),s.set(u.target,s.get(u.target)+1));let a=new Set,l=new Set(n.keys()),d=[...l].filter(u=>s.get(u)===0),f=[];for(;f.length<e.length;){let u;if(d.length>0){if(d.sort((c,S)=>n.get(c)-n.get(S)),u=d.shift(),a.has(u))continue}else u=[...l].sort((c,S)=>n.get(c)-n.get(S))[0];a.add(u),l.delete(u),f.push(i.get(u));for(let c of r.get(u)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&d.push(c)}return f}_inferConditionalTargets(e,t){let n=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,r;for(;(r=s.exec(n))!==null;){let d=r[2]!==void 0?r[2]:r[3];d!==void 0&&d!==""&&i.add(d)}let a=new Set(["END","START","__end__","__start__"]);for(let d of this.nodes.keys())a.add(d);if(t&&typeof t=="object")for(let d of Object.keys(t))a.add(d);let l=new Set;for(let d of i)a.has(d)&&l.add(d);if(l.size===0){let d=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=d.exec(n))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let n=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");n=e.definitions[i]||e}return this._flattenSchema(n,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let n=[],i=e.properties||{},s=e.required||[];for(let[r,a]of Object.entries(i)){let l=t?`${t}.${r}`:r;n.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(r),optional:!s.includes(r)}),a.type==="object"&&a.properties&&n.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&n.push(...this._flattenSchema(a.items,`${l}[]`))}return n}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let n=[];t.success!==void 0&&n.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)n.push(`${i}: ${s}`);else if(Array.isArray(s)){let r=s.length,a=s.filter(d=>d?.passed===!0).length,l=s.some(d=>d?.passed!==void 0);n.push(l?`${i}: ${a}/${r} passed${r-a?`, ${r-a} failed`:""}`:`${i}: ${r} items`)}if(n.length>=4)break}return n}async run(e,t={},n={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;n.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=n.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,r=t.cwd||process.cwd();Uo({path:z(r,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let T=z(r,".zibby.config.js");Ge(T)&&(a=(await import(T)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let T=a?.agent;T?.provider?l=T.provider:T?.gemini?l="gemini":T?.claude?l="claude":T?.cursor?l="cursor":T?.codex?l="codex":l=process.env.AGENT_TYPE||"cursor"}let d=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let T=f.safeParse(t);if(!T.success){let P=T.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}x.step("State validated against schema")}let u=Ht(),c=t.sessionPath||u;c||Jt();let{sessionPath:S,sessionTimestamp:g,sessionId:w}=Zt({cwd:r,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});x.step(`Session ${w}`);let b=await le.loadContext(t.specPath||"",r,d);Object.keys(b).length>0&&x.step(`Context loaded: ${Object.keys(b).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:S,sessionTimestamp:g,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:y}=await Promise.resolve().then(()=>(ie(),wt)),p=a.skills&&typeof a.skills=="object"?a.skills:{},$=Object.values(p).filter(T=>T&&typeof T=="object"&&typeof T.id=="string"),A=T=>{for(let P of $)if(P.id===T)return P;return y(T)},R=new Set;for(let[,T]of this.nodes)for(let P of T.config?.skills||[])R.add(P);for(let T of R){let P=A(T);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&h.set(T,C)}catch{}}let I=this.entryPoint,de=[],Ze=a?.recursionLimit??100,Xt=0;try{for(;I&&I!=="END";){if(++Xt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=z(S,Ae);if(Ge(P)){try{Go(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
-
\u{1F6D1} External stop requested \u2014 ending workflow.`),
|
|
43
|
-
${f}`),a.includes(".")||
|
|
41
|
+
${f}`)}}function Wt(){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 Ht(){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 Ut(String(e).trim())}catch{return String(e).trim()}}function Jt(){Wt()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function Yt({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 zt(o={}){let e=Ae.map(s=>process.env[s]).find(Boolean),t=Math.random().toString(36).slice(2,6),r=e||`${Date.now()}_${t}`,i=o.paths?.sessionPrefix;return i?`${i}_${r}`:r}function Zt({cwd:o=process.cwd(),config:e={},initialState:t={},traceFrom:r="resolveWorkflowSession"}={}){let i=t.sessionPath,s=t.sessionTimestamp,n="initialState.sessionPath";if(!i&&process.env.ZIBBY_SESSION_PATH)try{let u=Ut(String(process.env.ZIBBY_SESSION_PATH));u&&(i=u,n="ZIBBY_SESSION_PATH")}catch{}let a;if(i)a=String(i).split(/[/\\]/).filter(Boolean).pop(),s==null&&(s=Date.now());else{let u=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(u)a=u,n="ZIBBY_SESSION_ID";else{let d=e.sessionId!=null?String(e.sessionId).trim():"";d&&d!=="last"?(a=d,n="config.sessionId"):(a=zt(e),n="generated")}s=s??Date.now();let f=e.paths?.output||se;i=z(o,f,$e,a)}let l=!Ge(i);return l&&Gt(i,{recursive:!0}),(l||n!=="initialState.sessionPath")&&Ho({traceFrom:r,sessionId:a,sessionPath:i,idSource:n,mkdirFresh:l}),Yt({sessionPath:i,sessionId:a}),{sessionPath:i,sessionId:a,sessionTimestamp:s}}var Q=class{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.inputSchema=e.inputSchema||null,this.contextSchema=e.contextSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map,this._invokeAgent=e.invokeAgent||null,this._compiledPrompts=new Map}setInputSchema(e){return this.inputSchema=e,this}setContextSchema(e){return this.contextSchema=e,this}setStateSchema(e){return this.stateSchema=e,this}getInputSchema(){return this.inputSchema}getContextSchema(){return this.contextSchema}getStateSchema(){return this.stateSchema}_runtimeSchema(){if(this.inputSchema&&this.contextSchema)try{if(typeof this.inputSchema.merge=="function")return this.inputSchema.merge(this.contextSchema);if(typeof this.inputSchema.and=="function")return this.inputSchema.and(this.contextSchema)}catch{}return this.inputSchema&&!this.contextSchema?this.inputSchema:this.stateSchema}addNode(e,t,r={}){if(!(t instanceof M)&&t&&typeof t=="object"&&typeof t.workflow=="string"){let n=t,a={name:e,_isCustomCode:!0,dispatchesWorkflow:n.workflow,retries:n.retries,onComplete:n.onComplete,execute:async u=>{let f=u?.state&&typeof u.state.getAll=="function"?u.state.getAll():u,d;return typeof n.input=="function"?d=n.input(f):n.input&&typeof n.input=="object"?d=n.input:d={},Me(n.workflow,{input:d,async:n.async===!0,conversationId:typeof n.conversationId=="function"?n.conversationId(f):n.conversationId,output:n.output,timeoutMs:n.timeoutMs,pollIntervalMs:n.pollIntervalMs,signal:f?._signal,parentAgent:u?.agent})}},l=new M(a);return l.name=e,this.nodes.set(e,l),r.prompt&&this.nodePrompts.set(e,r.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}let i=!(t instanceof M)&&t&&typeof t=="object"&&typeof t.execute!="function"&&t.prompt==null&&t.outputSchema==null&&t._isCustomCode!==!0,s=t instanceof M?t:new M(i?{...t,_isRouter:!0}:t);return s.name=e,this.nodes.set(e,s),r.prompt?this.nodePrompts.set(e,r.prompt):typeof t?.prompt=="string"&&t.prompt.trim()&&this.nodePrompts.set(e,t.prompt),Object.keys(r).length>0&&this.nodeOptions.set(e,r),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:r}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:r}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,r,i,s){let n=r;for(let a=e.length-1;a>=0;a--){let l=e[a],u=n;n=()=>l(t,u,i,s)}return n()}serialize(){let e=[],t={};for(let[d,c]of this.nodes){let y=this.nodeTypeMap.get(d)||(c?.config?._isRouter===!0?"decision":d);e.push({id:d,type:y,data:{nodeType:y,label:d}});let g={};c._isCustomCode&&typeof c.execute=="function"&&(g.customCode=c.execute.toString());let S=typeof c?.config?.description=="string"&&c.config.description.trim()?c.config.description:typeof c?.description=="string"&&c.description.trim()?c.description:null;S&&(g.description=S);let b=this.nodePrompts.get(d);if(b)g.prompt=b;else if(typeof c.prompt=="function")try{let p=c.prompt({});typeof p=="string"&&p.trim()&&(g.prompt=p,g.promptIsCode=!0)}catch{}if(typeof c.customExecute=="function"&&(g.executeCode=c.customExecute.toString()),typeof c?.config?.dispatchesWorkflow=="string"&&c.config.dispatchesWorkflow.trim()&&(g.dispatchesWorkflow=c.config.dispatchesWorkflow.trim()),c.outputSchema)if(typeof c.outputSchema._def<"u"){let p=null;if(typeof ye?.toJSONSchema=="function")try{p=ye.toJSONSchema(c.outputSchema)}catch{}if(!p)try{p=Ft(c.outputSchema,{target:"openApi3"})}catch{}g.outputSchema=p?{jsonSchema:p,variables:this._flattenJsonSchemaToVariables(p)}:{schema:c.outputSchema}}else g.outputSchema={schema:c.outputSchema};let _=(this.resolvedToolsMap||{})[d];_?.toolIds&&(g.tools=_.toolIds);let m=Array.isArray(c?.config?.skills)?c.config.skills:Array.isArray(c?.skills)?c.skills:null;m&&m.length>0&&(g.skills=[...m]);let h=Array.isArray(c?.config?.plugins)?c.config.plugins:Array.isArray(c?.plugins)?c.plugins:null;h&&h.length>0&&(g.plugins=h.map(p=>p&&typeof p=="object"?{...p}:p));let w=Array.isArray(c?.config?.stores)?c.config.stores:Array.isArray(c?.stores)?c.stores:null;w&&w.length>0&&(g.stores=w.map(p=>p&&typeof p=="object"?{...p}:p)),Object.keys(g).length>0&&(t[d]=g)}let r=[];for(let[d,c]of this.edges)if(typeof c=="string")r.push({source:d,target:c});else if(c.conditional){let y=this.conditionalCodeMap.get(d)||c.routes.toString(),g=this._inferConditionalTargets(c.routes,c.labels),S=c.labels||{},b=this.nodes.get(d),_=b?.config?._isRouter===!0||this.nodeTypeMap.get(d)==="decision"||!b,m=d;if(!_){let h=`${d}__branch`;e.push({id:h,type:"decision",data:{nodeType:"decision",label:h}}),r.push({source:d,target:h}),m=h}for(let h of g){let w={source:m,target:h,data:{conditionalCode:y}};S[h]&&(w.label=S[h]),r.push(w)}}let i=d=>{if(!d)return null;if(typeof ye?.toJSONSchema=="function")try{return ye.toJSONSchema(d)}catch{}try{return Ft(d,{target:"openApi3"})}catch{return null}};this.entryPoint&&this.nodes.has(this.entryPoint)&&(e.unshift({id:"START",type:"start",data:{nodeType:"start",label:"Start"}}),r.unshift({source:"START",target:this.entryPoint}));let s=0;for(let d of r)if(d.target==="END"){s+=1;let c=`END__${s}`;d.target=c,e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}})}for(let d of this.nodes.keys())if(!this.edges.has(d)){s+=1;let c=`END__${s}`;e.push({id:c,type:"end",data:{nodeType:"end",label:"End"}}),r.push({source:d,target:c})}let n=this._topoOrderNodes(e,r),a=this._runtimeSchema(),l=i(a||this.stateSchema),u=i(this.inputSchema),f=i(this.contextSchema);return{nodes:n,edges:r,nodeConfigs:t,stateSchema:l,inputSchema:u,contextSchema:f}}_topoOrderNodes(e,t){let r=new Map(e.map((d,c)=>[d.id,c])),i=new Map(e.map(d=>[d.id,d])),s=new Map(e.map(d=>[d.id,0])),n=new Map(e.map(d=>[d.id,[]]));for(let d of t)n.has(d.source)&&s.has(d.target)&&(n.get(d.source).push(d.target),s.set(d.target,s.get(d.target)+1));let a=new Set,l=new Set(r.keys()),u=[...l].filter(d=>s.get(d)===0),f=[];for(;f.length<e.length;){let d;if(u.length>0){if(u.sort((c,y)=>r.get(c)-r.get(y)),d=u.shift(),a.has(d))continue}else d=[...l].sort((c,y)=>r.get(c)-r.get(y))[0];a.add(d),l.delete(d),f.push(i.get(d));for(let c of n.get(d)||[])s.set(c,s.get(c)-1),s.get(c)<=0&&!a.has(c)&&u.push(c)}return f}_inferConditionalTargets(e,t){let r=e.toString(),i=new Set,s=/(['"])((?:\\.|(?!\1).)*?)\1|`((?:\\.|[^`$]|\$(?!\{))*?)`/g,n;for(;(n=s.exec(r))!==null;){let u=n[2]!==void 0?n[2]:n[3];u!==void 0&&u!==""&&i.add(u)}let a=new Set(["END","START","__end__","__start__"]);for(let u of this.nodes.keys())a.add(u);if(t&&typeof t=="object")for(let u of Object.keys(t))a.add(u);let l=new Set;for(let u of i)a.has(u)&&l.add(u);if(l.size===0){let u=/return\s+['"]([^'"]+)['"]/g,f;for(;(f=u.exec(r))!==null;)l.add(f[1])}return[...l]}_flattenJsonSchemaToVariables(e,t=""){let r=e;if(e.$ref&&e.definitions){let i=e.$ref.replace("#/definitions/","");r=e.definitions[i]||e}return this._flattenSchema(r,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];let r=[],i=e.properties||{},s=e.required||[];for(let[n,a]of Object.entries(i)){let l=t?`${t}.${n}`:n;r.push({path:l,type:a.type||"unknown",label:a.description||this._formatLabel(n),optional:!s.includes(n)}),a.type==="object"&&a.properties&&r.push(...this._flattenSchema(a,l)),a.type==="array"&&a.items?.type==="object"&&a.items.properties&&r.push(...this._flattenSchema(a.items,`${l}[]`))}return r}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];let r=[];t.success!==void 0&&r.push(`Result: ${t.success?"passed":"failed"}`);for(let[i,s]of Object.entries(t))if(!(i==="success"||i==="raw"||i==="nextNode")){if(typeof s=="string"&&s.length<=80)r.push(`${i}: ${s}`);else if(Array.isArray(s)){let n=s.length,a=s.filter(u=>u?.passed===!0).length,l=s.some(u=>u?.passed!==void 0);r.push(l?`${i}: ${a}/${n} passed${n-a?`, ${n-a} failed`:""}`:`${i}: ${n} items`)}if(r.length>=4)break}return r}async run(e,t={},r={}){if(!this.entryPoint)throw new Error("No entry point set for graph");let i=new AbortController;r.signal&&(r.signal.aborted?i.abort():r.signal.addEventListener("abort",()=>i.abort(),{once:!0}));let s=r.strategyAbortTimeoutMs??t.config?.strategyAbortTimeoutMs??5e3,n=t.cwd||process.cwd();Uo({path:z(n,".env")});let a=t.config||{};if(!a||Object.keys(a).length===0)try{let v=z(n,".zibby.config.js");Ge(v)&&(a=(await import(v)).default||{})}catch{}process.env.EXECUTION_ID&&!a.agent?.strictMode&&(a.agent={...a.agent,strictMode:!0});let l=t.agentType;if(!l){let v=a?.agent;v?.provider?l=v.provider:v?.gemini?l="gemini":v?.claude?l="claude":v?.cursor?l="cursor":v?.codex?l="codex":l=process.env.AGENT_TYPE||"claude"}let u=t.contextConfig||e?.config?.contextConfig||e?.config?.context||a?.context||{},f=this._runtimeSchema();if(f){let v=f.safeParse(t);if(!v.success){let P=v.error.issues.map(C=>`${C.path.join(".")}: ${C.message}`);throw console.error("\u274C Initial state validation failed:"),P.forEach(C=>console.error(` - ${C}`)),new Error(`State validation failed: ${P.join(", ")}`)}N.step("State validated against schema")}let d=Ht(),c=t.sessionPath||d;c||Jt();let{sessionPath:y,sessionTimestamp:g,sessionId:S}=Zt({cwd:n,config:a,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:c,sessionTimestamp:t.sessionTimestamp}});N.step(`Session ${S}`);let b=await le.loadContext(t.specPath||"",n,u);Object.keys(b).length>0&&N.step(`Context loaded: ${Object.keys(b).join(", ")}`);let _=t.outputPath;!_&&t.specPath&&(e?.calculateOutputPath?_=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));let m=new te({...t,config:a,agentType:l,outputPath:_,sessionPath:y,sessionTimestamp:g,context:b,resolvedTools:this.resolvedToolsMap||{},_signal:i.signal}),h=new Map;try{await import("@zibby/skills")}catch{}let{getSkill:w}=await Promise.resolve().then(()=>(ie(),St)),p=a.skills&&typeof a.skills=="object"?a.skills:{},T=Object.values(p).filter(v=>v&&typeof v=="object"&&typeof v.id=="string"),k=v=>{for(let P of T)if(P.id===v)return P;return w(v)},R=new Set;for(let[,v]of this.nodes)for(let P of v.config?.skills||[])R.add(P);for(let v of R){let P=k(v);if(typeof P?.middleware=="function")try{let C=await P.middleware();typeof C=="function"&&h.set(v,C)}catch{}}let E=this.entryPoint,ue=[],Ze=a?.recursionLimit??100,Xt=0;try{for(;E&&E!=="END";){if(++Xt>Ze)throw new Error(`Workflow exceeded recursion limit (${Ze}) \u2014 likely a cyclic conditional route. Set config.recursionLimit if you need a higher cap.`);let P=z(y,ke);if(Ge(P)){try{Go(P)}catch{}i.abort()}if(i.signal.aborted)return console.warn(`
|
|
42
|
+
\u{1F6D1} External stop requested \u2014 ending workflow.`),N.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:ue,stoppedExternally:!0};let C=this.nodes.get(E);if(!C)throw new Error(`Node '${E}' not found in graph`);let Ke=JSON.stringify({sessionPath:y,sessionTimestamp:g,currentNode:E,createdAt:new Date().toISOString(),config:m.get("config")}),Qt=z(y,U);Mt(Qt,Ke,"utf-8");let Ve=m.get("config")?.paths?.output||se,eo=z(n,Ve,U);Gt(z(n,Ve),{recursive:!0});try{Mt(eo,Ke,"utf-8")}catch{}let qe=t.onPipelineProgress;if(typeof qe=="function")try{qe({cwd:n,sessionPath:y,sessionId:S,outputBase:m.get("config")?.paths?.output||se,currentNode:E})}catch{}let to=(this.resolvedToolsMap||{})[E]||null;m.set("_currentNodeTools",to);let oo=m.get("nodeConfigs")||{};m.set("_currentNodeConfig",oo[E]||{}),N.nodeStart(E);let Xe=Date.now(),pe=this.nodePrompts.get(E);if(!this._invokeAgent){let A=await Promise.resolve().then(()=>(X(),ae));this._invokeAgent=A.invokeAgent}let ro=this._invokeAgent,Ee={},no=C.config?.skills||[];for(let A of no){let B=k(A);if(typeof B?.invokeAgentOptions=="function")try{let $=B.invokeAgentOptions(m.getAll(),{agentType:m.get("agentType"),nodeName:E});$&&typeof $=="object"&&(Ee={...Ee,...$})}catch($){console.warn(`[graph] skill '${A}' invokeAgentOptions threw: ${$.message}`)}}let Qe=async(A,B,$={})=>{let j=ro(A,B,{...Ee,...$,signal:i.signal});return j.catch(()=>{}),i.signal.aborted?j:Promise.race([j,new Promise((Z,K)=>{let L=()=>{setTimeout(()=>{let ee=new Error(`Strategy ignored AbortSignal \u2014 engine deadman fired after ${s}ms`);ee.name="AbortError",K(ee)},s)};i.signal.addEventListener("abort",L,{once:!0})})])},so=async(A={},B={})=>{let $=B.prompt||"";if(pe){let j=this._compiledPrompts.get(E);j||(j=Wo.compile(pe,{noEscape:!0}),this._compiledPrompts.set(E,j));try{$=j(A)}catch(Z){throw console.error(`\u274C Template rendering failed for node '${E}':`,Z.message),new Error(`Template rendering failed: ${Z.message}`,{cause:Z})}}else if(!$)throw new Error(`No prompt template configured for node '${E}' and no prompt provided in options`);return Qe($,{state:m.getAll(),images:B.images||[]},{model:B.model||m.get("model"),workspace:m.get("workspace"),schema:B.schema,...B,signal:i.signal})},et=m.getAll(),io=["state","invokeAgent","_coreInvokeAgent","agent","nodeId","promptTemplate","getPromptTemplate"];for(let A of io)Object.prototype.hasOwnProperty.call(et,A)&&console.warn(`[workflow] node "${E}": state key "${A}" is shadowed by the engine context prop; read it via context.state.get('${A}')`);let tt={...et,state:m,invokeAgent:so,_coreInvokeAgent:Qe,agent:e,nodeId:E,promptTemplate:pe,getPromptTemplate:()=>pe};try{let A=(C.config?.skills||[]).map(L=>h.get(L)).filter(Boolean),B=[...this.middleware,...A],$;B.length>0?$=await this._composeMiddleware(B,E,async()=>C.execute(tt,m),m.getAll(),m):$=await C.execute(tt,m);let j=Date.now()-Xe;if(ue.push({node:E,success:$.success,duration:j,timestamp:new Date().toISOString()}),!$.success){if(i.signal.aborted)return N.step("Workflow stopped externally"),{success:!0,state:m.getAll(),executionLog:ue,stoppedExternally:!0};m.append("errors",{node:E,error:$.error});let L=C.config?.retries||0,ee=`${E}_retries`,fe=m.getAll()[ee]||0;if(fe<L){N.stepInfo(`Retrying (attempt ${fe+1}/${L})`),m.update({[ee]:fe+1,[`${E}_raw`]:$.raw});continue}throw N.nodeFailed(E,$.error,{duration:j}),new Error(`Node '${E}' failed after ${fe} attempts: ${$.error}`)}m.update({[E]:$.output});let Z=this._summarizeNodeOutput(E,$.output);N.nodeComplete(E,{duration:j,details:Z});let K=this.edges.get(E);if(!K)E="END";else if(K.conditional){let L=K.routes(m.getAll());N.route(E,L),E=L}else E=K}catch(A){throw N.isInsideNode&&N.nodeFailed(E,A.message,{duration:Date.now()-Xe}),m.set("failed",!0),m.set("failedAt",E),A}}N.graphComplete();let v={success:!0,state:m.getAll(),executionLog:ue};return e&&typeof e.onComplete=="function"&&await e.onComplete(v),v}finally{if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch(v){console.warn(`[workflow] agent.cleanup() failed: ${v.message}`)}}}};var Ue=Symbol.for("@zibby/agent-workflow.nodes");globalThis[Ue]||(globalThis[Ue]=new Map);var de=globalThis[Ue];function Kt(o,e){de.set(o,e)}function We(o){return de.get(o)}function we(o){return de.has(o)}function Jo(){return Array.from(de.keys())}function He(o){let e=de.get(o);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}Kt("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(()=>(X(),ae))).invokeAgent);let i=e.extraPromptInstructions||"Execute the task based on the current state.",s=Yo(i,t),n=await r(s,{cwd:t.workspace||process.cwd(),model:t.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:n,nodeId:o},raw:typeof n=="string"?n:n.raw}}})});function Yo(o,e){let t=/@([\w.]+)/g,r=new Set,i;for(;(i=t.exec(o))!==null;)r.add(i[1]);if(r.size===0)return o;let s=[],n=new Set;for(let a of r){let l=a.split(".")[0];if(n.has(l))continue;let u=a.split(".").reduce((c,y)=>c?.[y],e);if(u===void 0)continue;let f=typeof u=="string"?u:u?.raw??JSON.stringify(u,null,2),d=a.replace(/_/g," ").replace(/\b\w/g,c=>c.toUpperCase());s.push(`## ${d}
|
|
43
|
+
${f}`),a.includes(".")||n.add(l)}return s.length===0?o:`${o}
|
|
44
44
|
|
|
45
45
|
---
|
|
46
46
|
# Referenced Context
|
|
47
47
|
|
|
48
48
|
${s.join(`
|
|
49
49
|
|
|
50
|
-
`)}`}ie();F();var
|
|
51
|
-
`)}function
|
|
52
|
-
`)}function
|
|
53
|
-
`)}function
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function
|
|
57
|
-
`).map((f,
|
|
58
|
-
`);
|
|
59
|
-
`)}function
|
|
50
|
+
`)}`}ie();F();var Se={};function Ye(o,e){if(Array.isArray(e))return Je(e);let t=Se[o];return!t||t.length===0?null:Je(t)}function Je(o){if(!Array.isArray(o)||o.length===0)return null;let e=[],t={},r=[];for(let i of o){let s=q(i);if(!s){I.warn(`[workflow] unknown skill "${i}" \u2014 skipping`);continue}r.push(i);for(let n of s.tools||[])e.push({name:n.name,description:n.description,input_schema:n.input_schema||{type:"object",properties:{}}});if(!t[s.serverName])if(typeof s.resolve=="function"){let n=s.resolve();n&&(t[s.serverName]={...n,toolPrefix:i})}else{let n={};for(let a of s.envKeys||[]){let l=process.env[a];l&&(n[a]=l)}t[s.serverName]={command:s.command,args:[...s.args||[]],env:n,toolPrefix:i}}}return r.length===0?null:{toolIds:r,claudeTools:e,mcpServers:t}}F();function zo(o,e={}){let{nodes:t,edges:r,nodeConfigs:i={}}=o;if(!Array.isArray(t)||t.length===0)throw new D("Graph must have at least one node");if(!Array.isArray(r))throw new D("Graph edges must be an array");let s=new Q(e);e.stateSchema&&s.setStateSchema(e.stateSchema);let n=new Set,a=new Map,l={};for(let c of t){let y=_e(c);a.set(c.id,{...c,resolvedType:y}),y==="decision"&&n.add(c.id)}for(let[c,y]of a){if(n.has(c))continue;let g=y.resolvedType,S=i[c]||{},b=Ye(g,S.tools);b&&(l[c]=b);let _={};S.prompt&&(_.prompt=S.prompt);let m=we(g);if(I.debug(`[workflow] compiler: node "${c}" type="${g}" registered=${m}`),S.customCode&&!m)s.addNode(c,Vt(c,S.customCode,S),_),s.setNodeType(c,g);else if(m){let h=We(g);h.factory?s.addNode(c,h.create(c,{...S,resolvedTools:b}),_):s.addNode(c,h,_),s.setNodeType(c,g)}else if(S.executeCode)s.addNode(c,Vt(c,S.executeCode,S),_),s.setNodeType(c,g);else throw new D(`Unknown node type "${g}" for node "${c}". Did you forget to register it?`)}s.resolvedToolsMap=l;let u=new Set;for(let c of r)n.has(c.target)||u.add(c.target);let f=t.find(c=>!n.has(c.id)&&!u.has(c.id));if(!f)throw new D("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(f.id);let d=Vo(r,"source");for(let c of r)if(!n.has(c.source))if(n.has(c.target)){let y=c.target,g=d.get(y)||[];if(g.length===0)throw new D(`Decision node "${y}" has no outgoing edges`);let S=qo(y,g,n);s.addConditionalEdges(c.source,S)}else s.addEdge(c.source,c.target);return s}function Zo(o){let e=[];if(!o||typeof o!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(o.nodes)||o.nodes.length===0)&&e.push("Graph must have at least one node"),Array.isArray(o.edges)||e.push("Graph edges must be an array"),e.length>0)return{valid:!1,errors:e};let t=o.nodeConfigs||{};for(let a of o.nodes){let l=_e(a);if(l==="decision"||we(l))continue;let u=t[a.id]||{};u.customCode||u.executeCode||e.push(`Unknown node type "${l}" for node "${a.id}". Register it or provide customCode/executeCode.`)}let r=new Set(o.nodes.map(a=>a.id));for(let a of o.edges)r.has(a.source)||e.push(`Edge references unknown source node "${a.source}"`),r.has(a.target)||e.push(`Edge references unknown target node "${a.target}"`);let i=new Set(o.nodes.filter(a=>_e(a)==="decision").map(a=>a.id)),s=new Set;for(let a of o.edges)i.has(a.target)||s.add(a.target);let n=o.nodes.filter(a=>!i.has(a.id)&&!s.has(a.id));n.length===0?e.push("No entry point found (every node has incoming edges)"):n.length>1&&e.push(`Multiple entry points found: ${n.map(a=>a.id).join(", ")}`);for(let a of i){let l=o.edges.filter(f=>f.source===a);l.length===0&&e.push(`Decision node "${a}" has no outgoing edges`),l.some(f=>f.data?.conditionalCode||f.conditionalCode)||e.push(`Decision node "${a}" outgoing edges have no conditionalCode`)}return{valid:e.length===0,errors:e}}function Ko(o){return!o||!Array.isArray(o.nodes)?[]:o.nodes.filter(e=>_e(e)!=="decision").map(e=>e.id)}function _e(o){let e=o.data?.nodeType||o.data?.type||o.type;return e==="workflowNode"||e==="custom"||e==="default"?o.id:e}function Vo(o,e){let t=new Map;for(let r of o){let i=r[e];t.has(i)||t.set(i,[]),t.get(i).push(r)}return t}function qo(o,e,t){let r=e.find(a=>a.data?.conditionalCode||a.conditionalCode);if(!r)throw new D(`Decision node "${o}" has no conditionalCode on its outgoing edges`);let i=r.data?.conditionalCode||r.conditionalCode,s=new Set(e.map(a=>a.target).filter(a=>!t.has(a))),n;try{let l=new Function(`return (${i})`)();n=u=>{let f=l(u);return s.has(f)||I.warn(`[workflow] conditional route from "${o}" returned "${f}" which is not in valid targets: ${[...s].join(", ")}`),f}}catch(a){throw new D(`Failed to compile conditionalCode for "${o}": ${a.message}`)}return n}function Vt(o,e,t={}){let r;try{r=new Function("invokeAgent","require","console",`return (${e})`)}catch(n){throw new D(`Failed to compile customCode for node "${o}": ${n.message}`)}let i=r(async(...n)=>{let{invokeAgent:a}=await Promise.resolve().then(()=>(X(),ae));return a(...n)},typeof Ie<"u"?Ie:void 0,console),s=null;return t.outputSchema&&(s=t.outputSchema.jsonSchema||t.outputSchema),{name:o,_isCustomCode:!0,outputSchema:s,execute:async n=>{try{let a=await i(n);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 D=class extends Error{constructor(e){super(e),this.name="CompilationError"}};ie();var ze=/^[a-z][a-z0-9_]{0,40}$/;function Xo(o){if(o==null)return[];if(!Array.isArray(o))return["stores must be an array of { name, description } objects"];let e=[],t=new Map;return o.forEach((r,i)=>{if(r==null||typeof r!="object"||Array.isArray(r)){e.push(`stores[${i}] must be an object { name, description }`);return}let{name:s}=r;if(typeof s!="string"||s.length===0){e.push(`stores[${i}] is missing a string "name"`);return}ze.test(s)||e.push(`stores[${i}] name "${s}" is invalid \u2014 must match ${ze} (lowercase letter first, then up to 40 of [a-z0-9_])`),t.has(s)?e.push(`stores[${i}] duplicate store name "${s}" (also at index ${t.get(s)}) \u2014 store names must be unique within a workflow`):t.set(s,i)}),e}xe();X();function Qo(o,e={}){let{nodes:t,edges:r,nodeConfigs:i={}}=o,s=new Set,n=[],a=new Map;for(let b of t){let _=b.data?.nodeType||b.type;a.set(b.id,_),_==="decision"?s.add(b.id):n.push({id:b.id,nodeType:_,label:b.data?.label||b.id})}let l=n.some(b=>{let _=i[b.id]||{};return!_.customCode&&!_.executeCode}),{toolsPerNode:u,toolIdsByVar:f}=ar(n,i),{simpleEdges:d,conditionalEdges:c}=cr(r,s),y=lr(n,r,s),g=[],S=e.workflowType||"workflow";return g.push(tr(e)),g.push(or(S,{usesRegisteredNodes:l})),g.push(rr(f)),g.push(nr(S)),g.push(sr(n,i)),g.push(ir(n,y,d,c,u,S)),g.filter(Boolean).join(`
|
|
51
|
+
`)}function er(o){let e={};for(let[t,r]of Object.entries(o)){let{tools:i,...s}=r;Object.keys(s).length>0&&(e[t]=s)}return e}function tr(o){let e=o.workflowType||"workflow";return["// Generated workflow",`// ${o.projectId?`Project: ${o.projectId} | `:""}Type: ${e} | Version: ${o.version??0}`,`// Downloaded: ${new Date().toISOString()}`,""].join(`
|
|
52
|
+
`)}function or(o,{usesRegisteredNodes:e=!0}={}){let t=["import { WorkflowGraph, invokeAgent, getResolvedToolDefinitions } from '@zibby/agent-workflow';"];return e&&t.push("// import './register-nodes.js'; // register custom node types here"),t.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';",""),t.join(`
|
|
53
|
+
`)}function rr(o){if(o.size===0)return"";let e=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];for(let[t,r]of o)e.push(`const ${t} = getResolvedToolDefinitions(${JSON.stringify(r)}); // ${r.join(", ")}`);return e.push(""),e.join(`
|
|
54
|
+
`)}function nr(o){return["// \u2500\u2500 Node Configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${o}.config.json');`,"const nodeConfigs = existsSync(configPath) ? JSON.parse(readFileSync(configPath, 'utf-8')) : {};",""].join(`
|
|
55
|
+
`)}function sr(o,e){let t=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",""];for(let r of o){let i=qt(r.id),s=e[r.id]?.customCode;if(s)t.push(`// @custom \u2014 modified from default "${r.nodeType}" template`),t.push(`const ${i}_execute = ${s};`);else{let n=He(r.nodeType);n?(t.push(`// Default "${r.nodeType}" implementation`),t.push(`const ${i}_execute = ${n};`)):(t.push(`// No template for "${r.nodeType}" \u2014 passthrough`),t.push(`const ${i}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}t.push("")}return t.join(`
|
|
56
|
+
`)}function ir(o,e,t,r,i,s){let n=["// \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"];n.push("export function buildGraph(options = {}) {"),n.push(" const graph = new WorkflowGraph(options);",""),n.push(" // Nodes");for(let l of o){let u=qt(l.id);n.push(` graph.addNode('${l.id}', { name: '${l.id}', execute: ${u}_execute });`),n.push(` graph.setNodeType('${l.id}', '${l.nodeType}');`)}n.push("",` graph.setEntryPoint('${e}');`,""),(t.length>0||r.length>0)&&n.push(" // Edges");for(let l of t)n.push(` graph.addEdge('${l.source}', '${l.target}');`);for(let l of r){let u=l.code.split(`
|
|
57
|
+
`).map((f,d)=>d===0?f:` ${f}`).join(`
|
|
58
|
+
`);n.push(` graph.addConditionalEdges('${l.source}', ${u});`)}let a=[];for(let l of o){let u=i.get(l.id);u&&a.push(` '${l.id}': ${u},`)}return a.length>0&&n.push(""," graph.resolvedToolsMap = {",...a," };"),n.push(""," return graph;","}",""),n.push("export { nodeConfigs };",""),n.join(`
|
|
59
|
+
`)}function ar(o,e){let t=new Map,r=new Map;for(let i of o){let s=e[i.id]?.tools,n;if(Array.isArray(s)&&s.length>0)n=[...s].sort();else{let a=Se[i.nodeType];a?.length>0&&(n=[...a].sort())}if(n){let a=`${n.map(l=>l.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;t.set(i.id,a),r.has(a)||r.set(a,n)}}return{toolsPerNode:t,toolIdsByVar:r}}function cr(o,e){let t=[],r=[],i=new Map,s=new Set;for(let n of o)i.has(n.source)||i.set(n.source,[]),i.get(n.source).push(n);for(let n of o)if(!e.has(n.source))if(e.has(n.target)){if(s.has(n.target))continue;s.add(n.target);let l=(i.get(n.target)||[]).find(u=>u.data?.conditionalCode||u.conditionalCode);l&&r.push({source:n.source,code:l.data?.conditionalCode||l.conditionalCode})}else t.push({source:n.source,target:n.target});return{simpleEdges:t,conditionalEdges:r}}function lr(o,e,t){let r=new Set;for(let s of e)t.has(s.target)||r.add(s.target);let i=o.find(s=>!r.has(s.id));return i?i.id:o[0]?.id}function qt(o){return o.replace(/[^a-zA-Z0-9]/g,"_")}F();var dr=`## Composing deployed agents (wrapper over marketplace bricks)
|
|
60
|
+
|
|
61
|
+
**Red line: wrapper only.** Marketplace agents are shared LEGO bricks \u2014 NEVER
|
|
62
|
+
modify a brick template's source and never rebuild its logic from scratch.
|
|
63
|
+
The composition is a small project-private WRAPPER workflow that dispatches
|
|
64
|
+
already-DEPLOYED bricks as sub-workflows. A forked/edited brick falls off the
|
|
65
|
+
upgrade path.
|
|
66
|
+
|
|
67
|
+
**Reuse policy \u2014 ask, never silently choose.** If a needed brick is already
|
|
68
|
+
deployed in the project, the user decides: reuse that instance (runs + config
|
|
69
|
+
are shared with its standalone use) or deploy a dedicated instance under a
|
|
70
|
+
custom name (config isolation).
|
|
71
|
+
|
|
72
|
+
**Sub-workflow node.** Declare a child dispatch by giving addNode a config
|
|
73
|
+
with a \`workflow:\` field \u2014 the DEPLOYED slug in the SAME project (the row's
|
|
74
|
+
workflowType, not the marketplace slug, when they differ):
|
|
75
|
+
|
|
76
|
+
graph.addNode('review', {
|
|
77
|
+
workflow: 'gitlab-code-review', // deployed slug
|
|
78
|
+
input: (state) => ({ projectId: state.projectId, mrIid: state.mrIid }),
|
|
79
|
+
timeoutMs: 15 * 60 * 1000,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
The engine runs the child in-process (same worker) when possible and the
|
|
83
|
+
child's FINAL state \u2014 whichever End it exited \u2014 lands at \`state[nodeName]\`.
|
|
84
|
+
Options: \`workflow\` (required), \`input\` (object or \`(state) => object\`),
|
|
85
|
+
\`output\` (dot-path or \`(finalState) => any\` to extract just what's needed),
|
|
86
|
+
\`async: true\` (fire-and-forget \u2192 \`{ jobId }\`), \`timeoutMs\`, \`retries\`.
|
|
87
|
+
For PARALLEL fan-out call \`dispatchSubgraph(slug, { input })\` (exported by
|
|
88
|
+
@zibby/agent-workflow) inside one custom execute node with
|
|
89
|
+
\`Promise.allSettled\` \u2014 one brick failing must not kill its siblings.
|
|
90
|
+
|
|
91
|
+
**Chain conditions are EXPLICIT decision nodes.** Bricks are full multi-exit
|
|
92
|
+
graphs, so branch on the child's RETURNED state between dispatches \u2014 and model
|
|
93
|
+
the branch so the graph SHOWS it: a router node
|
|
94
|
+
(\`graph.addNode('<id>', { description })\` \u2014 no execute/prompt/outputSchema;
|
|
95
|
+
renders as the Condition diamond) routed with
|
|
96
|
+
\`graph.addConditionalEdges('<id>', routeFn, { labels })\`. Never an unlabeled
|
|
97
|
+
dispatch\u2192End edge. Note the child's own node outputs are NESTED
|
|
98
|
+
(\`state.review.review.posted\` = the child's \`review\` node output), e.g. only
|
|
99
|
+
meter when \`state.review?.review?.posted === true && state.review?.trigger
|
|
100
|
+
!== 'comment_reply'\`.
|
|
101
|
+
|
|
102
|
+
**Input mapping is the wrapper's job \u2014 use the brick's CANONICAL structured
|
|
103
|
+
fields.** In-process children run the brick's graph directly and SKIP any
|
|
104
|
+
convenience normalization its class run() does on cold starts (e.g.
|
|
105
|
+
gitlab-code-review parses mrUrl \u2192 projectId+mrIid only on cold runs \u2014 pass
|
|
106
|
+
projectId/mrIid yourself).
|
|
107
|
+
|
|
108
|
+
**Credentials/config: children use their OWN row's env** (engine \u22650.4.32 +
|
|
109
|
+
matching backend). A brick's per-workflow env (Env tab / envSecret) applies to
|
|
110
|
+
its in-process wrapped runs too \u2014 the child's value wins, the wrapper's env is
|
|
111
|
+
only the fallback for keys the brick doesn't define. So the wrapper needs ZERO
|
|
112
|
+
credential duplication: leave each brick's creds (e.g.
|
|
113
|
+
CLAUDE_CODE_OAUTH_TOKEN) on the brick itself and give the wrapper none.
|
|
114
|
+
(Env-carrying children serialize when dispatched in parallel; env-less ones
|
|
115
|
+
keep full parallelism. On older engines children inherit only the wrapper env
|
|
116
|
+
\u2014 symptom: authentication_failed inside the child.) A brick's saved per-node
|
|
117
|
+
custom prompts (nodeConfigOverrides.<node>.extraPromptInstructions) apply
|
|
118
|
+
in-process since \u22650.4.30, and its stores bindings ride along since \u22650.4.32.
|
|
119
|
+
|
|
120
|
+
**Triggers \u2014 INHERIT the entry brick's events, read not invent.** The
|
|
121
|
+
wrapper's trigger is AGENT-DRIVEN, never hardcoded: for webhook compositions
|
|
122
|
+
the wrapper's workflow.json \`triggers.events\` is a verbatim COPY of whatever
|
|
123
|
+
the ENTRY brick declares \u2014 read it from the brick's deployed row (or its
|
|
124
|
+
template workflow.json) and paste the exact array. The platform then
|
|
125
|
+
automatically SUPPRESSES the wrapped members' own subscriptions (any workflow
|
|
126
|
+
listed in a deployed wrapper's composedOf stops receiving standalone webhook
|
|
127
|
+
events), so the same event never double-fires a brick inside AND outside the
|
|
128
|
+
wrapper. Cron / manual / chat-triggered compositions need nothing special.`;export{Ne as AgentStrategy,Ae as CI_ENV_VARS,dr as COMPOSE_KNOWLEDGE,D as CompilationError,le as ContextLoader,se as DEFAULT_OUTPUT_BASE,go as EVENTS_FILE,Q as Graph,Se as NODE_DEFAULT_TOOLS,mo as NO_INTEGRATION_TOGGLEABLE_SKILL_IDS,M as Node,oe as OutputParser,ho as RAW_OUTPUT_FILE,fo as RESULT_FILE,$e as SESSIONS_DIR,U as SESSION_INFO_FILE,ft as SKILLS,ke as STOP_REQUEST_FILE,ze as STORE_NAME_REGEX,lo as SchemaTypes,ge as Timeline,pt as WORKFLOW_GRAPH_LOG_MARKER_PREFIX,Q as WorkflowGraph,te as WorkflowState,Jt as clearInheritedSessionEnvForFreshRun,wt as clearSkills,zo as compileGraph,Me as dispatchSubgraph,Ko as extractSteps,er as generateNodeConfigsJson,Qo as generateWorkflowCode,zt as generateWorkflowSessionId,Ce as getAgentStrategy,mt as getAllSkills,We as getNodeImpl,He as getNodeTemplate,Je as getResolvedToolDefinitions,q as getSkill,we as hasNode,gt as hasSkill,It as invokeAgent,Jo as listNodeTypes,yt as listSkillIds,Et as listStrategies,Ht as readPinnedSessionPathFromEnv,Kt as registerNode,ht as registerSkill,_t as registerStrategy,Ye as resolveNodeTools,Zt as resolveWorkflowSession,uo as setLogger,Wt as shouldTrustInheritedSessionEnv,Yt as syncProcessEnvToSession,N as timeline,Zo as validateGraphConfig,Xo as validateStoreDefs};
|