Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(workflows): complete server-native automation parity

Rahmancb722a7c7542
diff --git a/README.md b/README.md
index e2b8507d..7e6eb776 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
| **Understand a project** | Project context, trusted skills and task-specific tool discovery. |
| **Do the work** | Real PTY, bounded file tools, service controls and explicit approvals. |
| **Pick up where you left off** | Durable sessions, local memory, workflow evidence and agent handoffs. |
-| **Build server-native workflows** | Visual n8n-like workflow graphs, reusable scripts/subflows, per-node logs, dynamic project/folder bindings, and automatic private learning from successful sessions. |
+| **Build server-native workflows** | Server-native n8n-core workflow parity: schedule/webhook triggers, branching/loops/subflows, retries/error paths, versions/history, private variables, integrations, per-node logs, and automatic private learning. |
**One runtime, three ways in:** use desktop/mobile windows, stay in your terminal, or connect an MCP client.
Code, image/video tools, a browser and native credential setup live beside your operational tools.
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.ts
index 6d9e2625..79ae9308 100644
--- a/app/api/v1/workflows/route.ts
+++ b/app/api/v1/workflows/route.ts
@@ -3,55 +3,41 @@ import { getSessionContext } from "@/lib/auth/require-session";
import { roleAtLeast } from "@/lib/auth/roles";
import { createAgentSession } from "@/lib/agent/session-store";
import { readSetupJson } from "@/lib/infra/setup-http";
+import { rateLimited } from "@/lib/host/limits-api";
import { maxScope } from "@/lib/mcp/scope";
import { TOOLS_BY_NAME } from "@/lib/mcp/tools";
-import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph } from "@/lib/workflow/graph-store";
+import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph, workflowGraphOwner } from "@/lib/workflow/graph-store";
import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";
+import { listWorkflowGraphRuns } from "@/lib/workflow/graph-run-store";
+import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workflow/graph-version-store";
import { resolveWorkflowGraphNodeTarget } from "@/lib/workflow/graph-target";
-
-export const runtime = "nodejs";
-export const dynamic = "force-dynamic";
-const headers = { "Cache-Control": "no-store, private" };
-const fail = (error: unknown, status = 400) => NextResponse.json({ error: error instanceof Error ? error.message.slice(0, 500) : "workflow request failed" }, { status, headers });
-
-async function auth(minimum: "viewer" | "operator" | "owner" = "viewer") {
- const context = await getSessionContext();
- if (!context?.session.device_id) return null;
- if (!roleAtLeast(context.role, minimum)) return null;
- return { context, principal: `web:${context.session.device_id}` };
-}
-
-export async function GET(req: NextRequest) {
- const session = await auth("viewer"); if (!session) return fail("unauthorized", 401);
- try {
- const q = req.nextUrl.searchParams;
- if (q.has("run_id")) return NextResponse.json(await workflowGraphRunStatus(session.principal, q.get("run_id")!, Number(q.get("wait_ms")) || 0), { headers });
- if (q.has("graph_id") && q.has("node_id") && q.get("resolve") === "target") {
- const graph = await getWorkflowGraph(session.principal, q.get("graph_id")!); if (!graph) throw new Error("workflow graph not found");
- return NextResponse.json(await resolveWorkflowGraphNodeTarget(graph, q.get("node_id")!), { headers });
- }
- if (q.has("graph_id")) {
- const graph = await getWorkflowGraph(session.principal, q.get("graph_id")!); if (!graph) return fail("workflow graph not found", 404);
- return NextResponse.json({ graph }, { headers });
- }
- return NextResponse.json({ graphs: await listWorkflowGraphs(session.principal) }, { headers });
- } catch (error) { return fail(error); }
-}
-
-export async function POST(req: NextRequest) {
- const session = await auth("operator"); if (!session) return fail("operator_required", 403);
- try {
- const body = await readSetupJson(req), action = typeof body.action === "string" ? body.action : "";
- if (action === "create") return NextResponse.json({ graph: await createWorkflowGraph(session.principal, body.graph) }, { headers });
- if (action === "update") return NextResponse.json({ graph: await updateWorkflowGraph(session.principal, String(body.graph_id ?? ""), String(body.expected_revision ?? ""), body.graph) }, { headers });
- if (action === "delete") return NextResponse.json(await deleteWorkflowGraph(session.principal, String(body.graph_id ?? ""), String(body.expected_revision ?? "")), { headers });
- if (action === "clone") return NextResponse.json({ graph: await cloneWorkflowGraph(session.principal, String(body.graph_id ?? "")) }, { headers });
- if (action === "run") {
- const graph = await getWorkflowGraph(session.principal, String(body.graph_id ?? "")); if (!graph) throw new Error("workflow graph not found");
- const agentSession = await createAgentSession(session.principal, "cli", { title: `Workflow: ${graph.name}`, titleSource: "auto" });
- const context = { principal: session.principal, actor: session.principal, sessionId: agentSession.id, scope: maxScope() } as const;
- return NextResponse.json(await startWorkflowGraph(graph, body.input ?? {}, String(body.idempotency_key ?? `${Date.now()}`), context, (name) => TOOLS_BY_NAME.get(name)), { headers });
- }
- throw new Error("unknown workflow action");
- } catch (error) { return fail(error); }
-}
+import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";
+import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
+import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";
+import { suggestWorkflowGraph } from "@/lib/workflow/ai-assist";
+export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};
+const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});
+async function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}
+function definition(graph:NonNullable<Awaited<ReturnType<typeof getWorkflowGraph>>>){const{revision:_r,createdAt:_c,updatedAt:_u,version:_v,...rest}=graph;return rest;}
+export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=q.has("variables")?"operator":"viewer",session=await auth(minimum);if(!session)return fail("unauthorized",401);try{
+ if(q.get("catalog")==="1")return NextResponse.json({nodes:workflowNodeCatalog(q.get("q")??"")},{headers});
+ if(q.get("templates")==="1")return NextResponse.json({templates:workflowTemplates()},{headers});
+ if(q.get("variables")==="1")return NextResponse.json({variables:await listWorkflowVariables(session.principal)},{headers});
+ if(q.get("runs")==="1")return NextResponse.json(await listWorkflowGraphRuns(workflowGraphOwner(session.principal),{graphId:q.get("graph_id")||undefined,state:(q.get("state")||undefined) as never,limit:Number(q.get("limit"))||30,offset:Number(q.get("offset"))||0}),{headers});
+ if(q.has("versions")){const graphId=q.get("versions")!;return NextResponse.json({versions:await listWorkflowGraphVersions(workflowGraphOwner(session.principal),graphId)},{headers});}
+ if(q.has("run_id"))return NextResponse.json(await workflowGraphRunStatus(session.principal,q.get("run_id")!,Number(q.get("wait_ms"))||0),{headers});
+ if(q.has("graph_id")&&q.has("node_id")&&q.get("resolve")==="target"){const graph=await getWorkflowGraph(session.principal,q.get("graph_id")!);if(!graph)throw new Error("workflow graph not found");return NextResponse.json(await resolveWorkflowGraphNodeTarget(graph,q.get("node_id")!),{headers});}
+ if(q.has("graph_id")){const graph=await getWorkflowGraph(session.principal,q.get("graph_id")!);if(!graph)return fail("workflow graph not found",404);return NextResponse.json({graph},{headers});}
+ return NextResponse.json({graphs:await listWorkflowGraphs(session.principal)},{headers});
+ }catch(error){return fail(error);}}
+export async function POST(req:NextRequest){const session=await auth("operator");if(!session)return fail("operator_required",403);try{const body=await readSetupJson(req),action=typeof body.action==="string"?body.action:"";if(rateLimited(`workflow:${action}:${session.context.session.device_id}`,action==="run"?60:30,60_000))return fail("rate_limited",429);
+ if(action==="create")return NextResponse.json({graph:await createWorkflowGraph(session.principal,body.graph)},{headers});
+ if(action==="update")return NextResponse.json({graph:await updateWorkflowGraph(session.principal,String(body.graph_id??""),String(body.expected_revision??""),body.graph)},{headers});
+ if(action==="delete")return NextResponse.json(await deleteWorkflowGraph(session.principal,String(body.graph_id??""),String(body.expected_revision??"")),{headers});
+ if(action==="clone")return NextResponse.json({graph:await cloneWorkflowGraph(session.principal,String(body.graph_id??""))},{headers});
+ if(action==="create_from_template"){const row=workflowTemplate(String(body.template_id??""));if(!row)throw new Error("workflow template not found");return NextResponse.json({graph:await createWorkflowGraph(session.principal,row.definition,"template")},{headers});}
+ if(action==="restore_version"){const id=String(body.graph_id??""),snapshot=await readWorkflowGraphVersion(workflowGraphOwner(session.principal),id,String(body.revision??""));if(!snapshot)throw new Error("workflow version not found");return NextResponse.json({graph:await updateWorkflowGraph(session.principal,id,String(body.expected_revision??""),definition(snapshot.graph),"restore")},{headers});}
+ if(action==="variable_set"||action==="variable_delete"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json(action==="variable_set"?await setWorkflowVariable(session.principal,String(body.key??""),body.value,body.secret===true):await deleteWorkflowVariable(session.principal,String(body.key??"")),{headers});}
+ if(action==="ai_suggest"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json({definition:await suggestWorkflowGraph(String(body.prompt??""))},{headers});}
+ if(action==="run"){const graph=await getWorkflowGraph(session.principal,String(body.graph_id??""));if(!graph)throw new Error("workflow graph not found");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope()} as const;return NextResponse.json(await startWorkflowGraph(graph,body.input??{},String(body.idempotency_key??`${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}
+ throw new Error("unknown workflow action");}catch(error){return fail(error);}}
diff --git a/app/api/v1/workflows/webhook/[...hook]/route.ts b/app/api/v1/workflows/webhook/[...hook]/route.ts
new file mode 100644
index 00000000..f80c9900
--- /dev/null
+++ b/app/api/v1/workflows/webhook/[...hook]/route.ts
@@ -0,0 +1,14 @@
+import { timingSafeEqual } from "node:crypto";
+import { NextRequest, NextResponse } from "next/server";
+import { rateLimited } from "@/lib/host/limits-api";
+import { createAgentSession } from "@/lib/agent/session-store";
+import { maxScope } from "@/lib/mcp/scope";
+import { findActiveWebhookSource } from "@/lib/workflow/graph-triggers";
+import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";
+import { workflowVariableValues } from "@/lib/workflow/variables";
+export const runtime="nodejs";export const dynamic="force-dynamic";
+function same(a:string,b:string){const x=Buffer.from(a),y=Buffer.from(b);return x.length===y.length&&timingSafeEqual(x,y);}
+async function payload(req:NextRequest){const length=Number(req.headers.get("content-length")||0);if(length>64*1024)throw new Error("webhook body too large");let body:unknown=null;if(!["GET","HEAD"].includes(req.method)){const text=await req.text();if(Buffer.byteLength(text)>64*1024)throw new Error("webhook body too large");try{body=text?JSON.parse(text):null;}catch{body=text;}}return{method:req.method,query:Object.fromEntries(req.nextUrl.searchParams),headers:{"content-type":req.headers.get("content-type")||undefined,"user-agent":req.headers.get("user-agent")||undefined,"x-request-id":req.headers.get("x-request-id")||undefined},body};}
+async function handle(req:NextRequest,ctx:{params:Promise<{hook:string[]}>}){try{const {hook}=await ctx.params;if(hook.length!==2)return NextResponse.json({error:"webhook_not_found"},{status:404});const source=await findActiveWebhookSource(hook[0]!,hook[1]!);if(!source)return NextResponse.json({error:"webhook_not_found"},{status:404});const methods=Array.isArray(source.node.config.methods)?source.node.config.methods.map(String):["POST"];if(!methods.includes(req.method))return NextResponse.json({error:"method_not_allowed"},{status:405,headers:{Allow:methods.join(", ")}});if(rateLimited(`workflow-webhook:${source.graph.id}:${source.node.id}`,120,60_000))return NextResponse.json({error:"rate_limited"},{status:429});const authVar=typeof source.node.config.authVariable==="string"?source.node.config.authVariable:"";if(authVar){const vars=await workflowVariableValues(source.principal),expected=vars[authVar];if(typeof expected!=="string")return NextResponse.json({error:"webhook_auth_not_configured"},{status:503});const raw=req.headers.get("authorization")?.replace(/^Bearer\s+/i,"")??req.headers.get("x-webhook-token")??"";if(!same(raw,expected))return NextResponse.json({error:"unauthorized"},{status:401});}
+ const input=await payload(req),session=await createAgentSession(source.principal,"cli",{title:`Webhook: ${source.graph.name}`,titleSource:"auto"}),{TOOLS_BY_NAME}=await import("@/lib/mcp/tools"),key=(req.headers.get("idempotency-key")||`webhook-${crypto.randomUUID()}`).slice(0,128),context={principal:source.principal,actor:source.principal,sessionId:session.id,scope:maxScope()} as const;const started=await startWorkflowGraph(source.graph,input,key,context,(name)=>TOOLS_BY_NAME.get(name),source.principal,{type:"webhook",nodeId:source.node.id,receivedAt:new Date().toISOString()});if(source.node.config.responseMode!=="lastNode")return NextResponse.json({runId:started.id,state:started.state},{status:202});const done=await workflowGraphRunStatus(source.principal,started.id,25_000),output=[...done.nodes].reverse().find((node)=>node.type==="output"&&node.output!==undefined)?.output;return NextResponse.json({runId:done.id,state:done.state,output},{status:done.state==="failed"?500:200});}catch(error){return NextResponse.json({error:error instanceof Error?error.message.slice(0,300):"webhook_failed"},{status:400});}}
+export const GET=handle;export const POST=handle;export const PUT=handle;export const PATCH=handle;export const DELETE=handle;
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 305cb2e9..48c18b7a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -291,4 +291,4 @@ Each MSO connector/server scope owns its own Page app catalog. Core MSO Page cod
## Server-native workflow graph
-MSO now has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMIC primitives. The graph is the automation-topology SSOT; canonical project paths are resolved dynamically from the project registry and are not copied into portable workflow definitions. Graph definitions/runs are isolated by authenticated principal, while tools/scripts/subflows retain normal capability scope, audit, connection and project guards. See [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md).
+MSO has a Workflow Graph v2 layer above the existing automation/lifecycle/RASMIC primitives. It is the automation-topology SSOT and provides server-side schedule/webhook triggers, bounded branching/loops/subflows, retry/error paths, versioned definitions, private variables and persisted execution history. Canonical project paths resolve dynamically and credentials remain in integration authorities rather than portable graph definitions. Graph definitions/versions/runs/variables are isolated by authenticated principal, while tools/scripts/subflows retain normal capability scope, audit, connection and project guards. See [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md).
diff --git a/docs/AUTOMATION-FLOWS.md b/docs/AUTOMATION-FLOWS.md
index 5193f9e5..4f46a1bc 100644
--- a/docs/AUTOMATION-FLOWS.md
+++ b/docs/AUTOMATION-FLOWS.md
@@ -142,4 +142,4 @@ workflow-store model; a multi-writer database is not introduced.
## Workflow Graph v2
-For visual, branching, mixed-node workflows, see [WORKFLOW-GRAPH.md](./WORKFLOW-GRAPH.md). Graph v2 is private per authenticated principal, has per-node logs/error identity, resolves project/folder locations dynamically, and coexists with the linear flow format documented above. `workflow_start` checks matching private graphs before learned recipes; successful `workflow_finish` seeds private draft graphs automatically.
+For visual, branching, mixed-node workflows, see [WORKFLOW-GRAPH.md](./WORKFLOW-GRAPH.md). Graph v2 is private per authenticated principal and now covers server schedule/webhook triggers, switch/merge/batch/loop/wait/sub-workflow control, retry/error routing, version/history rollback, private variables, integration references and per-node receipts while resolving project/folder locations dynamically. It coexists with the linear flow format documented above. `workflow_start` checks matching private graphs before learned recipes; successful `workflow_finish` seeds private draft graphs automatically.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index e148c6af..4a3ce250 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `workflows` complete server-native automation parity
- `workflows` add server-native workflow graph
**Fixed**
diff --git a/docs/README.md b/docs/README.md
index 12a948d9..9c30b067 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -35,7 +35,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page |
| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs |
| [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits |
-| [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2, visual editor, node runtime/logging, dynamic project/folder bindings and automatic learning |
+| [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2 with n8n-core triggers/flow control, versions/history, variables, integrations, visual execution and automatic learning |
| [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting |
| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |
| [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary |
diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.md
index 5700d408..10d5a193 100644
--- a/docs/SLICE-CATALOG.md
+++ b/docs/SLICE-CATALOG.md
@@ -35,7 +35,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c
| `reel-editor` | Video/reel timeline editor |
| `shell-settings` | Shared shell settings UI primitives |
| `system-monitor` | Live metrics/processes plus service inventory/logs/allowlisted lifecycle and cache-only package updates |
-| `workflows` | Server-native visual workflow graph editor, private runs and node-level logs |
+| `workflows` | Server-native automation editor with schedule/webhook triggers, flow control, private history/versions/variables and node-level logs |
## AppShell feature directories (10)
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 67f8618f..699b796e 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -1,90 +1,178 @@
-# Workflow Graph v2
+# Workflow Graph v2 — server-native automation
-MSO Workflow Graph v2 is the private, server-native automation layer for reusable workflows. It extends the existing linear project flow engine rather than replacing it.
+MSO Workflow Graph v2 is MSO's private, server-native visual automation layer. It provides the core self-hosted workflow capabilities normally expected from n8n while keeping MSO's project registry, Linux filesystem, Skills, project knowledge, agents, integrations and capability permissions as the execution authorities.
-## SSOT boundaries
+It is additive: existing deterministic project flows, RASMIC scripts and learned workflow memory remain supported.
-- **MSO Workflow Graph** owns automation topology, runtime node state, execution bindings and reusable workflow definitions.
-- **MSO project registry** resolves canonical projects and real server paths at runtime. Graph definitions store project ids/hints, not installation-specific absolute paths.
-- **Git** remains the code source of truth.
-- **Project `.mso/KNOWLEDGE.md` / repo memory** remain project knowledge sources.
-- External delivery systems may remain delivery/task SSOT when connected; MSO does not copy their task state into graph definitions.
-- No separate organizational-memory product is required for workflow execution.
+## Authority and storage
-## Privacy and portability
+- **Workflow Graph** owns automation topology, triggers, flow control, node configuration, execution history and graph versions.
+- **Project registry** resolves canonical projects and real server paths at runtime. Portable graph definitions store ids/hints, never installation-specific absolute paths.
+- **Integrations** own credentials and provider connections. Graphs store connection references only.
+- **Private workflow variables** provide runtime values through `{"$var":"KEY"}`. Secret variables are never returned by list APIs and exact secret values are redacted from execution receipts.
+- **Git** remains code SSOT; project knowledge/memory remain their existing SSOTs.
-Private graphs and run receipts are keyed by an authenticated principal hash. Another principal cannot list, read or poll them. Source code and builtin templates contain no installation owner, private path, credential or user-specific workflow seed. Project/folder paths are resolved only at runtime after canonical-project containment checks.
+Graphs, versions, variables and execution receipts are private per authenticated principal. Source and builtin templates contain no operator-specific user, credential, path or seeded workflow.
-Secret-like fields (`token`, `password`, `apiKey`, authorization headers, cookies, etc.) are rejected recursively from stored graph definitions. Credentials continue to resolve through normal MSO integration/project authorities during execution.
+## Node catalog
-## Graph model
+### Triggers
-A graph is a versioned DAG with revision conflict protection. MVP node types:
+- `manual` — UI/CLI/MCP run
+- `schedule` — interval or five-field cron, with IANA timezone support
+- `webhook` — GET/POST/PUT/PATCH/DELETE server endpoint; optional bearer token from a private secret variable
+
+Trigger nodes must be roots. Activating a workflow enables its server-side schedule/webhook behavior; drafts remain inert.
+
+Webhook endpoint:
+
+```text
+/api/v1/workflows/webhook/<graphId>/<nodeId>
+```
+
+`responseMode=onReceived` returns a run id immediately. `responseMode=lastNode` waits for bounded execution and returns only the explicit output-node result.
+
+### Flow control
+
+- `condition` — true/false handles
+- `switch` — named case handles plus default
+- `merge` — combine, append or pass-through incoming outputs
+- `batch` — split up to 1000 items into deterministic batches
+- `loop` — execute one bounded tool for each item with concurrency 1–4
+- `wait` — delay/until, bounded to ten minutes inside a run
+- `subflow` — execute another private Workflow Graph, or a legacy project flow
+- `output` — explicit result collection
+
+Graph edges stay acyclic. Repetition is represented by the bounded `loop` node or reusable subflow rather than unrestricted cyclic edges, preventing accidental runaway server automation. Cross-workflow recursion is rejected with an ancestry guard.
+
+### Actions and context
-- `manual`
- `tool`
- `project_function`
- `project_mcp`
+- `integration`
- `script`
- `agent`
-- `subflow`
-- `condition`
- `project`
- `folder`
- `skill`
- `knowledge`
-- `output`
-Cycles are rejected in v2 MVP. Condition nodes route `true` / `false` handles. Disabled or unselected branches become `skipped`.
+Project/folder nodes resolve the live canonical server path when the graph runs and can open that real directory in MSO Files/Finder.
-## Runtime receipts
+## Data binding
-Each graph run persists a private receipt. Nodes expose:
+Node config supports safe declarative bindings:
-- queued / running / completed / failed / skipped / blocked
-- start/end/duration
-- bounded redacted output
-- error text
-- compact node log
+```json
+{ "$ref": "nodes.previous.output.value" }
+```
-On failure, the receipt includes `failedNodeId` and `failedNodeName`; downstream queued nodes become `blocked`. Failed mutations are not replayed automatically.
+```json
+{ "$var": "PRIVATE_VARIABLE" }
+```
-## Visual editor
+Loop arguments additionally support `$item` and `$index`.
-The native **Workflows** app (`/workflows`) provides:
+Secret-like fields such as raw tokens, passwords, API keys, cookies and authorization headers are rejected recursively from stored graph definitions. Credential-backed actions use an `integration` node referencing an existing MSO integration connection instead.
-- private workflow list
-- draggable node canvas and edges
-- node/edge CRUD
-- JSON node config inspector
-- duplicate/archive/save/run controls
-- per-node run log
-- project/folder nodes that open the resolved real server directory in MSO Files/Finder
+## Retry and error handling
-The browser does not attempt to open a VPS desktop file manager.
+Action nodes may use:
-## Automatic learning
+```json
+{
+ "retry": { "maxAttempts": 3, "backoffMs": 1000 }
+}
+```
+
+Retries are bounded to five attempts with bounded exponential backoff. A red `error` output routes a failed node to an explicit error branch. `onError: "continue"` supports continue-on-fail behavior. A graph can also set `metadata.errorWorkflowId` to invoke another private workflow after an unhandled failure.
+
+Successful runs finish `completed`; handled action failures finish `completed_with_errors`; unhandled failures record the exact failed node and block downstream nodes.
+
+## Execution history and observability
+
+Private run receipts retain up to 1000 recent executions and expose:
+
+- trigger type
+- graph revision
+- queued / running / completed / failed / skipped / blocked node state
+- attempts and duration
+- bounded node output
+- compact logs
+- failed node id/name
+
+The Workflows canvas reflects live node state and pulses edges while related nodes run. The History panel filters one graph's persisted executions and can reopen a complete receipt.
-`workflow_start` checks automation in this order:
+## Versions and rollback
-1. matching private Workflow Graph v2
-2. existing project/builtin linear flow
-3. learned recipe and deterministic script candidate
-4. normal bounded execution
+Create/update/restore operations save private snapshots. Up to 100 versions are retained per graph. The Versions panel shows timestamp, reason, revision and node count; restore is compare-and-swap against the current graph revision so concurrent edits cannot be silently overwritten.
-Successful `workflow_finish` automatically learns the sanitized route, updates private procedural memory and creates/deduplicates a private **draft** graph candidate. Learned drafts never auto-activate or auto-run; ordinary scope/authorization still applies.
+## Templates and AI-assisted creation
-This makes repeated session history useful without requiring a separate manual memory write for every successful workflow. Manual user-test evidence still uses project memory because it has stronger authority semantics.
+The Create dialog supports:
-## MCP tools
+- blank graph
+- generic builtin templates
+- AI-assisted draft generation using MSO's currently selected model
-- `workflow_graph` — `action=list|get|create|update|delete|clone|run|status`; action-specific fields go in `data` (`definition`, `revision`, `input`, `key`).
+AI assistance has an isolated workflow-design system prompt, receives no implicit owner-memory recall, emits JSON only, cannot authorize execution, and is validated through the same graph schema. AI-created graphs always start as drafts.
+
+## Native Workflows app
+
+`/workflows` provides:
+
+- private searchable workflow library with folder/tag metadata
+- draft / active / archived lifecycle
+- searchable node palette
+- draggable canvas
+- click-to-connect input/output ports
+- true/false, switch and error handles
+- structured trigger/action/retry inspectors plus advanced JSON
+- real project/folder navigation
+- execution log + persisted history
+- graph version restore
+- private variable/secret manager
+- template and AI-assisted creation
+
+Run automatically saves a dirty graph before execution, so execution always uses the revision visible in the editor.
+
+## CLI
+
+```bash
+mso workflow list
+mso workflow show <id>
+mso workflow catalog --query webhook
+mso workflow templates
+mso workflow template webhook-router
+mso workflow create --input @workflow.json
+mso workflow save <id> --revision <rev> --input @workflow.json
+mso workflow run <id> --input '{}' --key operation-001 --wait
+mso workflow runs <id>
+mso workflow versions <id>
+mso workflow restore <id> --revision <current> --version <saved>
+mso workflow variables
+mso workflow variable-set WEBHOOK_TOKEN --input '"secret"' --secret
+mso workflow variable-delete WEBHOOK_TOKEN
+mso workflow ai --prompt "Every weekday inspect project health and route failures"
+```
+
+## MCP
+
+MSO deliberately keeps this capability behind one compact MCP tool to preserve the public schema budget:
+
+`workflow_graph`
+
+Actions:
+
+`list`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `versions`, `restore`, `catalog`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`.
+
+The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools remain compatible for small deterministic project-owned sequences.
+
+## Automatic learning
-The existing v1 tools remain compatible:
+`workflow_start` still checks reusable automation before performing exploratory work. Successful `workflow_finish` learns a sanitized route, updates private procedural memory and creates/deduplicates a private draft graph candidate. Learned workflows never auto-activate or bypass normal scope/authz checks.
-- `flow_catalog`
-- `flow_manage`
-- `flow_run`
-- `flow_status`
+## Scope of n8n parity
-Use v1 for compact deterministic ordered API/MCP sequences; use graph v2 for visual branching workflows, mixed node types and richer runtime observability.
+MSO targets **core self-hosted workflow parity**, not n8n's SaaS business surface. MSO intentionally uses its own server-native project, filesystem, Skill, agent and integration nodes instead of reproducing n8n's marketplace or cloud billing/team-administration products. Free cyclic graph topology is also intentionally replaced by bounded loop/subflow constructs for safer unattended server execution.
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index ff631f2c..89f583d6 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -1,81 +1,54 @@
"use client";
-
import { useEffect, useMemo, useState } from "react";
-import { Copy, Play, Plus, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
+import { Copy, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
import type { AppProps } from "@/features/appshell";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
import { AppFrame, openWindow } from "@/features/appshell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { Badge } from "@/components/ui/badge";
import { WorkflowCanvas } from "./components/workflow-canvas";
+import { WorkflowCreateDialog } from "./components/workflow-create-dialog";
import { WorkflowInspector } from "./components/workflow-inspector";
+import { WorkflowNodePalette } from "./components/workflow-node-palette";
+import { WorkflowRunHistory } from "./components/workflow-run-history";
import { WorkflowRunPanel } from "./components/workflow-run-panel";
-import { cloneGraph, createGraph, deleteGraph, getGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
-
-function starterGraph(name = "New Workflow") {
- return {
- name, description: "Private workflow graph.", status: "draft" as const, inputs: {}, metadata: { provenance: "user" as const },
- nodes: [
- { id: "manual", name: "Manual Trigger", type: "manual" as const, position: { x: 80, y: 160 }, config: {} },
- { id: "output", name: "Output", type: "output" as const, position: { x: 420, y: 160 }, config: {} },
- ],
- edges: [{ id: "edge-start", source: "manual", target: "output" }],
- };
-}
-
-export default function WorkflowsApp(_props: AppProps) {
- const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null);
- const [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
- const [busy, setBusy] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<"inspector" | "runs">("inspector");
- const node = useMemo(() => graph?.nodes.find((item) => item.id === selected) ?? null, [graph, selected]);
- const runStates = useMemo(() => new Map(run?.nodes.map((item) => [item.id, item.state]) ?? []), [run]);
- const refresh = async (selectId?: string) => {
- const list = await listGraphs(); setGraphs(list);
- const id = selectId ?? graph?.id ?? list[0]?.id;
- if (id) setGraph(await getGraph(id)); else setGraph(null);
- };
- useEffect(() => {
- let cancelled = false;
- void listGraphs().then(async (list) => {
- if (cancelled) return;
- setGraphs(list);
- if (list[0]) setGraph(await getGraph(list[0].id));
- }).catch((error: unknown) => { if (!cancelled) setMessage(error instanceof Error ? error.message : "Could not load workflows"); });
- return () => { cancelled = true; };
- }, []);
- useEffect(() => {
- if (!run || run.state !== "running") return;
- const timer = setInterval(() => { void runStatus(run.id).then(setRun).catch(() => undefined); }, 1600); return () => clearInterval(timer);
- }, [run]);
- const wrap = async (fn: () => Promise<void>) => { setBusy(true); setMessage(""); try { await fn(); } catch (error) { setMessage(error instanceof Error ? error.message : "Action failed"); } finally { setBusy(false); } };
- const create = () => wrap(async () => { const next = await createGraph(starterGraph()); await refresh(next.id); setSelected("manual"); });
- const save = () => graph && wrap(async () => { const next = await updateGraph(graph); setGraph(next); setGraphs(await listGraphs()); setMessage("Saved"); });
- const duplicate = () => graph && wrap(async () => { const next = await cloneGraph(graph.id); await refresh(next.id); });
- const remove = () => graph && wrap(async () => { await deleteGraph(graph); setSelected(null); setRun(null); const list = await listGraphs(); setGraphs(list); setGraph(list[0] ? await getGraph(list[0].id) : null); });
- const execute = () => graph && wrap(async () => { const receipt = await runGraph(graph.id); setRun(receipt); setPanel("runs"); });
- const updateNode = (next: WorkflowGraphNode) => graph && setGraph({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });
- const deleteNode = (id: string) => { if (!graph) return; setGraph({ ...graph, nodes: graph.nodes.filter((item) => item.id !== id), edges: graph.edges.filter((edge) => edge.source !== id && edge.target !== id) }); setSelected(null); };
- const openNode = async (id: string) => {
- if (!graph) return;
- const resolved = await resolveNode(graph.id, id);
- openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true });
- };
- const addNode = (type: WorkflowGraphNodeType) => {
- if (!graph) return; const id = `${type}-${crypto.randomUUID().slice(0, 8)}`;
- const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase()), type, position: { x: 220 + graph.nodes.length * 32, y: 280 + (graph.nodes.length % 4) * 100 }, config: {} };
- setGraph({ ...graph, nodes: [...graph.nodes, next] }); setSelected(id); setPanel("inspector");
- };
+import { WorkflowVariablePanel } from "./components/workflow-variable-panel";
+import { WorkflowVersionPanel } from "./components/workflow-version-panel";
+import { cloneGraph, createFromTemplate, createGraph, deleteGraph, getGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
- return <AppFrame safeArea={false} className="h-full" toolbar={<div className="flex h-11 items-center gap-2 border-b px-3">
- <Workflow className="size-4" /><span className="text-sm font-semibold">Workflows</span><div className="h-4 w-px bg-border" />
- {graph && <Input className="h-8 max-w-56" value={graph.name} onChange={(e) => setGraph({ ...graph, name: e.target.value })} />}
- <div className="ml-auto flex items-center gap-1"><Button size="sm" variant="ghost" onClick={() => void refresh()} disabled={busy}><RefreshCw className="size-3" /></Button><Button size="sm" variant="outline" onClick={() => void create()} disabled={busy}><Plus className="mr-1 size-3" />New</Button>{graph && <><Button size="sm" variant="outline" onClick={() => void duplicate()} disabled={busy}><Copy className="size-3" /></Button><Button size="sm" variant="outline" onClick={() => void save()} disabled={busy}><Save className="mr-1 size-3" />Save</Button><Button size="sm" onClick={() => void execute()} disabled={busy}><Play className="mr-1 size-3" />Run</Button><Button size="sm" variant="ghost" onClick={() => void remove()} disabled={busy}><Trash2 className="size-3" /></Button></>}</div>
- </div>}>
- <div className="grid h-full min-h-0 grid-cols-[220px_minmax(0,1fr)_300px]">
- <aside className="min-h-0 border-r bg-muted/10"><div className="border-b p-2"><Button className="w-full" size="sm" onClick={() => void create()}><Plus className="mr-1 size-3" />Create workflow</Button></div><ScrollArea className="h-[calc(100%-49px)]"><div className="space-y-1 p-2">{graphs.length === 0 && <div className="p-3 text-xs text-muted-foreground">No private workflows yet. Successful repeated sessions can also create learned drafts.</div>}{graphs.map((item) => <button key={item.id} type="button" onClick={() => void wrap(async () => { setGraph(await getGraph(item.id)); setSelected(null); setRun(null); })} className={`w-full rounded-lg border p-2 text-left text-xs ${graph?.id === item.id ? "bg-accent" : "bg-card"}`}><div className="truncate font-medium">{item.name}</div><div className="mt-1 text-[10px] text-muted-foreground">{item.status} · {item.nodes.length} nodes{item.metadata.provenance === "learned-from-session" ? " · learned" : ""}</div></button>)}</div></ScrollArea></aside>
- <main className="min-h-0 min-w-0 overflow-hidden">{graph ? <div className="flex h-full flex-col"><div className="flex h-10 items-center gap-2 border-b px-2"><select className="h-7 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(e) => setGraph({ ...graph, status: e.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><select className="h-7 rounded border bg-background px-2 text-xs" defaultValue="" onChange={(e) => { if (e.target.value) { addNode(e.target.value as WorkflowGraphNodeType); e.target.value = ""; } }}><option value="">+ Add node</option>{["tool","project_function","project_mcp","script","agent","subflow","condition","project","folder","skill","knowledge","output"].map((type) => <option key={type} value={type}>{type}</option>)}</select>{message && <span className="ml-auto truncate text-[11px] text-muted-foreground">{message}</span>}</div><div className="min-h-0 flex-1 overflow-auto"><WorkflowCanvas graph={graph} selectedId={selected} onSelect={setSelected} nodeStates={runStates} onOpen={(id) => void openNode(id)} onMove={(id, position) => setGraph({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} /></div></div> : <div className="flex h-full items-center justify-center text-sm text-muted-foreground">Create or select a workflow.</div>}</main>
- <aside className="min-h-0 border-l"><div className="flex h-10 border-b"><button className={`flex-1 text-xs ${panel === "inspector" ? "font-semibold" : "text-muted-foreground"}`} onClick={() => setPanel("inspector")}>Inspector</button><button className={`flex-1 text-xs ${panel === "runs" ? "font-semibold" : "text-muted-foreground"}`} onClick={() => setPanel("runs")}>Run log</button></div><div className="h-[calc(100%-40px)]">{graph && panel === "inspector" ? <ScrollArea className="h-full"><WorkflowInspector key={node?.id ?? "none"} graph={graph} node={node} onNode={updateNode} onDeleteNode={deleteNode} onGraph={setGraph} /></ScrollArea> : <WorkflowRunPanel run={run} />}</div></aside>
- </div>
- </AppFrame>;
+type Definition=Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">;
+type Panel="inspector"|"run"|"history"|"versions"|"variables";
+function starterGraph():Definition{return{name:"New Workflow",description:"Private workflow graph.",status:"draft",inputs:{},metadata:{provenance:"user"},nodes:[{id:"manual",name:"Manual Trigger",type:"manual",position:{x:80,y:160},config:{}},{id:"output",name:"Output",type:"output",position:{x:420,y:160},config:{}}],edges:[{id:"edge-start",source:"manual",target:"output"}]};}
+export default function WorkflowsApp(_props:AppProps){
+ const[graphs,setGraphs]=useState<WorkflowGraph[]>([]),[graph,setGraph]=useState<WorkflowGraph|null>(null),[selected,setSelected]=useState<string|null>(null),[run,setRun]=useState<WorkflowGraphRun|null>(null),[busy,setBusy]=useState(false),[dirty,setDirty]=useState(false),[message,setMessage]=useState(""),[panel,setPanel]=useState<Panel>("inspector"),[search,setSearch]=useState("");
+ const node=useMemo(()=>graph?.nodes.find((item)=>item.id===selected)??null,[graph,selected]),runStates=useMemo(()=>new Map(run?.nodes.map((item)=>[item.id,item.state])??[]),[run]),filtered=useMemo(()=>{const q=search.toLowerCase().trim();return graphs.filter((item)=>!q||`${item.name} ${item.metadata.folder??""} ${(item.metadata.tags??[]).join(" ")}`.toLowerCase().includes(q));},[graphs,search]);
+ const load=async(selectId?:string)=>{const list=await listGraphs();setGraphs(list);const id=selectId??graph?.id??list[0]?.id;if(id){setGraph(await getGraph(id));setDirty(false);}else{setGraph(null);setDirty(false);}};
+ useEffect(()=>{let cancelled=false;void listGraphs().then(async(list)=>{if(cancelled)return;setGraphs(list);if(list[0]){const first=await getGraph(list[0].id);if(!cancelled)setGraph(first);}}).catch((error:unknown)=>{if(!cancelled)setMessage(error instanceof Error?error.message:"Could not load workflows");});return()=>{cancelled=true;};},[]);
+ useEffect(()=>{if(!run||run.state!=="running")return;const timer=setInterval(()=>{void runStatus(run.id).then(setRun).catch(()=>undefined);},1600);return()=>clearInterval(timer);},[run]);
+ const wrap=async(fn:()=>Promise<void>)=>{setBusy(true);setMessage("");try{await fn();}catch(error){setMessage(error instanceof Error?error.message:"Action failed");}finally{setBusy(false);}};
+ const mutate=(next:WorkflowGraph)=>{setGraph(next);setDirty(true);};
+ const selectGraph=async(id:string)=>{setGraph(await getGraph(id));setSelected(null);setRun(null);setDirty(false);setPanel("inspector");};
+ const createBlank=()=>wrap(async()=>{const next=await createGraph(starterGraph());await load(next.id);setSelected("manual");});
+ const createTemplate=(id:string)=>wrap(async()=>{const next=await createFromTemplate(id);await load(next.id);setSelected(next.nodes[0]?.id??null);});
+ const createAI=(definition:Definition)=>wrap(async()=>{const next=await createGraph(definition);await load(next.id);setSelected(next.nodes[0]?.id??null);});
+ const saveCurrent=async()=>{if(!graph)throw new Error("No workflow selected");if(!dirty)return graph;const next=await updateGraph(graph);setGraph(next);setDirty(false);setGraphs(await listGraphs());return next;};
+ const save=()=>graph&&wrap(async()=>{await saveCurrent();setMessage("Saved");});
+ const duplicate=()=>graph&&wrap(async()=>{const next=await cloneGraph(graph.id);await load(next.id);});
+ const remove=()=>graph&&wrap(async()=>{await deleteGraph(graph);setSelected(null);setRun(null);const list=await listGraphs();setGraphs(list);setGraph(list[0]?await getGraph(list[0].id):null);setDirty(false);});
+ const execute=()=>graph&&wrap(async()=>{const saved=await saveCurrent(),receipt=await runGraph(saved.id);setRun(receipt);setPanel("run");});
+ const updateNode=(next:WorkflowGraphNode)=>graph&&mutate({...graph,nodes:graph.nodes.map((item)=>item.id===next.id?next:item)});
+ const deleteNode=(id:string)=>{if(!graph)return;mutate({...graph,nodes:graph.nodes.filter((item)=>item.id!==id),edges:graph.edges.filter((edge)=>edge.source!==id&&edge.target!==id)});setSelected(null);};
+ const addNode=(type:WorkflowGraphNodeType,defaults:Record<string,unknown>)=>{if(!graph)return;const id=`${type}-${crypto.randomUUID().slice(0,8)}`,next:WorkflowGraphNode={id,name:type.replaceAll("_"," ").replace(/\b\w/g,(c)=>c.toUpperCase()),type,position:{x:220+graph.nodes.length*36,y:240+(graph.nodes.length%4)*110},config:structuredClone(defaults)};mutate({...graph,nodes:[...graph.nodes,next]});setSelected(id);setPanel("inspector");};
+ const connect=(source:string,target:string,sourceHandle?:string)=>{if(!graph||graph.edges.some((edge)=>edge.source===source&&edge.target===target&&edge.sourceHandle===sourceHandle))return;mutate({...graph,edges:[...graph.edges,{id:`edge-${crypto.randomUUID().slice(0,8)}`,source,target,...(sourceHandle?{sourceHandle}:{})}]});};
+ const openNode=async(id:string)=>{if(!graph)return;const resolved=await resolveNode(graph.id,id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
+ const panelButton=(value:Panel,label:string)=><button type="button" className={`min-w-0 flex-1 px-1 text-[10px] ${panel===value?"font-semibold text-foreground":"text-muted-foreground"}`} onClick={()=>setPanel(value)}>{label}</button>;
+ return <AppFrame safeArea={false} className="h-full" toolbar={<div className="flex h-11 items-center gap-2 border-b px-3"><Workflow className="size-4"/><span className="text-sm font-semibold">Workflows</span>{dirty&&<Badge variant="outline">Unsaved</Badge>}{graph&&<Input className="h-8 max-w-56" value={graph.name} onChange={(e)=>mutate({...graph,name:e.target.value})}/>}<div className="ml-auto flex items-center gap-1"><Button size="sm" variant="ghost" onClick={()=>void load()} disabled={busy}><RefreshCw className="size-3"/></Button><WorkflowCreateDialog onBlank={async()=>{await createBlank();}} onTemplate={async(id)=>{await createTemplate(id);}} onAI={async(definition)=>{await createAI(definition);}}/>{graph&&<><Button size="sm" variant="outline" onClick={()=>void duplicate()} disabled={busy}><Copy className="size-3"/></Button><Button size="sm" variant="outline" onClick={()=>void save()} disabled={busy||!dirty}><Save className="mr-1 size-3"/>Save</Button><Button size="sm" onClick={()=>void execute()} disabled={busy}><Play className="mr-1 size-3"/>Run</Button><Button size="sm" variant="ghost" onClick={()=>void remove()} disabled={busy}><Trash2 className="size-3"/></Button></>}</div></div>}>
+ <div className="grid h-full min-h-0 grid-cols-[240px_minmax(0,1fr)_340px]">
+ <aside className="min-h-0 border-r bg-muted/10"><div className="space-y-2 border-b p-2"><Input className="h-8" placeholder="Search workflows…" value={search} onChange={(e)=>setSearch(e.target.value)}/><WorkflowCreateDialog onBlank={async()=>{await createBlank();}} onTemplate={async(id)=>{await createTemplate(id);}} onAI={async(definition)=>{await createAI(definition);}}/></div><ScrollArea className="h-[calc(100%-86px)]"><div className="space-y-1 p-2">{filtered.length===0&&<div className="p-3 text-xs text-muted-foreground">No matching private workflows.</div>}{filtered.map((item)=><button key={item.id} type="button" onClick={()=>void wrap(()=>selectGraph(item.id))} className={`w-full rounded-lg border p-2 text-left text-xs ${graph?.id===item.id?"bg-accent":"bg-card"}`}><div className="truncate font-medium">{item.name}</div><div className="mt-1 flex flex-wrap gap-1 text-[10px] text-muted-foreground"><span>{item.status} · {item.nodes.length} nodes</span>{item.metadata.folder&&<span>· {item.metadata.folder}</span>}</div></button>)}</div></ScrollArea></aside>
+ <main className="min-h-0 min-w-0 overflow-hidden">{graph?<div className="flex h-full flex-col"><div className="flex h-10 items-center gap-2 border-b px-2"><select className="h-7 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(e)=>mutate({...graph,status:e.target.value as WorkflowGraph["status"]})}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="text-[10px] text-muted-foreground">Click output port → input port to connect. Red port = error.</span>{message&&<span className="ml-auto max-w-72 truncate text-[11px] text-muted-foreground">{message}</span>}</div><div className="min-h-0 flex-1 overflow-auto"><WorkflowCanvas graph={graph} selectedId={selected} onSelect={(id)=>{setSelected(id);if(id)setPanel("inspector");}} nodeStates={runStates} onOpen={(id)=>void openNode(id)} onConnect={connect} onMove={(id,position)=>mutate({...graph,nodes:graph.nodes.map((item)=>item.id===id?{...item,position}:item)})}/></div></div>:<div className="flex h-full items-center justify-center text-sm text-muted-foreground">Create or select a workflow.</div>}</main>
+ <aside className="min-h-0 border-l"><div className="flex h-10 border-b">{panelButton("inspector","Inspector")}{panelButton("run","Run")}{panelButton("history","History")}{panelButton("versions","Versions")}{panelButton("variables","Vars")}</div><div className="h-[calc(100%-40px)]">{graph&&panel==="inspector"&&<ScrollArea className="h-full"><WorkflowInspector key={node?.id??`graph-${graph.id}`} graph={graph} graphs={graphs} node={node} onNode={updateNode} onDeleteNode={deleteNode} onGraph={mutate}/></ScrollArea>}{panel==="run"&&<WorkflowRunPanel run={run}/>} {graph&&panel==="history"&&<WorkflowRunHistory graph={graph} onSelect={(selectedRun)=>{setRun(selectedRun);setPanel("run");}}/>}{graph&&panel==="versions"&&<WorkflowVersionPanel graph={graph} onRestored={(next)=>{setGraph(next);setDirty(false);void listGraphs().then(setGraphs);}}/>}{panel==="variables"&&<WorkflowVariablePanel/>}</div></aside>
+ </div>
+ </AppFrame>;
}
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
index 4b43200c..5477f442 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -1,52 +1,25 @@
"use client";
-
-import { useMemo, useRef } from "react";
+import { useMemo, useRef, useState } from "react";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeState } from "@/lib/contracts/workflow-graph";
import { cn } from "@/lib/utils";
-
-const W = 184, H = 76;
-
-export function WorkflowCanvas({ graph, selectedId, onSelect, onMove, nodeStates, onOpen }: {
- graph: WorkflowGraph;
- selectedId: string | null;
- onSelect: (id: string | null) => void;
- onMove: (id: string, position: { x: number; y: number }) => void;
- nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>;
- onOpen?: (id: string) => void;
-}) {
- const drag = useRef<{ id: string; dx: number; dy: number } | null>(null);
- const nodes = useMemo(() => new Map(graph.nodes.map((node) => [node.id, node])), [graph.nodes]);
- const down = (event: React.PointerEvent, node: WorkflowGraphNode) => {
- const box = event.currentTarget.getBoundingClientRect();
- drag.current = { id: node.id, dx: event.clientX - box.left, dy: event.clientY - box.top };
- event.currentTarget.setPointerCapture(event.pointerId); onSelect(node.id);
- };
- const move = (event: React.PointerEvent) => {
- if (!drag.current) return;
- const canvas = event.currentTarget.getBoundingClientRect();
- onMove(drag.current.id, { x: Math.max(12, event.clientX - canvas.left - drag.current.dx), y: Math.max(12, event.clientY - canvas.top - drag.current.dy) });
- };
- return (
- <div className="relative h-full min-h-[520px] min-w-[880px] overflow-auto bg-muted/20" onPointerMove={move} onPointerUp={() => { drag.current = null; }} onClick={(event) => { if (event.target === event.currentTarget) onSelect(null); }}>
- <svg className="pointer-events-none absolute inset-0 h-[1400px] w-[2200px]" aria-hidden>
- {graph.edges.map((edge) => {
- const a = nodes.get(edge.source), b = nodes.get(edge.target); if (!a || !b) return null;
- const x1 = a.position.x + W, y1 = a.position.y + H / 2, x2 = b.position.x, y2 = b.position.y + H / 2, c = Math.max(60, Math.abs(x2 - x1) / 2);
- return <path key={edge.id} d={`M ${x1} ${y1} C ${x1 + c} ${y1}, ${x2 - c} ${y2}, ${x2} ${y2}`} fill="none" stroke="currentColor" strokeWidth="1.5" className="text-border" />;
- })}
- </svg>
- <div className="relative h-[1400px] w-[2200px]">
- {graph.nodes.map((node) => (
- <button key={node.id} type="button" onPointerDown={(event) => down(event, node)} onClick={(event) => { event.stopPropagation(); onSelect(node.id); }}
- onDoubleClick={() => { if ((node.type === "project" || node.type === "folder") && onOpen) onOpen(node.id); }}
- className={cn("absolute flex h-[76px] w-[184px] cursor-grab flex-col items-start justify-center rounded-xl border bg-card px-3 text-left shadow-sm active:cursor-grabbing", selectedId === node.id && "ring-2 ring-ring", nodeStates?.get(node.id) === "failed" && "border-destructive ring-1 ring-destructive", nodeStates?.get(node.id) === "running" && "border-primary ring-1 ring-primary", ["skipped", "blocked"].includes(nodeStates?.get(node.id) ?? "") && "opacity-55", node.disabled && "opacity-50")}
- style={{ transform: `translate(${node.position.x}px, ${node.position.y}px)` }}>
- <span className="w-full truncate text-xs font-semibold">{node.name}</span>
- <span className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{node.type.replaceAll("_", " ")}{nodeStates?.get(node.id) ? ` · ${nodeStates.get(node.id)}` : ""}</span>
- {node.type === "condition" && <span className="mt-1 text-[10px] text-muted-foreground">true / false</span>}
- </button>
- ))}
- </div>
- </div>
- );
+const W=184,H=76;
+type Source={id:string;handle?:string}|null;
+function handles(node:WorkflowGraphNode){if(node.type==="condition")return["true","false"];if(node.type==="switch"){const cases=Array.isArray(node.config.cases)?node.config.cases:[];return[...cases.map((row,i)=>row&&typeof row==="object"&&typeof (row as {handle?:unknown}).handle==="string"?String((row as {handle:string}).handle):`case-${i+1}`),"default"];}return[undefined];}
+function canError(node:WorkflowGraphNode){return!["manual","schedule","webhook","output"].includes(node.type);}
+export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeStates,onOpen}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;onOpen?:(id:string)=>void;}){
+ const drag=useRef<{id:string;dx:number;dy:number}|null>(null),[source,setSource]=useState<Source>(null),nodes=useMemo(()=>new Map(graph.nodes.map((node)=>[node.id,node])),[graph.nodes]);
+ const down=(event:React.PointerEvent,node:WorkflowGraphNode)=>{const box=event.currentTarget.getBoundingClientRect();drag.current={id:node.id,dx:event.clientX-box.left,dy:event.clientY-box.top};event.currentTarget.setPointerCapture(event.pointerId);onSelect(node.id);};
+ const move=(event:React.PointerEvent)=>{if(!drag.current)return;const canvas=event.currentTarget.getBoundingClientRect();onMove(drag.current.id,{x:Math.max(12,event.clientX-canvas.left-drag.current.dx),y:Math.max(12,event.clientY-canvas.top-drag.current.dy)});};
+ const connect=(target:string)=>{if(source&&source.id!==target)onConnect(source.id,target,source.handle);setSource(null);};
+ return <div className="relative h-full min-h-[520px] min-w-[880px] overflow-auto bg-muted/20" onPointerMove={move} onPointerUp={()=>{drag.current=null;}} onClick={(event)=>{if(event.target===event.currentTarget){onSelect(null);setSource(null);}}}>
+ <svg className="absolute inset-0 h-[1400px] w-[2200px]" aria-hidden>{graph.edges.map((edge)=>{const a=nodes.get(edge.source),b=nodes.get(edge.target);if(!a||!b)return null;const x1=a.position.x+W,y1=a.position.y+H/2,x2=b.position.x,y2=b.position.y+H/2,c=Math.max(60,Math.abs(x2-x1)/2),live=nodeStates?.get(edge.source)==="running"||nodeStates?.get(edge.target)==="running";return <path key={edge.id} d={`M ${x1} ${y1} C ${x1+c} ${y1}, ${x2-c} ${y2}, ${x2} ${y2}`} fill="none" stroke="currentColor" strokeWidth="1.5" className={cn("pointer-events-none text-border",live&&"animate-pulse text-primary")}/>;})}</svg>
+ <div className="relative h-[1400px] w-[2200px]">{graph.nodes.map((node)=><div key={node.id} className="absolute" style={{transform:`translate(${node.position.x}px, ${node.position.y}px)`}}>
+ <button type="button" onPointerDown={(event)=>down(event,node)} onClick={(event)=>{event.stopPropagation();onSelect(node.id);}} onDoubleClick={()=>{if((node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}} className={cn("flex h-[76px] w-[184px] cursor-grab flex-col items-start justify-center rounded-xl border bg-card px-3 text-left shadow-sm active:cursor-grabbing",selectedId===node.id&&"ring-2 ring-ring",nodeStates?.get(node.id)==="failed"&&"border-destructive ring-1 ring-destructive",nodeStates?.get(node.id)==="running"&&"border-primary ring-1 ring-primary",["skipped","blocked"].includes(nodeStates?.get(node.id)??"")&&"opacity-55",node.disabled&&"opacity-50")}>
+ <span className="w-full truncate text-xs font-semibold">{node.name}</span><span className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{node.type.replaceAll("_"," ")}{nodeStates?.get(node.id)?` · ${nodeStates.get(node.id)}`:""}</span>{node.type==="condition"&&<span className="mt-1 text-[10px] text-muted-foreground">true / false</span>}
+ </button>
+ {!["manual","schedule","webhook"].includes(node.type)&&<button type="button" aria-label={`Connect into ${node.name}`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();connect(node.id);}} className={cn("absolute -left-2 top-1/2 size-4 -translate-y-1/2 rounded-full border bg-background",source&&"ring-1 ring-ring")}/>}
+ {node.type!=="output"&&handles(node).map((handle,index)=><button key={handle??"default"} type="button" title={handle??"output"} aria-label={`Connect ${node.name} ${handle??"output"}`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();setSource({id:node.id,...(handle?{handle}:{})});}} className={cn("absolute -right-2 size-4 rounded-full border bg-background",source?.id===node.id&&source.handle===handle&&"ring-2 ring-ring")} style={{top:`${22+index*22}px`}}/>)}
+ {canError(node)&&<button type="button" title="error" aria-label={`Connect ${node.name} error`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();setSource({id:node.id,handle:"error"});}} className={cn("absolute -right-2 bottom-1 size-3 rounded-full border border-destructive bg-background",source?.id===node.id&&source.handle==="error"&&"ring-2 ring-destructive")}/>}
+ </div>)}</div>
+ </div>;
}
diff --git a/frontend/slices/workflows/components/workflow-create-dialog.tsx b/frontend/slices/workflows/components/workflow-create-dialog.tsx
new file mode 100644
index 00000000..897fbb22
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-create-dialog.tsx
@@ -0,0 +1,17 @@
+"use client";
+import { useEffect, useState } from "react";
+import { Sparkles } from "lucide-react";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Textarea } from "@/components/ui/textarea";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { aiSuggest, listTemplates } from "../lib/api";
+type Definition=Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">;
+export function WorkflowCreateDialog({onBlank,onTemplate,onAI}:{onBlank:()=>Promise<void>;onTemplate:(id:string)=>Promise<void>;onAI:(definition:Definition)=>Promise<void>}){
+ const[open,setOpen]=useState(false),[tab,setTab]=useState<"blank"|"templates"|"ai">("templates"),[templates,setTemplates]=useState<Array<{id:string;title:string;description:string;tags:string[];nodeCount:number}>>([]),[prompt,setPrompt]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState("");
+ useEffect(()=>{if(!open)return;let cancelled=false;void listTemplates().then((rows)=>{if(!cancelled)setTemplates(rows);}).catch(()=>undefined);return()=>{cancelled=true;};},[open]);
+ const run=async(fn:()=>Promise<void>)=>{setBusy(true);setError("");try{await fn();setOpen(false);}catch(e){setError(e instanceof Error?e.message:"Action failed");}finally{setBusy(false);}};
+ return <Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild><Button size="sm" variant="outline">New</Button></DialogTrigger><DialogContent className="sm:max-w-2xl"><DialogHeader><DialogTitle>Create workflow</DialogTitle><DialogDescription>Blank graph, reusable template, or AI-assisted draft. Secrets stay outside definitions.</DialogDescription></DialogHeader><Tabs><TabsList>{(["templates","blank","ai"] as const).map((value)=><TabsTrigger key={value} active={tab===value} onClick={()=>setTab(value)}>{value}</TabsTrigger>)}</TabsList></Tabs>{tab==="blank"&&<div className="rounded-lg border p-4"><p className="mb-3 text-sm text-muted-foreground">Start with Manual Trigger → Output.</p><Button disabled={busy} onClick={()=>void run(onBlank)}>Create blank</Button></div>}{tab==="templates"&&<ScrollArea className="h-72"><div className="grid gap-2 sm:grid-cols-2">{templates.map((item)=><button key={item.id} type="button" disabled={busy} onClick={()=>void run(()=>onTemplate(item.id))} className="rounded-lg border p-3 text-left hover:bg-accent"><div className="text-sm font-semibold">{item.title}</div><p className="mt-1 text-xs text-muted-foreground">{item.description}</p><div className="mt-2 text-[10px] text-muted-foreground">{item.nodeCount} nodes · {item.tags.join(" · ")}</div></button>)}</div></ScrollArea>}{tab==="ai"&&<div className="space-y-3"><Textarea className="min-h-32" placeholder="Describe the workflow, triggers, branches, project/integration actions, and expected output…" value={prompt} onChange={(e)=>setPrompt(e.target.value)}/><Button disabled={busy||!prompt.trim()} onClick={()=>void run(async()=>onAI(await aiSuggest(prompt)))}><Sparkles className="mr-2 size-4"/>Generate draft</Button></div>}{error&&<p className="text-xs text-destructive">{error}</p>}</DialogContent></Dialog>;
+}
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
index 505a33b1..0bfa2894 100644
--- a/frontend/slices/workflows/components/workflow-inspector.tsx
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -1,41 +1,47 @@
"use client";
import { useMemo, useState } from "react";
-import { FolderOpen, Link2, Trash2 } from "lucide-react";
+import { Copy, FolderOpen, Trash2 } from "lucide-react";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";
import { WORKFLOW_GRAPH_NODE_TYPES } from "@/lib/contracts/workflow-graph";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
+import { Switch } from "@/components/ui/switch";
import { openWindow } from "@/features/appshell";
import { resolveNode } from "../lib/api";
+const selectClass="h-9 w-full rounded-md border bg-background px-2";
+function Field({label,children}:{label:string;children:React.ReactNode}){return <label className="block space-y-1"><span className="text-muted-foreground">{label}</span>{children}</label>;}
+function number(value:unknown,fallback:number){const n=Number(value);return Number.isFinite(n)?n:fallback;}
-export function WorkflowInspector({ graph, node, onNode, onDeleteNode, onGraph }: {
- graph: WorkflowGraph; node: WorkflowGraphNode | null;
- onNode: (node: WorkflowGraphNode) => void; onDeleteNode: (id: string) => void; onGraph: (graph: WorkflowGraph) => void;
-}) {
- const [configText, setConfigText] = useState(node ? JSON.stringify(node.config, null, 2) : "{}");
- const [target, setTarget] = useState("");
- const outgoing = useMemo(() => node ? graph.edges.filter((edge) => edge.source === node.id) : [], [graph.edges, node]);
- if (!node) return <div className="p-4 text-xs text-muted-foreground">Select a node to edit config, edges, or open project folders.</div>;
- const patch = (next: Partial<WorkflowGraphNode>) => onNode({ ...node, ...next });
- const applyConfig = () => { try { patch({ config: JSON.parse(configText) as Record<string, unknown> }); } catch { /* keep draft text */ } };
- const addEdge = () => {
- if (!target || target === node.id) return;
- const id = `edge-${crypto.randomUUID().slice(0, 8)}`;
- onGraph({ ...graph, edges: [...graph.edges, { id, source: node.id, target }] }); setTarget("");
- };
- const openTarget = async () => {
- const resolved = await resolveNode(graph.id, node.id);
- openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true });
- };
- return <div className="space-y-4 p-3 text-xs">
- <div><label className="mb-1 block text-muted-foreground">Name</label><Input value={node.name} onChange={(e) => patch({ name: e.target.value })} /></div>
- <div><label className="mb-1 block text-muted-foreground">Type</label><select className="h-9 w-full rounded-md border bg-background px-2" value={node.type} onChange={(e) => patch({ type: e.target.value as WorkflowGraphNodeType })}>{WORKFLOW_GRAPH_NODE_TYPES.map((type) => <option key={type} value={type}>{type}</option>)}</select></div>
- <div><label className="mb-1 block text-muted-foreground">Config JSON</label><Textarea className="min-h-36 font-mono text-[11px]" value={configText} onChange={(e) => setConfigText(e.target.value)} onBlur={applyConfig} /></div>
- {(node.type === "project" || node.type === "folder") && <Button variant="secondary" size="sm" className="w-full" onClick={() => void openTarget()}><FolderOpen className="mr-2 size-3" />Open real folder</Button>}
- <div className="space-y-2"><div className="font-medium">Outgoing edges</div>{outgoing.map((edge) => <div key={edge.id} className="flex items-center justify-between rounded border p-2"><span className="truncate">→ {graph.nodes.find((item) => item.id === edge.target)?.name ?? edge.target}</span><Button size="icon" variant="ghost" onClick={() => onGraph({ ...graph, edges: graph.edges.filter((item) => item.id !== edge.id) })}><Trash2 className="size-3" /></Button></div>)}
- <div className="flex gap-1"><select className="h-8 min-w-0 flex-1 rounded-md border bg-background px-2" value={target} onChange={(e) => setTarget(e.target.value)}><option value="">Connect to…</option>{graph.nodes.filter((item) => item.id !== node.id).map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}</select><Button size="sm" variant="outline" onClick={addEdge}><Link2 className="size-3" /></Button></div>
- </div>
- <Button variant="destructive" size="sm" className="w-full" onClick={() => onDeleteNode(node.id)}><Trash2 className="mr-2 size-3" />Delete node</Button>
- </div>;
+function AdvancedConfig({value,onApply}:{value:Record<string,unknown>;onApply:(text:string)=>void}){const[text,setText]=useState(JSON.stringify(value,null,2));return <Textarea className="min-h-40 font-mono text-[11px]" value={text} onChange={(e)=>setText(e.target.value)} onBlur={()=>onApply(text)}/>;}
+export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph}:{graph:WorkflowGraph;graphs:WorkflowGraph[];node:WorkflowGraphNode|null;onNode:(node:WorkflowGraphNode)=>void;onDeleteNode:(id:string)=>void;onGraph:(graph:WorkflowGraph)=>void;}){
+ const[advancedError,setAdvancedError]=useState("");
+ const outgoing=useMemo(()=>node?graph.edges.filter((edge)=>edge.source===node.id):[],[graph.edges,node]);
+ if(!node){const tags=graph.metadata.tags?.join(", ")??"";return <div className="space-y-4 p-3 text-xs"><div className="font-semibold">Workflow settings</div><Field label="Description"><Textarea value={graph.description} onChange={(e)=>onGraph({...graph,description:e.target.value})}/></Field><Field label="Folder"><Input value={graph.metadata.folder??""} placeholder="Automation / Operations" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,folder:e.target.value||undefined}})}/></Field><Field label="Tags"><Input value={tags} placeholder="deploy, qa, daily" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,tags:e.target.value.split(",").map((v)=>v.trim()).filter(Boolean).slice(0,32)}})}/></Field><Field label="Timezone"><Input value={graph.metadata.timezone??"UTC"} placeholder="UTC" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,timezone:e.target.value||undefined}})}/></Field><Field label="Error workflow"><select className={selectClass} value={graph.metadata.errorWorkflowId??""} onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,errorWorkflowId:e.target.value||undefined}})}><option value="">None</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><p className="text-[10px] text-muted-foreground">Active schedule/webhook triggers execute server-side. Workflow data, versions, runs and variables stay private to the authenticated principal.</p></div>;}
+ const patch=(next:Partial<WorkflowGraphNode>)=>onNode({...node,...next}),setConfig=(key:string,value:unknown)=>patch({config:{...node.config,[key]:value}}),removeConfig=(key:string)=>{const next={...node.config};delete next[key];patch({config:next});};
+ const applyAdvanced=(text:string)=>{try{const value=JSON.parse(text);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Config must be an object");patch({config:value as Record<string,unknown>});setAdvancedError("");}catch(e){setAdvancedError(e instanceof Error?e.message:"Invalid JSON");}};
+ const openTarget=async()=>{const resolved=await resolveNode(graph.id,node.id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
+ const copyWebhook=()=>void navigator.clipboard?.writeText(`${window.location.origin}/api/v1/workflows/webhook/${graph.id}/${node.id}`);
+ const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop"].includes(node.type);
+ return <div className="space-y-4 p-3 text-xs">
+ <Field label="Name"><Input value={node.name} onChange={(e)=>patch({name:e.target.value})}/></Field>
+ <Field label="Type"><select className={selectClass} value={node.type} onChange={(e)=>patch({type:e.target.value as WorkflowGraphNodeType})}>{WORKFLOW_GRAPH_NODE_TYPES.map((type)=><option key={type} value={type}>{type}</option>)}</select></Field>
+ {node.type==="schedule"&&<><Field label="Schedule mode"><select className={selectClass} value={String(node.config.mode??"interval")} onChange={(e)=>setConfig("mode",e.target.value)}><option value="interval">Interval</option><option value="cron">Cron</option></select></Field>{node.config.mode==="cron"?<Field label="Cron (5 fields)"><Input value={String(node.config.cron??"0 * * * *")} onChange={(e)=>setConfig("cron",e.target.value)}/></Field>:<Field label="Every minutes"><Input type="number" min={1} max={10080} value={number(node.config.everyMinutes,60)} onChange={(e)=>setConfig("everyMinutes",Number(e.target.value))}/></Field>}<Field label="Timezone override"><Input value={String(node.config.timezone??"")} placeholder={graph.metadata.timezone??"UTC"} onChange={(e)=>setConfig("timezone",e.target.value)}/></Field></>}
+ {node.type==="webhook"&&<><Field label="Methods"><Input value={Array.isArray(node.config.methods)?node.config.methods.join(", "):"POST"} onChange={(e)=>setConfig("methods",e.target.value.split(",").map((v)=>v.trim().toUpperCase()).filter(Boolean))}/></Field><Field label="Response"><select className={selectClass} value={String(node.config.responseMode??"onReceived")} onChange={(e)=>setConfig("responseMode",e.target.value)}><option value="onReceived">202 immediately</option><option value="lastNode">Wait for output</option></select></Field><Field label="Auth variable"><Input value={String(node.config.authVariable??"")} placeholder="WEBHOOK_TOKEN (optional)" onChange={(e)=>e.target.value?setConfig("authVariable",e.target.value.toUpperCase()):removeConfig("authVariable")}/></Field><div className="rounded border p-2"><div className="break-all font-mono text-[10px]">/api/v1/workflows/webhook/{graph.id}/{node.id}</div><Button className="mt-2" size="sm" variant="outline" onClick={copyWebhook}><Copy className="mr-1 size-3"/>Copy URL</Button></div></>}
+ {(node.type==="project"||node.type==="folder"||node.type==="knowledge"||node.type==="agent"||node.type==="script"||node.type==="project_function"||node.type==="project_mcp"||node.type==="subflow")&&<Field label="Project"><Input value={String(node.config.project??graph.metadata.project??"")} placeholder="Canonical project id/name" onChange={(e)=>setConfig("project",e.target.value)}/></Field>}
+ {node.type==="folder"&&<Field label="Relative path"><Input value={String(node.config.path??".")} onChange={(e)=>setConfig("path",e.target.value)}/></Field>}
+ {node.type==="tool"&&<Field label="MSO tool"><Input value={String(node.config.tool??"")} placeholder="project_get" onChange={(e)=>setConfig("tool",e.target.value)}/></Field>}
+ {node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}
+ {node.type==="agent"&&<Field label="Agent objective"><Textarea value={String(node.config.message??"")} onChange={(e)=>setConfig("message",e.target.value)}/></Field>}
+ {node.type==="subflow"&&<><Field label="Workflow graph"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Legacy project flow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field>{!node.config.workflowId&&<Field label="Legacy flow id"><Input value={String(node.config.flow??"")} onChange={(e)=>setConfig("flow",e.target.value)}/></Field>}</>}
+ {node.type==="wait"&&<Field label="Delay ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field>}
+ {node.type==="batch"&&<><Field label="Items path"><Input value={String(node.config.itemsPath??"input.items")} onChange={(e)=>setConfig("itemsPath",e.target.value)}/></Field><Field label="Batch size"><Input type="number" min={1} max={1000} value={number(node.config.size,10)} onChange={(e)=>setConfig("size",Number(e.target.value))}/></Field></>}
+ {node.type==="loop"&&<><Field label="Items path"><Input value={String(node.config.itemsPath??"input.items")} onChange={(e)=>setConfig("itemsPath",e.target.value)}/></Field><Field label="Tool per item"><Input value={String(node.config.tool??"")} onChange={(e)=>setConfig("tool",e.target.value)}/></Field><Field label="Concurrency"><Input type="number" min={1} max={4} value={number(node.config.concurrency,1)} onChange={(e)=>setConfig("concurrency",Number(e.target.value))}/></Field></>}
+ {node.type==="merge"&&<Field label="Merge mode"><select className={selectClass} value={String(node.config.mode??"combine")} onChange={(e)=>setConfig("mode",e.target.value)}><option value="combine">Combine by source</option><option value="append">Append</option><option value="passThrough">Pass through latest</option></select></Field>}
+ {actionNode&&<div className="space-y-3 rounded-lg border p-3"><div className="font-medium">Failure policy</div><Field label="Attempts"><Input type="number" min={1} max={5} value={number((node.config.retry as Record<string,unknown>|undefined)?.maxAttempts,1)} onChange={(e)=>setConfig("retry",{...((node.config.retry as Record<string,unknown>|undefined)??{}),maxAttempts:Number(e.target.value)})}/></Field><Field label="Backoff ms"><Input type="number" min={0} max={30000} value={number((node.config.retry as Record<string,unknown>|undefined)?.backoffMs,0)} onChange={(e)=>setConfig("retry",{...((node.config.retry as Record<string,unknown>|undefined)??{}),backoffMs:Number(e.target.value)})}/></Field><label className="flex items-center justify-between"><span>Continue on error</span><Switch checked={node.config.onError==="continue"} onCheckedChange={(checked)=>checked?setConfig("onError","continue"):removeConfig("onError")}/></label><p className="text-[10px] text-muted-foreground">Connect the red error port for an explicit error branch.</p></div>}
+ {(node.type==="project"||node.type==="folder")&&<Button variant="secondary" size="sm" className="w-full" onClick={()=>void openTarget()}><FolderOpen className="mr-2 size-3"/>Open real folder</Button>}
+ <details><summary className="cursor-pointer font-medium">Advanced config JSON</summary><div className="mt-2 space-y-2"><AdvancedConfig key={JSON.stringify(node.config)} value={node.config} onApply={applyAdvanced}/>{advancedError&&<p className="text-destructive">{advancedError}</p>}</div></details>
+ <div className="space-y-2"><div className="font-medium">Connections</div>{outgoing.map((edge)=><div key={edge.id} className="flex items-center justify-between rounded border p-2"><span className="truncate">{edge.sourceHandle?`${edge.sourceHandle} → `:"→ "}{graph.nodes.find((item)=>item.id===edge.target)?.name??edge.target}</span><Button size="icon" variant="ghost" onClick={()=>onGraph({...graph,edges:graph.edges.filter((item)=>item.id!==edge.id)})}><Trash2 className="size-3"/></Button></div>)}<p className="text-[10px] text-muted-foreground">Connect nodes directly from canvas ports.</p></div>
+ <Button variant="destructive" size="sm" className="w-full" onClick={()=>onDeleteNode(node.id)}><Trash2 className="mr-2 size-3"/>Delete node</Button>
+ </div>;
}
diff --git a/frontend/slices/workflows/components/workflow-node-palette.tsx b/frontend/slices/workflows/components/workflow-node-palette.tsx
new file mode 100644
index 00000000..34ccb196
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-node-palette.tsx
@@ -0,0 +1,16 @@
+"use client";
+import { useEffect, useMemo, useState } from "react";
+import { Plus, Search } from "lucide-react";
+import type { WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";
+import type { WorkflowNodeCatalogItem } from "@/lib/workflow/node-catalog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { listNodeCatalog } from "../lib/api";
+export function WorkflowNodePalette({onAdd}:{onAdd:(type:WorkflowGraphNodeType,defaults:Record<string,unknown>)=>void}){
+ const[open,setOpen]=useState(false),[query,setQuery]=useState(""),[items,setItems]=useState<WorkflowNodeCatalogItem[]>([]);
+ useEffect(()=>{let cancelled=false;void listNodeCatalog().then((rows)=>{if(!cancelled)setItems(rows);}).catch(()=>undefined);return()=>{cancelled=true;};},[]);
+ const filtered=useMemo(()=>{const q=query.toLowerCase().trim();return items.filter((item)=>!q||`${item.title} ${item.type} ${item.category} ${item.description}`.toLowerCase().includes(q));},[items,query]);
+ return <Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button size="sm" variant="outline"><Plus className="mr-1 size-3"/>Node</Button></PopoverTrigger><PopoverContent align="start" className="w-80 p-2"><div className="relative mb-2"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="pl-7" placeholder="Search nodes…" value={query} onChange={(e)=>setQuery(e.target.value)}/></div><ScrollArea className="h-80"><div className="space-y-1">{filtered.map((item)=><button key={item.type} type="button" className="w-full rounded-md border p-2 text-left hover:bg-accent" onClick={()=>{onAdd(item.type,item.defaults);setOpen(false);setQuery("");}}><div className="flex items-center justify-between gap-2"><span className="text-xs font-semibold">{item.title}</span><span className="text-[10px] text-muted-foreground">{item.category}</span></div><p className="mt-1 text-[11px] text-muted-foreground">{item.description}</p></button>)}</div></ScrollArea></PopoverContent></Popover>;
+}
diff --git a/frontend/slices/workflows/components/workflow-run-history.tsx b/frontend/slices/workflows/components/workflow-run-history.tsx
new file mode 100644
index 00000000..2b621471
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-run-history.tsx
@@ -0,0 +1,13 @@
+"use client";
+import { useEffect, useState } from "react";
+import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { listRuns, runStatus } from "../lib/api";
+export function WorkflowRunHistory({graph,onSelect}:{graph:WorkflowGraph;onSelect:(run:WorkflowGraphRun)=>void}){
+ const[rows,setRows]=useState<Awaited<ReturnType<typeof listRuns>>["runs"]>([]),[loading,setLoading]=useState(false);
+ const load=async()=>{setLoading(true);try{setRows((await listRuns(graph.id)).runs);}finally{setLoading(false);}};
+ useEffect(()=>{let cancelled=false;void Promise.resolve().then(()=>listRuns(graph.id)).then((value)=>{if(!cancelled)setRows(value.runs);}).finally(()=>{if(!cancelled)setLoading(false);});return()=>{cancelled=true;};},[graph.id]);
+ return <ScrollArea className="h-full"><div className="space-y-2 p-3"><div className="flex items-center justify-between"><span className="text-xs font-semibold">Execution history</span><Button size="sm" variant="ghost" disabled={loading} onClick={()=>void load()}>Refresh</Button></div>{rows.length===0&&<p className="text-xs text-muted-foreground">No executions yet.</p>}{rows.map((row)=><button key={row.id} type="button" className="w-full rounded-lg border p-2 text-left" onClick={()=>void runStatus(row.id).then(onSelect)}><div className="flex items-center justify-between gap-2"><span className="truncate text-xs font-medium">{new Date(row.startedAt).toLocaleString()}</span><Badge variant="outline">{row.state}</Badge></div><div className="mt-1 text-[10px] text-muted-foreground">{row.trigger?.type??"manual"}{row.failedNodeName?` · ${row.failedNodeName}`:""}</div></button>)}</div></ScrollArea>;
+}
diff --git a/frontend/slices/workflows/components/workflow-run-panel.tsx b/frontend/slices/workflows/components/workflow-run-panel.tsx
index 36ab8c41..22099ff2 100644
--- a/frontend/slices/workflows/components/workflow-run-panel.tsx
+++ b/frontend/slices/workflows/components/workflow-run-panel.tsx
@@ -1,14 +1,5 @@
"use client";
import type { WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
-
-export function WorkflowRunPanel({ run }: { run: WorkflowGraphRun | null }) {
- if (!run) return <div className="p-4 text-xs text-muted-foreground">Run a workflow to inspect node-by-node receipts.</div>;
- return <ScrollArea className="h-full"><div className="space-y-2 p-3">
- <div className="rounded-lg border p-3 text-xs"><div className="font-semibold">{run.graphName}</div><div className="mt-1 text-muted-foreground">{run.state}{run.failedNodeName ? ` · failed at ${run.failedNodeName}` : ""}</div></div>
- {run.nodes.map((node) => <details key={node.id} className="rounded-lg border p-2" open={node.state === "failed"}>
- <summary className="cursor-pointer text-xs font-medium">{node.name} <span className="text-muted-foreground">· {node.state}{node.durationMs != null ? ` · ${node.durationMs}ms` : ""}</span></summary>
- <div className="mt-2 space-y-1 font-mono text-[10px] text-muted-foreground">{node.logs.map((log, i) => <div key={i}>{log}</div>)}{node.error && <div>{node.error}</div>}{node.output !== undefined && <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-muted p-2">{JSON.stringify(node.output, null, 2)}</pre>}</div>
- </details>)}
- </div></ScrollArea>;
-}
+export function WorkflowRunPanel({run}:{run:WorkflowGraphRun|null}){if(!run)return <div className="p-4 text-xs text-muted-foreground">Run a workflow or select execution history to inspect node-by-node receipts.</div>;return <ScrollArea className="h-full"><div className="space-y-2 p-3"><div className="rounded-lg border p-3 text-xs"><div className="flex items-center justify-between gap-2"><div className="font-semibold">{run.graphName}</div><Badge variant="outline">{run.state}</Badge></div><div className="mt-1 text-muted-foreground">{run.trigger?.type??"manual"}{run.failedNodeName?` · failed at ${run.failedNodeName}`:""}</div></div>{run.nodes.map((node)=><details key={node.id} className="rounded-lg border p-2" open={node.state==="failed"||node.state==="running"}><summary className="cursor-pointer text-xs font-medium">{node.name} <span className="text-muted-foreground">· {node.state}{node.attempts&&node.attempts>1?` · ${node.attempts} attempts`:""}{node.durationMs!=null?` · ${node.durationMs}ms`:""}</span></summary><div className="mt-2 space-y-1 font-mono text-[10px] text-muted-foreground">{node.logs.map((log,i)=><div key={i}>{log}</div>)}{node.error&&<div className="text-destructive">{node.error}</div>}{node.output!==undefined&&<pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-muted p-2">{JSON.stringify(node.output,null,2)}</pre>}</div></details>)}</div></ScrollArea>;}
diff --git a/frontend/slices/workflows/components/workflow-variable-panel.tsx b/frontend/slices/workflows/components/workflow-variable-panel.tsx
new file mode 100644
index 00000000..b371c4b3
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-variable-panel.tsx
@@ -0,0 +1,9 @@
+"use client";
+import { useEffect, useState } from "react";
+import { Trash2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Switch } from "@/components/ui/switch";
+import { deleteVariable, listVariables, setVariable } from "../lib/api";
+export function WorkflowVariablePanel(){const[rows,setRows]=useState<Awaited<ReturnType<typeof listVariables>>>([]),[key,setKey]=useState(""),[value,setValue]=useState(""),[secret,setSecret]=useState(false),[error,setError]=useState("");const load=async()=>setRows(await listVariables());useEffect(()=>{let cancelled=false;void listVariables().then((v)=>{if(!cancelled)setRows(v);}).catch((e)=>{if(!cancelled)setError(e instanceof Error?e.message:"Could not load variables");});return()=>{cancelled=true;};},[]);const save=async()=>{try{let parsed:unknown=value;try{parsed=JSON.parse(value);}catch{}await setVariable(key.toUpperCase(),parsed,secret);setKey("");setValue("");setSecret(false);await load();}catch(e){setError(e instanceof Error?e.message:"Save failed");}};return <ScrollArea className="h-full"><div className="space-y-3 p-3"><div><div className="text-xs font-semibold">Private variables</div><p className="mt-1 text-[10px] text-muted-foreground">Use {`{"$var":"KEY"}`} in node config. Secret values are never returned by the API.</p></div><Input placeholder="KEY" value={key} onChange={(e)=>setKey(e.target.value.toUpperCase())}/><Input type={secret?"password":"text"} placeholder="Value or JSON" value={value} onChange={(e)=>setValue(e.target.value)}/><label className="flex items-center justify-between text-xs"><span>Secret</span><Switch checked={secret} onCheckedChange={setSecret}/></label><Button size="sm" disabled={!key||!value} onClick={()=>void save()}>Save variable</Button>{error&&<p className="text-xs text-destructive">{error}</p>}<div className="space-y-1">{rows.map((row)=><div key={row.key} className="flex items-center justify-between rounded border p-2"><div><div className="text-xs font-medium">{row.key}</div><div className="text-[10px] text-muted-foreground">{row.secret?"secret":JSON.stringify(row.value)}</div></div><Button size="icon" variant="ghost" onClick={()=>void deleteVariable(row.key).then(load)}><Trash2 className="size-3"/></Button></div>)}</div></div></ScrollArea>;}
diff --git a/frontend/slices/workflows/components/workflow-version-panel.tsx b/frontend/slices/workflows/components/workflow-version-panel.tsx
new file mode 100644
index 00000000..df42b398
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-version-panel.tsx
@@ -0,0 +1,12 @@
+"use client";
+import { useEffect, useState } from "react";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { Button } from "@/components/ui/button";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { listVersions, restoreVersion } from "../lib/api";
+export function WorkflowVersionPanel({graph,onRestored}:{graph:WorkflowGraph;onRestored:(graph:WorkflowGraph)=>void}){
+ const[rows,setRows]=useState<Awaited<ReturnType<typeof listVersions>>>([]),[busy,setBusy]=useState(false),[error,setError]=useState("");
+ const load=async()=>setRows(await listVersions(graph.id));useEffect(()=>{let cancelled=false;void listVersions(graph.id).then((value)=>{if(!cancelled)setRows(value);});return()=>{cancelled=true;};},[graph.id]);
+ const restore=async(revision:string)=>{setBusy(true);setError("");try{const next=await restoreVersion(graph,revision);onRestored(next);await load();}catch(e){setError(e instanceof Error?e.message:"Restore failed");}finally{setBusy(false);}};
+ return <ScrollArea className="h-full"><div className="space-y-2 p-3"><div className="text-xs font-semibold">Version history</div>{error&&<p className="text-xs text-destructive">{error}</p>}{rows.map((row)=><div key={`${row.savedAt}-${row.revision}`} className="rounded-lg border p-2"><div className="text-xs font-medium">{new Date(row.savedAt).toLocaleString()}</div><div className="mt-1 text-[10px] text-muted-foreground">{row.reason} · {row.nodeCount} nodes · {row.revision.slice(0,8)}</div>{row.revision!==graph.revision&&<Button className="mt-2" size="sm" variant="outline" disabled={busy} onClick={()=>void restore(row.revision)}>Restore</Button>}</div>)}</div></ScrollArea>;
+}
diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.ts
index 4fb3adaf..598d3e13 100644
--- a/frontend/slices/workflows/lib/api.ts
+++ b/frontend/slices/workflows/lib/api.ts
@@ -1,21 +1,23 @@
-import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
-
-async function json<T>(input: RequestInfo, init?: RequestInit): Promise<T> {
- const response = await fetch(input, { ...init, cache: "no-store", headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) } });
- const body = await response.json().catch(() => ({}));
- if (!response.ok) throw new Error(typeof body.error === "string" ? body.error : `request failed (${response.status})`);
- return body as T;
-}
-
-export async function listGraphs(): Promise<WorkflowGraph[]> { return (await json<{ graphs: WorkflowGraph[] }>("/api/v1/workflows")).graphs; }
-export async function getGraph(id: string): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>(`/api/v1/workflows?graph_id=${encodeURIComponent(id)}`)).graph; }
-export async function createGraph(graph: unknown): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "create", graph }) })).graph; }
-export async function updateGraph(graph: WorkflowGraph): Promise<WorkflowGraph> {
- const { revision, createdAt: _createdAt, updatedAt: _updatedAt, version: _version, ...definition } = graph;
- return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "update", graph_id: graph.id, expected_revision: revision, graph: definition }) })).graph;
-}
-export async function deleteGraph(graph: WorkflowGraph): Promise<void> { await json("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "delete", graph_id: graph.id, expected_revision: graph.revision }) }); }
-export async function cloneGraph(id: string): Promise<WorkflowGraph> { return (await json<{ graph: WorkflowGraph }>("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "clone", graph_id: id }) })).graph; }
-export async function runGraph(id: string): Promise<WorkflowGraphRun & { pollAfterMs?: number }> { return json("/api/v1/workflows", { method: "POST", body: JSON.stringify({ action: "run", graph_id: id, input: {}, idempotency_key: `ui-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` }) }); }
-export async function runStatus(id: string): Promise<WorkflowGraphRun & { pollAfterMs?: number }> { return json(`/api/v1/workflows?run_id=${encodeURIComponent(id)}&wait_ms=1500`); }
-export async function resolveNode(graphId: string, nodeId: string): Promise<{ project: string; name: string; path: string; relativePath: string }> { return json(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`); }
+import type { WorkflowGraph, WorkflowGraphRun, WorkflowGraphStatus } from "@/lib/contracts/workflow-graph";
+import type { WorkflowNodeCatalogItem } from "@/lib/workflow/node-catalog";
+async function json<T>(input:RequestInfo,init?:RequestInit):Promise<T>{const response=await fetch(input,{...init,cache:"no-store",headers:{"Content-Type":"application/json",...(init?.headers??{})}}),body=await response.json().catch(()=>({}));if(!response.ok)throw new Error(typeof body.error==="string"?body.error:`request failed (${response.status})`);return body as T;}
+const post=<T>(body:Record<string,unknown>)=>json<T>("/api/v1/workflows",{method:"POST",body:JSON.stringify(body)});
+export async function listGraphs(){return(await json<{graphs:WorkflowGraph[]}>("/api/v1/workflows")).graphs;}
+export async function getGraph(id:string){return(await json<{graph:WorkflowGraph}>(`/api/v1/workflows?graph_id=${encodeURIComponent(id)}`)).graph;}
+export async function createGraph(graph:unknown){return(await post<{graph:WorkflowGraph}>({action:"create",graph})).graph;}
+export async function updateGraph(graph:WorkflowGraph){const{revision,createdAt:_c,updatedAt:_u,version:_v,...definition}=graph;return(await post<{graph:WorkflowGraph}>({action:"update",graph_id:graph.id,expected_revision:revision,graph:definition})).graph;}
+export async function deleteGraph(graph:WorkflowGraph){await post({action:"delete",graph_id:graph.id,expected_revision:graph.revision});}
+export async function cloneGraph(id:string){return(await post<{graph:WorkflowGraph}>({action:"clone",graph_id:id})).graph;}
+export async function runGraph(id:string,input:Record<string,unknown>={}){return post<WorkflowGraphRun&{pollAfterMs?:number}>({action:"run",graph_id:id,input,idempotency_key:`ui-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});}
+export async function runStatus(id:string){return json<WorkflowGraphRun&{pollAfterMs?:number}>(`/api/v1/workflows?run_id=${encodeURIComponent(id)}&wait_ms=1500`);}
+export async function listRuns(graphId?:string,state?:WorkflowGraphStatus|string,offset=0){const q=new URLSearchParams({runs:"1",limit:"30",offset:String(offset)});if(graphId)q.set("graph_id",graphId);if(state)q.set("state",state);return json<{total:number;runs:Array<Pick<WorkflowGraphRun,"id"|"graphId"|"graphRevision"|"graphName"|"state"|"startedAt"|"updatedAt"|"finishedAt"|"failedNodeId"|"failedNodeName"|"trigger">>;nextOffset?:number}>(`/api/v1/workflows?${q}`);}
+export async function listVersions(graphId:string){return(await json<{versions:Array<{revision:string;savedAt:string;reason:string;name:string;nodeCount:number}>}>(`/api/v1/workflows?versions=${encodeURIComponent(graphId)}`)).versions;}
+export async function restoreVersion(graph:WorkflowGraph,revision:string){return(await post<{graph:WorkflowGraph}>({action:"restore_version",graph_id:graph.id,expected_revision:graph.revision,revision})).graph;}
+export async function listNodeCatalog(query=""){return(await json<{nodes:WorkflowNodeCatalogItem[]}>(`/api/v1/workflows?catalog=1&q=${encodeURIComponent(query)}`)).nodes;}
+export async function listTemplates(){return(await json<{templates:Array<{id:string;title:string;description:string;tags:string[];nodeCount:number}>}>("/api/v1/workflows?templates=1")).templates;}
+export async function createFromTemplate(id:string){return(await post<{graph:WorkflowGraph}>({action:"create_from_template",template_id:id})).graph;}
+export async function listVariables(){return(await json<{variables:Array<{key:string;secret:boolean;updatedAt:string;value?:unknown}>}>("/api/v1/workflows?variables=1")).variables;}
+export async function setVariable(key:string,value:unknown,secret=false){return post({action:"variable_set",key,value,secret});}
+export async function deleteVariable(key:string){return post({action:"variable_delete",key});}
+export async function aiSuggest(prompt:string){return(await post<{definition:Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">}>({action:"ai_suggest",prompt})).definition;}
+export async function resolveNode(graphId:string,nodeId:string){return json<{project:string;name:string;path:string;relativePath:string}>(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`);}
diff --git a/instrumentation.ts b/instrumentation.ts
index 32981e59..1728a2a4 100644
--- a/instrumentation.ts
+++ b/instrumentation.ts
@@ -16,6 +16,9 @@ export async function register() {
import("./lib/agent/session-archive")
.then(({ pruneAgentSessionArchives }) => pruneAgentSessionArchives())
.catch(() => undefined),
+ Promise.all([import("./lib/workflow/graph-triggers"), import("./lib/mcp/tools")])
+ .then(([{ startWorkflowScheduler }, { TOOLS_BY_NAME }]) => startWorkflowScheduler((name) => TOOLS_BY_NAME.get(name)))
+ .catch(() => undefined),
]);
// systemd liveness: when the unit sets WatchdogSec, systemd exposes
// NOTIFY_SOCKET + WATCHDOG_USEC. Node has no native AF_UNIX SOCK_DGRAM
diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.ts
index 89f46f33..eb87aa66 100644
--- a/lib/contracts/workflow-graph.ts
+++ b/lib/contracts/workflow-graph.ts
@@ -1,6 +1,6 @@
export const WORKFLOW_GRAPH_NODE_TYPES = [
- "manual", "tool", "project_function", "project_mcp", "script", "agent", "subflow",
- "condition", "project", "folder", "skill", "knowledge", "output",
+ "manual", "schedule", "webhook", "tool", "project_function", "project_mcp", "integration", "script", "agent", "subflow",
+ "condition", "switch", "merge", "batch", "loop", "wait", "project", "folder", "skill", "knowledge", "output",
] as const;
export type WorkflowGraphNodeType = (typeof WORKFLOW_GRAPH_NODE_TYPES)[number];
export type WorkflowGraphStatus = "draft" | "active" | "archived";
@@ -26,10 +26,13 @@ export type WorkflowGraphMetadata = {
intent?: string;
normalizedIntent?: string;
project?: string;
- provenance?: "user" | "learned-from-session" | "clone" | "import";
+ provenance?: "user" | "learned-from-session" | "clone" | "import" | "template" | "ai-assisted";
fingerprint?: string;
sourceDigests?: string[];
tags?: string[];
+ folder?: string;
+ errorWorkflowId?: string;
+ timezone?: string;
};
export type WorkflowGraph = {
@@ -60,6 +63,8 @@ export type WorkflowGraphRunNode = {
output?: unknown;
error?: string;
logs: string[];
+ attempts?: number;
+ waitingUntil?: string;
};
export type WorkflowGraphRun = {
@@ -72,7 +77,7 @@ export type WorkflowGraphRun = {
graphName: string;
idempotencyKey: string;
fingerprint: string;
- state: "running" | "completed" | "failed" | "interrupted";
+ state: "running" | "completed" | "completed_with_errors" | "failed" | "interrupted";
startedAt: string;
updatedAt: string;
finishedAt?: string;
@@ -82,4 +87,6 @@ export type WorkflowGraphRun = {
pid: number;
instance: string;
nodes: WorkflowGraphRunNode[];
+ trigger?: { type: "manual" | "schedule" | "webhook" | "system"; nodeId?: string; receivedAt: string };
+ ancestry?: string[];
};
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 9494a816..31458bb4 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -3,8 +3,13 @@ import { startFlow, flowStatus } from "@/lib/workflow/automation-engine";
import { BUILTIN_FLOWS } from "@/lib/workflow/automation-builtins";
import { manageProjectFlow } from "@/lib/host/project-flow-manifest";
import { type McpTool, S, str } from "./tool-kit";
-import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph } from "@/lib/workflow/graph-store";
+import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph, workflowGraphOwner } from "@/lib/workflow/graph-store";
import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";
+import { listWorkflowGraphRuns } from "@/lib/workflow/graph-run-store";
+import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workflow/graph-version-store";
+import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";
+import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";
+import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";
const project = { type: "string", maxLength: 4096 };
const flow = { type: "string", maxLength: 64 };
@@ -50,18 +55,27 @@ export const FLOW_TOOLS: McpTool[] = [
return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });
} },
{ name: "workflow_graph", title: "Workflow Graph", scope: "exec", limit: { key: "workflow.graph", max: 20, windowMs: 60_000 },
- description: "Private Workflow Graph v2 CRUD/run/status. Use action list|get|create|update|delete|clone|run|status. Definitions reject secrets; runs keep per-node receipts.",
+ description: "Private workflow graph CRUD/run plus history, versions, templates, catalog and variable references. Definitions reject embedded secrets.",
chatgptDescription: "CRUD/run workflows; read node logs.",
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "id" },
- inputSchema: S({ action: { type: "string", enum: ["list", "get", "create", "update", "delete", "clone", "run", "status"] }, id: { type: "string", maxLength: 96 }, data: { type: "object", additionalProperties: true }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["action"]),
+ inputSchema: S({ action: { type: "string", minLength: 1, maxLength: 32 }, id: { type: "string", maxLength: 96 }, data: { type: "object", additionalProperties: true }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["action"]),
run: async (a, context) => {
const principal = privateGraphPrincipal(context), action = str(a, "action");
const data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};
if (action === "list") { const graphs = await listWorkflowGraphs(principal); return { graphs: graphs.map(graph => ({ id: graph.id, name: graph.name, status: graph.status, revision: graph.revision, nodeCount: graph.nodes.length, updatedAt: graph.updatedAt, provenance: graph.metadata.provenance, project: graph.metadata.project })) }; }
if (action === "status") return workflowGraphRunStatus(principal, str(a, "id"), Number(a.wait_ms) || 0);
+ if (action === "runs") return listWorkflowGraphRuns(workflowGraphOwner(principal), { graphId: typeof data.graph_id === "string" ? data.graph_id : undefined, limit: Number(data.limit) || 30, offset: Number(data.offset) || 0 });
+ if (action === "catalog") return { nodes: workflowNodeCatalog(typeof data.query === "string" ? data.query : "") };
+ if (action === "templates") return { templates: workflowTemplates() };
+ if (action === "variables") return { variables: await listWorkflowVariables(principal) };
+ if (action === "variable_set") return setWorkflowVariable(principal, String(data.key ?? ""), data.value, data.secret === true);
+ if (action === "variable_delete") return deleteWorkflowVariable(principal, String(data.key ?? ""));
+ if (action === "create_from_template") { const row = workflowTemplate(String(data.template_id ?? "")); if (!row) throw new Error("workflow template not found"); return { graph: await createWorkflowGraph(principal, row.definition, "template") }; }
if (action === "create") return { graph: await createWorkflowGraph(principal, data.definition ?? data) };
const id = str(a, "id");
if (action === "get") { const graph = await getWorkflowGraph(principal, id); if (!graph) throw new Error("workflow graph not found"); return { graph }; }
+ if (action === "versions") return { versions: await listWorkflowGraphVersions(workflowGraphOwner(principal), id) };
+ if (action === "restore") { const current = await getWorkflowGraph(principal, id), snapshot = await readWorkflowGraphVersion(workflowGraphOwner(principal), id, String(data.version ?? "")); if (!current || !snapshot) throw new Error("workflow graph/version not found"); const { revision: _r, createdAt: _c, updatedAt: _u, version: _v, ...definition } = snapshot.graph; return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? current.revision), definition, "restore") }; }
if (action === "clone") return { graph: await cloneWorkflowGraph(principal, id) };
if (action === "update") return { graph: await updateWorkflowGraph(principal, id, String(data.revision ?? ""), data.definition) };
if (action === "delete") return deleteWorkflowGraph(principal, id, String(data.revision ?? ""));
diff --git a/lib/workflow/ai-assist.ts b/lib/workflow/ai-assist.ts
new file mode 100644
index 00000000..0ba9a12b
--- /dev/null
+++ b/lib/workflow/ai-assist.ts
@@ -0,0 +1,13 @@
+import { prepareSelectedModel, streamPreparedSelectedModel } from "@/lib/ai/selected-model-stream";
+import { WORKFLOW_GRAPH_NODE_TYPES } from "@/lib/contracts/workflow-graph";
+import { parseWorkflowGraphDefinition } from "./graph-schema";
+export async function suggestWorkflowGraph(prompt:string){
+ const request=prompt.trim();if(!request||request.length>4000)throw new Error("workflow AI prompt must be 1-4000 characters");
+ const prepared=await prepareSelectedModel(),abort=new AbortController(),timer=setTimeout(()=>abort.abort(new Error("workflow AI suggestion timed out")),45_000);let text="";
+ const system=["Design one MSO workflow graph as strict JSON only. No markdown.",`Allowed node types: ${WORKFLOW_GRAPH_NODE_TYPES.join(", ")}.`,`Return keys: name, description, status, inputs, metadata, nodes, edges. Status must be draft.`,"Every node needs id,name,type,position{x,y},config. Every edge needs id,source,target and optional sourceHandle.","Never output credentials, tokens, passwords, cookies, authorization headers, or secret values. Use {$var:\"NAME\"} for runtime private variables and integration nodes for credential-backed provider actions.","Use schedule/webhook nodes only as roots. Use true/false handles for condition, named handles/default for switch, error handle for failure branches. Prefer DRY subflows and explicit output nodes."].join(" ");
+ try{await streamPreparedSelectedModel({prepared,messages:[{role:"user",text:request}],system,signal:abort.signal,emit:(event,data)=>{if(event==="delta"&&typeof data==="string"&&text.length<256*1024)text+=data;}});}finally{clearTimeout(timer);}
+ const clean=text.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,""),start=clean.indexOf("{"),end=clean.lastIndexOf("}");if(start<0||end<=start)throw new Error("workflow AI did not return JSON");
+ let raw:unknown;try{raw=JSON.parse(clean.slice(start,end+1));}catch{throw new Error("workflow AI returned invalid JSON");}
+ if(!raw||typeof raw!=="object"||Array.isArray(raw))throw new Error("workflow AI returned invalid graph");const row=raw as Record<string,unknown>,metadata=row.metadata&&typeof row.metadata==="object"&&!Array.isArray(row.metadata)?row.metadata as Record<string,unknown>:{};
+ return parseWorkflowGraphDefinition({...row,status:"draft",metadata:{...metadata,provenance:"ai-assisted"}});
+}
diff --git a/lib/workflow/graph-bindings.ts b/lib/workflow/graph-bindings.ts
new file mode 100644
index 00000000..4b6f37fa
--- /dev/null
+++ b/lib/workflow/graph-bindings.ts
@@ -0,0 +1,39 @@
+import { graphObject } from "./graph-schema";
+export function workflowPath(root: unknown, ref: string): unknown {
+ const parts = ref.split(".");
+ if (!parts.length || parts.length > 16 || parts.some((part) => !/^[A-Za-z0-9_:-]+$/.test(part) || ["__proto__", "constructor", "prototype"].includes(part))) throw new Error("invalid workflow reference");
+ let value = root;
+ for (const part of parts) {
+ if ((!graphObject(value) && !Array.isArray(value)) || !Object.hasOwn(value, part)) throw new Error(`unresolved workflow reference: ${ref}`);
+ value = (value as Record<string, unknown>)[part];
+ }
+ return structuredClone(value);
+}
+export function bindWorkflowValue(value: unknown, context: unknown, variables: Record<string, unknown>, depth = 0): unknown {
+ if (depth > 14) throw new Error("workflow references too deep");
+ if (Array.isArray(value)) return value.map((item) => bindWorkflowValue(item, context, variables, depth + 1));
+ if (!graphObject(value)) return value;
+ if (Object.hasOwn(value, "$ref")) {
+ if (Object.keys(value).length !== 1 || typeof value.$ref !== "string") throw new Error("workflow $ref must be the whole value");
+ return workflowPath(context, value.$ref);
+ }
+ if (Object.hasOwn(value, "$var")) {
+ if (Object.keys(value).length !== 1 || typeof value.$var !== "string") throw new Error("workflow $var must be the whole value");
+ if (!Object.hasOwn(variables, value.$var)) throw new Error(`workflow variable not found: ${value.$var}`);
+ return structuredClone(variables[value.$var]);
+ }
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, bindWorkflowValue(child, context, variables, depth + 1)]));
+}
+export function bindLoopItem(value: unknown, item: unknown, index: number, depth = 0): unknown {
+ if (depth > 14) throw new Error("loop bindings too deep");
+ if (Array.isArray(value)) return value.map((child) => bindLoopItem(child, item, index, depth + 1));
+ if (!graphObject(value)) return value;
+ if (Object.hasOwn(value, "$item")) {
+ if (Object.keys(value).length !== 1) throw new Error("$item must be the whole value");
+ if (value.$item === true || value.$item === "") return structuredClone(item);
+ if (typeof value.$item !== "string") throw new Error("invalid $item binding");
+ return workflowPath({ item }, `item.${value.$item}`);
+ }
+ if (Object.hasOwn(value, "$index")) return index;
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, bindLoopItem(child, item, index, depth + 1)]));
+}
diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.ts
index 11f465c9..ec949b18 100644
--- a/lib/workflow/graph-engine.test.ts
+++ b/lib/workflow/graph-engine.test.ts
@@ -46,4 +46,58 @@ describe("workflow graph engine", () => {
it("keeps run receipts private to the principal", async () => {
await expect(workflowGraphRunStatus("another-owner", "0".repeat(32))).rejects.toThrow("not found");
});
+
+ it("retries a bounded action and records attempts", async () => {
+ let calls = 0;
+ const graph = await createWorkflowGraph("graph-owner", { name: "Retry", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "start3", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "retry", name: "Retry tool", type: "tool", position: { x: 100, y: 0 }, config: { tool: "fixture_retry", arguments: {}, retry: { maxAttempts: 3, backoffMs: 0 } } },
+ { id: "after3", name: "After", type: "output", position: { x: 200, y: 0 }, config: {} },
+ ], edges: [{ id: "r1", source: "start3", target: "retry" }, { id: "r2", source: "retry", target: "after3" }] });
+ const tool: CapabilityTool = { name: "fixture_retry", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async () => { calls += 1; if (calls < 3) throw new Error("retry me"); return { ok: true }; } };
+ const started = await startWorkflowGraph(graph, {}, "retry-once", context, (name) => name === tool.name ? tool : undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("completed"); expect(calls).toBe(3); expect(done.nodes.find((node) => node.id === "retry")?.attempts).toBe(3);
+ });
+ it("routes an action failure into an explicit error branch", async () => {
+ const graph = await createWorkflowGraph("graph-owner", { name: "Handled", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "start4", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "bad4", name: "Expected failure", type: "tool", position: { x: 100, y: 0 }, config: { tool: "fixture_error", arguments: {} } },
+ { id: "handled", name: "Handled", type: "output", position: { x: 200, y: 0 }, config: { value: { handled: true } } },
+ ], edges: [{ id: "h1", source: "start4", target: "bad4" }, { id: "h2", source: "bad4", target: "handled", sourceHandle: "error" }] });
+ const tool: CapabilityTool = { name: "fixture_error", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async () => { throw new Error("expected failure"); } };
+ const started = await startWorkflowGraph(graph, {}, "handled-once", context, (name) => name === tool.name ? tool : undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("completed_with_errors"); expect(done.nodes.find((node) => node.id === "bad4")?.state).toBe("failed"); expect(done.nodes.find((node) => node.id === "handled")?.state).toBe("completed");
+ });
+ it("redacts private secret variable values from receipts", async () => {
+ const { setWorkflowVariable } = await import("./variables"); await setWorkflowVariable("graph-owner", "API_TOKEN", "top-secret-value", true);
+ const graph = await createWorkflowGraph("graph-owner", { name: "Secret", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "start5", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "echo", name: "Echo", type: "tool", position: { x: 100, y: 0 }, config: { tool: "fixture_echo", arguments: { value: { $var: "API_TOKEN" } } } },
+ ], edges: [{ id: "s1", source: "start5", target: "echo" }] });
+ const tool: CapabilityTool = { name: "fixture_echo", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async (args) => args };
+ const started = await startWorkflowGraph(graph, {}, "secret-once", context, (name) => name === tool.name ? tool : undefined);
+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000), receipt = JSON.stringify(done);
+ expect(receipt).not.toContain("top-secret-value"); expect(receipt).toContain("[REDACTED]");
+ });
+
+ it("runs another workflow graph as a reusable subflow and blocks recursion", async () => {
+ const child = await createWorkflowGraph("graph-owner", { name: "Child", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "child-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "child-out", name: "Out", type: "output", position: { x: 120, y: 0 }, config: { value: { child: true } } },
+ ], edges: [{ id: "child-e", source: "child-start", target: "child-out" }] });
+ let parent = await createWorkflowGraph("graph-owner", { name: "Parent", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "parent-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "child", name: "Child", type: "subflow", position: { x: 120, y: 0 }, config: { workflowId: child.id } },
+ { id: "parent-out", name: "Out", type: "output", position: { x: 240, y: 0 }, config: {} },
+ ], edges: [{ id: "parent-e1", source: "parent-start", target: "child" }, { id: "parent-e2", source: "child", target: "parent-out" }] });
+ const started = await startWorkflowGraph(parent, {}, "subflow-once", context, () => undefined), done = await workflowGraphRunStatus("graph-owner", started.id, 5000);
+ expect(done.state).toBe("completed"); expect(done.nodes.find((node) => node.id === "child")?.state).toBe("completed");
+ const { version: _v, createdAt: _c, updatedAt: _u, revision: _r, ...definition } = parent;
+ definition.nodes = definition.nodes.map((node) => node.id === "child" ? { ...node, config: { workflowId: parent.id } } : node);
+ parent = await (await import("./graph-store")).updateWorkflowGraph("graph-owner", parent.id, parent.revision, definition);
+ const recursive = await startWorkflowGraph(parent, {}, "subflow-recursive", context, () => undefined), recursiveDone = await workflowGraphRunStatus("graph-owner", recursive.id, 5000);
+ expect(recursiveDone.state).toBe("failed"); expect(recursiveDone.nodes.find((node) => node.id === "child")?.error).toContain("recursive");
+ });
});
diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.ts
index 7f8edb58..f2236c6a 100644
--- a/lib/workflow/graph-engine.ts
+++ b/lib/workflow/graph-engine.ts
@@ -6,110 +6,56 @@ import { assertWorkflowMetadataOnly, graphObject } from "./graph-schema";
import { workflowGraphOwner } from "./graph-store";
import { compact, executeNode } from "./graph-runtime";
import { lockWorkflowGraphRun, pruneWorkflowGraphRuns, publicWorkflowGraphRun, readWorkflowGraphRun, writeWorkflowGraphRun } from "./graph-run-store";
+import { workflowSecretValues } from "./variables";
const state = globalThis as typeof globalThis & { msoGraphInstance?: string; msoGraphPending?: Map<string, Promise<void>> };
const INSTANCE = state.msoGraphInstance ??= randomUUID();
const pending = state.msoGraphPending ??= new Map<string, Promise<void>>();
type Resolver = (name: string) => CapabilityTool | undefined;
-
+export type WorkflowRunTrigger = WorkflowGraphRun["trigger"];
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
-function canonical(value: unknown): string {
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
- if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`).join(",")}}`;
- return JSON.stringify(value);
-}
-function inputObject(raw: unknown): Record<string, unknown> {
- if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("workflow graph input must be an object up to 64 KiB");
- assertWorkflowMetadataOnly(raw); return structuredClone(raw);
-}
+function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (value && typeof value === "object") return `{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`; return JSON.stringify(value); }
+function inputObject(raw: unknown): Record<string, unknown> { if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("workflow graph input must be an object up to 64 KiB"); assertWorkflowMetadataOnly(raw); return structuredClone(raw); }
+function retryPolicy(node: WorkflowGraph["nodes"][number]) { const raw = graphObject(node.config.retry) ? node.config.retry : {}; return { maxAttempts: Math.max(1, Math.min(5, Math.trunc(Number(raw.maxAttempts) || 1))), backoffMs: Math.max(0, Math.min(30_000, Math.trunc(Number(raw.backoffMs) || 0))) }; }
+function sleep(ms:number){return ms?new Promise((resolve)=>setTimeout(resolve,ms)):Promise.resolve();}
+function secretText(text:string,secrets:string[]){let out=text;for(const value of secrets)out=out.split(value).join("[REDACTED]");return out;}
+function secretValue(value:unknown,secrets:string[],depth=0):unknown{if(depth>14)return "[TRUNCATED]";if(typeof value==="string")return secretText(value,secrets);if(Array.isArray(value))return value.map((item)=>secretValue(item,secrets,depth+1));if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,child])=>[key,secretValue(child,secrets,depth+1)]));return value;}
async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<void> {
- const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {};
- const edgeState = new Map(graph.edges.map((edge) => [edge.id, "pending" as "pending" | "enabled" | "disabled"]));
- const incoming = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.target === node.id)]));
- const outgoing = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.source === node.id)]));
- const disableOutgoing = (nodeId: string) => { for (const edge of outgoing.get(nodeId) ?? []) if (edgeState.get(edge.id) === "pending") edgeState.set(edge.id, "disabled"); };
- const resolveOutgoing = (nodeId: string, branch?: boolean) => {
- for (const edge of outgoing.get(nodeId) ?? []) {
- if (branch === undefined || !edge.sourceHandle) edgeState.set(edge.id, "enabled");
- else edgeState.set(edge.id, edge.sourceHandle === String(branch) ? "enabled" : "disabled");
- }
- };
-
+ const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {}, secrets = await workflowSecretValues(context.principal ?? context.actor ?? ""), edgeState = new Map(graph.edges.map((edge) => [edge.id, "pending" as "pending"|"enabled"|"disabled"]));
+ const incoming = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.target===node.id)])), outgoing = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.source===node.id)]));
+ const disableOutgoing=(id:string)=>{for(const edge of outgoing.get(id)??[])if(edgeState.get(edge.id)==="pending")edgeState.set(edge.id,"disabled");};
+ const resolveOutgoing=(id:string,handles?:string[])=>{for(const edge of outgoing.get(id)??[]){const enabled=handles?Boolean(edge.sourceHandle&&handles.includes(edge.sourceHandle)):!edge.sourceHandle;edgeState.set(edge.id,enabled?"enabled":"disabled");}};
+ let handledErrors=false;
try {
- let remaining = new Set(graph.nodes.map((node) => node.id));
- while (remaining.size) {
- if (Date.now() - Date.parse(run.startedAt) > 15 * 60_000) throw new Error("workflow graph exceeded 15 minutes; remaining nodes were not started");
- let progressed = false;
- for (const node of graph.nodes) {
- if (!remaining.has(node.id)) continue;
- const deps = incoming.get(node.id) ?? [];
- if (deps.some((edge) => edgeState.get(edge.id) === "pending")) continue;
- const row = rows.get(node.id)!;
- if (node.disabled || (deps.length > 0 && deps.every((edge) => edgeState.get(edge.id) === "disabled"))) {
- row.state = "skipped"; row.finishedAt = new Date().toISOString(); row.logs.push(node.disabled ? "Node disabled by workflow definition." : "Skipped because no incoming branch was selected.");
- disableOutgoing(node.id); remaining.delete(node.id); progressed = true; run.updatedAt = new Date().toISOString(); await writeWorkflowGraphRun(run); continue;
- }
- row.state = "running"; row.startedAt = new Date().toISOString(); row.logs.push("Node started."); run.updatedAt = row.startedAt; await writeWorkflowGraphRun(run);
- const started = Date.now();
- try {
- const result = await executeNode(node, run, graph, input, outputs, context, resolve);
- row.output = compact(result.output); row.state = "completed"; outputs[node.id] = result.output;
- if (result.log) row.logs.push(result.log); resolveOutgoing(node.id, result.branch);
- } catch (error) {
- row.state = "failed"; row.error = redactText(error instanceof Error ? error.message : "node failed", 800); row.logs.push(row.error);
- run.failedNodeId = node.id; run.failedNodeName = node.name; run.error = row.error; run.state = "failed";
- for (const pendingId of remaining) {
- if (pendingId === node.id) continue;
- const blocked = rows.get(pendingId)!; if (blocked.state === "queued") { blocked.state = "blocked"; blocked.logs.push(`Blocked by failed node ${node.name}.`); }
- }
- throw error;
- } finally {
- row.durationMs = Date.now() - started; row.finishedAt = new Date().toISOString(); run.updatedAt = row.finishedAt; await writeWorkflowGraphRun(run);
- }
- remaining.delete(node.id); progressed = true;
+ const remaining=new Set(graph.nodes.map((node)=>node.id));
+ while(remaining.size){
+ if(Date.now()-Date.parse(run.startedAt)>15*60_000)throw new Error("workflow graph exceeded 15 minutes; remaining nodes were not started");
+ let progressed=false;
+ for(const node of graph.nodes){
+ if(!remaining.has(node.id))continue; const deps=incoming.get(node.id)??[]; if(deps.some((edge)=>edgeState.get(edge.id)==="pending"))continue; const row=rows.get(node.id)!;
+ const triggerNode=["manual","schedule","webhook"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}
+ row.state="running";row.startedAt=new Date().toISOString();row.logs.push("Node started.");run.updatedAt=row.startedAt;await writeWorkflowGraphRun(run); const started=Date.now(),policy=retryPolicy(node); let failure:unknown;
+ for(let attempt=1;attempt<=policy.maxAttempts;attempt+=1){row.attempts=attempt;try{const result=await executeNode(node,run,graph,input,outputs,context,resolve);row.output=compact(secretValue(result.output,secrets));outputs[node.id]=result.output;row.state="completed";if(result.log)row.logs.push(result.log);resolveOutgoing(node.id,result.handles);failure=undefined;break;}catch(error){failure=error;row.logs.push(`Attempt ${attempt}/${policy.maxAttempts} failed: ${secretText(redactText(error instanceof Error?error.message:"node failed",500),secrets)}`);if(attempt<policy.maxAttempts)await sleep(Math.min(30_000,policy.backoffMs*Math.max(1,2**(attempt-1))));}}
+ if(failure){row.state="failed";row.error=secretText(redactText(failure instanceof Error?failure.message:"node failed",800),secrets);outputs[node.id]={error:row.error};const errorEdges=(outgoing.get(node.id)??[]).filter((edge)=>edge.sourceHandle==="error"),continueOnError=node.config.onError==="continue";if(errorEdges.length||continueOnError){handledErrors=true;resolveOutgoing(node.id,errorEdges.length?["error"]:undefined);row.logs.push(errorEdges.length?"Failure routed through error output.":"Failure continued by node policy.");}else{run.failedNodeId=node.id;run.failedNodeName=node.name;run.error=row.error;run.state="failed";for(const pendingId of remaining){if(pendingId===node.id)continue;const blocked=rows.get(pendingId)!;if(blocked.state==="queued"){blocked.state="blocked";blocked.logs.push(`Blocked by failed node ${node.name}.`);}}row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);throw failure;}}
+ row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);remaining.delete(node.id);progressed=true;
}
- if (!progressed && remaining.size) throw new Error("workflow graph could not make progress; inspect dependencies/branches");
+ if(!progressed&&remaining.size)throw new Error("workflow graph could not make progress; inspect dependencies/branches");
}
- run.state = "completed";
- } catch (error) {
- if (run.state !== "failed") { run.state = "failed"; run.error = redactText(error instanceof Error ? error.message : "workflow graph failed", 800); }
- }
- run.finishedAt = run.updatedAt = new Date().toISOString(); await writeWorkflowGraphRun(run);
+ run.state=handledErrors?"completed_with_errors":"completed";
+ } catch(error){if(run.state!=="failed"){run.state="failed";run.error=secretText(redactText(error instanceof Error?error.message:"workflow graph failed",800),secrets);}}
+ run.finishedAt=run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);
}
-export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string) {
- if (!(storagePrincipal ?? context.principal) || !context.sessionId) throw new Error("workflow graph requires an authenticated principal/session");
- if (graph.status === "archived") throw new Error("archived workflow graph cannot run");
- if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey)) throw new Error("idempotency_key must be 1-128 simple characters");
- const owner = workflowGraphOwner(storagePrincipal ?? context.principal!), input = inputObject(rawInput), fingerprint = hash(canonical({ graphId: graph.id, revision: graph.revision, input }));
- const id = hash(`${owner}:${idempotencyKey}`).slice(0, 32);
- return lockWorkflowGraphRun(owner, id, async () => {
- const existing = await readWorkflowGraphRun(owner, id);
- if (existing) { if (existing.fingerprint !== fingerprint) throw new Error("idempotency_key already identifies a different graph/input/revision"); return publicWorkflowGraphRun(existing); }
- await pruneWorkflowGraphRuns(owner);
- const run: WorkflowGraphRun = {
- version: 1, id, owner, sessionId: context.sessionId!, graphId: graph.id, graphRevision: graph.revision, graphName: graph.name,
- idempotencyKey, fingerprint, state: "running", startedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), pid: process.pid, instance: INSTANCE,
- nodes: graph.nodes.map((node) => ({ id: node.id, name: node.name, type: node.type, state: "queued", logs: [] })),
- };
- await writeWorkflowGraphRun(run);
- const work = execute(run, graph, input, context, resolve).catch(() => undefined).finally(() => pending.delete(id)); pending.set(id, work);
- return publicWorkflowGraphRun(run);
- });
+async function maybeRunErrorWorkflow(run:WorkflowGraphRun,graph:WorkflowGraph,context:CapabilityRunContext,resolve:Resolver,principal:string){
+ const errorId=graph.metadata.errorWorkflowId;if(run.state!=="failed"||!errorId||errorId===graph.id)return;
+ const {getWorkflowGraph}=await import("./graph-store"),errorGraph=await getWorkflowGraph(principal,errorId);if(!errorGraph||errorGraph.status==="archived")return;
+ await startWorkflowGraph(errorGraph,{error:{runId:run.id,graphId:graph.id,graphName:graph.name,nodeId:run.failedNodeId,nodeName:run.failedNodeName,message:run.error}},`error:${run.id}`,context,resolve,principal,{type:"system",receivedAt:new Date().toISOString()});
}
-
-export async function workflowGraphRunStatus(principal: string, id: string, waitMs = 0) {
- if (!Number.isSafeInteger(waitMs) || waitMs < 0 || waitMs > 25_000) throw new Error("wait_ms must be 0-25000");
- const owner = workflowGraphOwner(principal); let run = await readWorkflowGraphRun(owner, id);
- if (!run) throw new Error("workflow graph run not found for this principal");
- if (run.state === "running" && pending.has(id) && waitMs > 0) {
- let timer: ReturnType<typeof setTimeout> | undefined;
- await Promise.race([pending.get(id), new Promise((resolve) => { timer = setTimeout(resolve, waitMs); })]); clearTimeout(timer); run = await readWorkflowGraphRun(owner, id) ?? run;
- }
- if (run.state === "running" && run.instance !== INSTANCE) {
- let gone = false; try { process.kill(run.pid, 0); } catch (error) { gone = (error as NodeJS.ErrnoException).code === "ESRCH"; }
- if (gone) { run.state = "interrupted"; run.updatedAt = run.finishedAt = new Date().toISOString(); await writeWorkflowGraphRun(run); }
- }
- return publicWorkflowGraphRun(run);
+export function workflowGraphRunId(owner:string,key:string){return hash(`${owner}:${key}`).slice(0,32);}
+export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string, trigger?: WorkflowRunTrigger, ancestry: string[] = []) {
+ const principal=storagePrincipal??context.principal;if(!principal||!context.sessionId)throw new Error("workflow graph requires an authenticated principal/session");if(ancestry.includes(graph.id)||ancestry.length>=16)throw new Error("recursive workflow subflow detected");if(graph.status==="archived")throw new Error("archived workflow graph cannot run");if(!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))throw new Error("idempotency_key must be 1-128 simple characters");
+ const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey);
+ return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id]};await writeWorkflowGraphRun(run);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>pending.delete(id));pending.set(id,work);return publicWorkflowGraphRun(run);});
}
+export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}return publicWorkflowGraphRun(run);}
diff --git a/lib/workflow/graph-flow-nodes.test.ts b/lib/workflow/graph-flow-nodes.test.ts
new file mode 100644
index 00000000..3e785a55
--- /dev/null
+++ b/lib/workflow/graph-flow-nodes.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, it } from "vitest";
+import type { WorkflowGraph, WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+import { executeFlowNode } from "./graph-flow-nodes";
+const make=(type:WorkflowGraphNode["type"],config:Record<string,unknown>={}):WorkflowGraphNode=>({id:type,name:type,type,position:{x:0,y:0},config});
+const graph=(node:WorkflowGraphNode,edges:WorkflowGraph["edges"]=[]):WorkflowGraph=>({version:2,id:"g",name:"G",description:"",status:"draft",inputs:{},nodes:[node],edges,metadata:{},createdAt:"2026-01-01T00:00:00Z",updatedAt:"2026-01-01T00:00:00Z",revision:"r"});
+describe("workflow flow nodes",()=>{
+ it("routes switch handles with default fallback",async()=>{const node=make("switch",{path:"input.kind",cases:[{handle:"alpha",equals:"a"},{handle:"beta",equals:"b"}]});expect((await executeFlowNode(node,node.config,graph(node),{},{input:{kind:"b"}}))?.handles).toEqual(["beta"]);expect((await executeFlowNode(node,node.config,graph(node),{},{input:{kind:"x"}}))?.handles).toEqual(["default"]);});
+ it("merges incoming outputs by source",async()=>{const node=make("merge",{mode:"combine"}),g=graph(node,[{id:"a",source:"left",target:"merge"},{id:"b",source:"right",target:"merge"}]);expect((await executeFlowNode(node,node.config,g,{left:{a:1},right:{b:2}},{}))?.output).toEqual({left:{a:1},right:{b:2}});});
+ it("splits bounded batches",async()=>{const node=make("batch",{itemsPath:"input.items",size:2}),result=await executeFlowNode(node,node.config,graph(node),{},{input:{items:[1,2,3,4,5]}});expect(result?.output).toMatchObject({count:3,size:2,batches:[[1,2],[3,4],[5]]});});
+ it("supports zero-delay wait without timer drift",async()=>{const node=make("wait",{delayMs:0}),result=await executeFlowNode(node,node.config,graph(node),{},{});expect(result?.output).toMatchObject({waitedMs:0});});
+});
diff --git a/lib/workflow/graph-flow-nodes.ts b/lib/workflow/graph-flow-nodes.ts
new file mode 100644
index 00000000..536069e8
--- /dev/null
+++ b/lib/workflow/graph-flow-nodes.ts
@@ -0,0 +1,14 @@
+import type { WorkflowGraph, WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+import { graphObject } from "./graph-schema";
+import { workflowPath } from "./graph-bindings";
+export type FlowNodeResult={output:unknown;handles?:string[];log?:string};
+function items(config:Record<string,unknown>,runtime:unknown){const raw=Array.isArray(config.items)?config.items:typeof config.itemsPath==="string"?workflowPath(runtime,config.itemsPath):[];if(!Array.isArray(raw))throw new Error("workflow items must resolve to an array");if(raw.length>1000)throw new Error("workflow item limit is 1000");return raw;}
+export async function executeFlowNode(node:WorkflowGraphNode,config:Record<string,unknown>,graph:WorkflowGraph,outputs:Record<string,unknown>,runtime:unknown):Promise<FlowNodeResult|null>{
+ if(node.type==="condition"){const ref=typeof config.path==="string"?config.path:"input",value=workflowPath(runtime,ref),branch=Object.hasOwn(config,"equals")?JSON.stringify(value)===JSON.stringify(config.equals):Boolean(value);return{output:{value,branch},handles:[String(branch)],log:`Condition evaluated to ${branch}.`};}
+ if(node.type==="switch"){const ref=typeof config.path==="string"?config.path:"input",value=workflowPath(runtime,ref),cases=Array.isArray(config.cases)?config.cases:[],handles:string[]=[];for(let i=0;i<Math.min(32,cases.length);i++){const row=cases[i];if(!graphObject(row))continue;const handle=typeof row.handle==="string"&&row.handle?row.handle:`case-${i+1}`;if(Object.hasOwn(row,"equals")&&JSON.stringify(value)===JSON.stringify(row.equals))handles.push(handle);}if(!handles.length)handles.push("default");return{output:{value,handles},handles,log:`Switch selected ${handles.join(", ")}.`};}
+ if(node.type==="merge"){const incoming=graph.edges.filter((edge)=>edge.target===node.id).map((edge)=>({source:edge.source,value:outputs[edge.source]}));const mode=String(config.mode??"combine");let output:unknown;if(mode==="append")output=incoming.flatMap((row)=>Array.isArray(row.value)?row.value:[row.value]);else if(mode==="passThrough")output=incoming.at(-1)?.value??null;else output=Object.fromEntries(incoming.map((row)=>[row.source,row.value]));return{output,log:`Merged ${incoming.length} incoming branch(es) using ${mode}.`};}
+ if(node.type==="batch"){const all=items(config,runtime),size=Math.max(1,Math.min(1000,Math.trunc(Number(config.size)||10))),batches=[];for(let i=0;i<all.length;i+=size)batches.push(all.slice(i,i+size));return{output:{items:all,batches,count:batches.length,size},log:`Split ${all.length} item(s) into ${batches.length} batch(es).`};}
+ if(node.type==="wait"){const until=typeof config.until==="string"?Date.parse(config.until):NaN,delay=Number.isFinite(until)?until-Date.now():Number(config.delayMs??0),ms=Math.max(0,Math.min(10*60_000,Math.trunc(delay)||0));if(delay>10*60_000)throw new Error("wait node maximum is 10 minutes per run");if(ms)await new Promise((resolve)=>setTimeout(resolve,ms));return{output:{waitedMs:ms,resumedAt:new Date().toISOString()},log:`Waited ${ms}ms.`};}
+ return null;
+}
+export function workflowItems(config:Record<string,unknown>,runtime:unknown){return items(config,runtime);}
diff --git a/lib/workflow/graph-run-store.ts b/lib/workflow/graph-run-store.ts
index 1e2a6673..5446e390 100644
--- a/lib/workflow/graph-run-store.ts
+++ b/lib/workflow/graph-run-store.ts
@@ -61,6 +61,25 @@ export async function pruneWorkflowGraphRuns(owner: string): Promise<void> {
}
export function publicWorkflowGraphRun(run: WorkflowGraphRun) {
- const { owner: _owner, pid: _pid, instance: _instance, sessionId: _sessionId, fingerprint: _fingerprint, ...safe } = run;
+ const { owner: _owner, pid: _pid, instance: _instance, sessionId: _sessionId, fingerprint: _fingerprint, ancestry: _ancestry, ...safe } = run;
return { ...safe, pollAfterMs: run.state === "running" ? 1500 : 0 };
}
+
+export type WorkflowGraphRunFilter = { graphId?: string; state?: WorkflowGraphRun["state"]; limit?: number; offset?: number };
+export async function listWorkflowGraphRuns(owner: string, filter: WorkflowGraphRunFilter = {}) {
+ await ensureOwnerDir(owner);
+ const dir = path.dirname(file(owner, "0".repeat(32))), names = (await fs.readdir(dir)).filter((name) => /^[a-f0-9]{32}\.json$/.test(name));
+ const rows: WorkflowGraphRun[] = [];
+ for (const name of names.slice(0, MAX_RECEIPTS)) {
+ const row = await readWorkflowGraphRun(owner, name.slice(0, 32)).catch(() => null); if (!row) continue;
+ if (filter.graphId && row.graphId !== filter.graphId) continue;
+ if (filter.state && row.state !== filter.state) continue;
+ rows.push(row);
+ }
+ rows.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
+ const offset = Math.max(0, Math.trunc(filter.offset ?? 0)), limit = Math.max(1, Math.min(100, Math.trunc(filter.limit ?? 30)));
+ return { total: rows.length, runs: rows.slice(offset, offset + limit).map((run) => {
+ const safe = publicWorkflowGraphRun(run);
+ return { id: safe.id, graphId: safe.graphId, graphRevision: safe.graphRevision, graphName: safe.graphName, state: safe.state, startedAt: safe.startedAt, updatedAt: safe.updatedAt, finishedAt: safe.finishedAt, failedNodeId: safe.failedNodeId, failedNodeName: safe.failedNodeName, trigger: safe.trigger };
+ }), nextOffset: offset + limit < rows.length ? offset + limit : undefined };
+}
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index ab315b9f..29ff3e34 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -7,18 +7,18 @@ import { boundedResultText } from "@/lib/capabilities/result-budget";
import { resolveProjectHint } from "@/lib/host/projects-api";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun, WorkflowGraphRunNode } from "@/lib/contracts/workflow-graph";
import { graphObject } from "./graph-schema";
+import { bindLoopItem, bindWorkflowValue } from "./graph-bindings";
+import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-flow-nodes";
+import { workflowVariableValues } from "./variables";
type Resolver = (name: string) => CapabilityTool | undefined;
-type NodeExecutionResult = { output: unknown; branch?: boolean; log?: string };
-
-const BLOCKED_TOOL_NODES = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "flow_run", "flow_status"]);
+type NodeExecutionResult = FlowNodeResult;
+const BLOCKED_TOOL_NODES = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "flow_run", "flow_status", "workflow_graph"]);
function compact(value: unknown): unknown {
- try {
- return JSON.parse(boundedResultText(typeof value === "string" ? { text: value } : value, { maxTextBytes: 12 * 1024, overflowHint: "Open the underlying project/tool result for full details." }));
- } catch { return { text: String(value).slice(0, 12_000) }; }
+ try { return JSON.parse(boundedResultText(typeof value === "string" ? { text: value } : value, { maxTextBytes: 12 * 1024, overflowHint: "Open the underlying project/tool result for full details." })); }
+ catch { return { text: String(value).slice(0, 12_000) }; }
}
-
function resultData(result: unknown): unknown {
if (capabilityReportedFailure(result)) throw new Error("downstream tool reported an error");
if (!isCapabilityDirectResult(result)) return result;
@@ -27,112 +27,80 @@ function resultData(result: unknown): unknown {
const text = result.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
try { return JSON.parse(text); } catch { return { text }; }
}
-
-function safePath(root: unknown, ref: string): unknown {
- const parts = ref.split(".");
- if (!parts.length || parts.length > 16 || parts.some((part) => !/^[A-Za-z0-9_:-]+$/.test(part) || ["__proto__", "constructor", "prototype"].includes(part))) throw new Error("invalid workflow reference");
- let value = root;
- for (const part of parts) {
- if ((!graphObject(value) && !Array.isArray(value)) || !Object.hasOwn(value, part)) throw new Error(`unresolved workflow reference: ${ref}`);
- value = (value as Record<string, unknown>)[part];
- }
- return structuredClone(value);
-}
-
-function bind(value: unknown, context: unknown, depth = 0): unknown {
- if (depth > 14) throw new Error("workflow references too deep");
- if (Array.isArray(value)) return value.map((item) => bind(item, context, depth + 1));
- if (!graphObject(value)) return value;
- if (Object.hasOwn(value, "$ref")) {
- if (Object.keys(value).length !== 1 || typeof value.$ref !== "string") throw new Error("workflow $ref must be the whole value");
- return safePath(context, value.$ref);
- }
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, bind(child, context, depth + 1)]));
-}
-
async function callTool(name: string, args: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<unknown> {
- const tool = resolve(name);
- if (!tool) throw new Error(`workflow tool unavailable: ${name}`);
+ const tool = resolve(name); if (!tool) throw new Error(`workflow tool unavailable: ${name}`);
const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });
- if (outcome.kind !== "success") throw new Error(outcome.message);
- return resultData(outcome.result);
+ if (outcome.kind !== "success") throw new Error(outcome.message); return resultData(outcome.result);
}
-
async function resolvedProject(hint: unknown): Promise<{ id: string; name: string; path: string; matchedBy: string }> {
if (typeof hint !== "string" || !hint) throw new Error("project node requires config.project");
- const project = await resolveProjectHint(hint);
- if (!project || project.matchedBy === "fuzzy") throw new Error("project node requires an exact resolvable project");
+ const project = await resolveProjectHint(hint); if (!project || project.matchedBy === "fuzzy") throw new Error("project node requires an exact resolvable project");
return { id: project.id, name: project.name, path: project.path, matchedBy: project.matchedBy };
}
+async function loopTool(config: Record<string, unknown>, runtime: unknown, context: CapabilityRunContext, resolve: Resolver) {
+ const tool = typeof config.tool === "string" ? config.tool : ""; if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("loop node requires a bounded tool");
+ const all = workflowItems(config, runtime), concurrency = Math.max(1, Math.min(4, Math.trunc(Number(config.concurrency) || 1))), results: unknown[] = [];
+ for (let start = 0; start < all.length; start += concurrency) {
+ const batch = all.slice(start, start + concurrency);
+ results.push(...await Promise.all(batch.map(async (item, offset) => {
+ const args = bindLoopItem(graphObject(config.arguments) ? config.arguments : {}, item, start + offset) as Record<string, unknown>;
+ if (context.workflowId) args.workflow_id = context.workflowId; return callTool(tool, args, context, resolve);
+ })));
+ }
+ return { output: { count: all.length, results }, log: `Looped ${all.length} item(s) through ${tool}.` };
+}
async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph: WorkflowGraph, graphInput: Record<string, unknown>, outputs: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<NodeExecutionResult> {
- const runtimeContext = { input: graphInput, nodes: Object.fromEntries(Object.entries(outputs).map(([id, output]) => [id, { output }])), graph: { id: graph.id, name: graph.name, metadata: graph.metadata } };
- const config = bind(node.config, runtimeContext) as Record<string, unknown>;
+ const runtime = { input: graphInput, trigger: run.trigger, nodes: Object.fromEntries(Object.entries(outputs).map(([id, output]) => [id, { output }])), graph: { id: graph.id, name: graph.name, metadata: graph.metadata } };
+ const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow node requires principal");
+ const config = bindWorkflowValue(node.config, runtime, await workflowVariableValues(principal)) as Record<string, unknown>;
const project = typeof config.project === "string" ? config.project : graph.metadata.project;
- if (node.type === "manual") return { output: graphInput, log: "Manual trigger accepted." };
+ if (["manual", "schedule", "webhook"].includes(node.type)) return { output: graphInput, log: `${node.type} trigger accepted.` };
if (node.type === "project") return { output: await resolvedProject(config.project ?? project), log: "Canonical project resolved at runtime." };
if (node.type === "folder") {
- const resolved = await resolvedProject(config.project ?? project), relative = typeof config.path === "string" ? config.path : ".";
- const target = path.resolve(resolved.path, relative), root = resolved.path.endsWith(path.sep) ? resolved.path : resolved.path + path.sep;
- if (target !== resolved.path && !target.startsWith(root)) throw new Error("folder node path escapes project root");
- const stat = await fs.stat(target); if (!stat.isDirectory()) throw new Error("folder node target is not a directory");
+ const resolved = await resolvedProject(config.project ?? project), relative = typeof config.path === "string" ? config.path : ".", target = path.resolve(resolved.path, relative), root = resolved.path.endsWith(path.sep) ? resolved.path : resolved.path + path.sep;
+ if (target !== resolved.path && !target.startsWith(root)) throw new Error("folder node path escapes project root"); const stat = await fs.stat(target); if (!stat.isDirectory()) throw new Error("folder node target is not a directory");
return { output: { project: resolved.id, path: target, relativePath: path.relative(resolved.path, target) || "." }, log: "Folder resolved inside the canonical project root." };
}
- if (node.type === "skill") {
- const query = typeof config.query === "string" ? config.query : typeof config.key === "string" ? config.key : node.name;
- return { output: await callTool("skills_search", { query, top_k: Number(config.top_k) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Skill catalog queried with provenance/trust metadata." };
- }
+ if (node.type === "skill") { const query = typeof config.query === "string" ? config.query : typeof config.key === "string" ? config.key : node.name; return { output: await callTool("skills_search", { query, top_k: Number(config.top_k) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Skill catalog queried with provenance/trust metadata." }; }
if (node.type === "knowledge") {
if (!project) throw new Error("knowledge node requires project binding");
if (typeof config.query === "string" && config.query) return { output: await callTool("project_memory_search", { project, query: config.query, limit: Number(config.limit) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project memory queried." };
return { output: await callTool("project_knowledge_get", { project, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project knowledge resolved." };
}
- if (node.type === "condition") {
- const ref = typeof config.path === "string" ? config.path : "input";
- const value = safePath(runtimeContext, ref), branch = Object.hasOwn(config, "equals") ? JSON.stringify(value) === JSON.stringify(config.equals) : Boolean(value);
- return { output: { value, branch }, branch, log: `Condition evaluated to ${branch}.` };
- }
+ const flow = await executeFlowNode(node, config, graph, outputs, runtime); if (flow) return flow;
if (node.type === "output") return { output: Object.hasOwn(config, "value") ? config.value : { nodes: outputs }, log: "Workflow output collected." };
+ if (node.type === "loop") return loopTool(config, runtime, context, resolve);
if (node.type === "tool") {
- const tool = typeof config.tool === "string" ? config.tool : "";
- if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("tool node requires a bounded non-workflow tool");
- const args = graphObject(config.arguments) ? structuredClone(config.arguments) : {};
- if (context.workflowId) args.workflow_id = context.workflowId;
+ const tool = typeof config.tool === "string" ? config.tool : ""; if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("tool node requires a bounded non-workflow tool");
+ const args = graphObject(config.arguments) ? structuredClone(config.arguments) : {}; if (context.workflowId) args.workflow_id = context.workflowId;
return { output: await callTool(tool, args, context, resolve), log: `Tool ${tool} completed.` };
}
- if (node.type === "project_function") {
- if (!project || typeof config.name !== "string") throw new Error("project_function node requires project and name");
- return { output: await callTool("project_function_call", { project, name: config.name, input: graphObject(config.input) ? config.input : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project function ${config.name} completed.` };
- }
- if (node.type === "project_mcp") {
- if (!project || typeof config.server !== "string" || typeof config.tool !== "string") throw new Error("project_mcp node requires project/server/tool");
- return { output: await callTool("project_mcp_call", { project, server: config.server, tool: config.tool, arguments: graphObject(config.arguments) ? config.arguments : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project MCP ${config.server}.${config.tool} completed.` };
- }
- if (node.type === "script") {
- if (!project || typeof config.script_id !== "string") throw new Error("script node requires project and script_id");
- return { output: await callTool("project_script_run", { project, script_id: config.script_id, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Script ${config.script_id} completed.` };
- }
- if (node.type === "agent") {
- if (!project || typeof config.message !== "string") throw new Error("agent node requires project and message");
- const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" };
- if (context.workflowId) args.workflow_id = context.workflowId;
- return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." };
+ if (node.type === "integration") {
+ for (const key of ["user", "provider", "connection", "operation"]) if (typeof config[key] !== "string" || !config[key]) throw new Error(`integration node requires ${key}`);
+ const args = { user: config.user, provider: config.provider, connection: config.connection, operation: config.operation, ...(typeof config.tool === "string" ? { tool: config.tool } : {}), ...(graphObject(config.arguments) ? { arguments: config.arguments } : {}), ...(config.confirm === true ? { confirm: true } : {}), ...(context.workflowId ? { workflow_id: context.workflowId } : {}) };
+ return { output: await callTool("integration_execute", args, context, resolve), log: `Integration ${config.provider}/${config.connection} completed.` };
}
+ if (node.type === "project_function") { if (!project || typeof config.name !== "string") throw new Error("project_function node requires project and name"); return { output: await callTool("project_function_call", { project, name: config.name, input: graphObject(config.input) ? config.input : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project function ${config.name} completed.` }; }
+ if (node.type === "project_mcp") { if (!project || typeof config.server !== "string" || typeof config.tool !== "string") throw new Error("project_mcp node requires project/server/tool"); return { output: await callTool("project_mcp_call", { project, server: config.server, tool: config.tool, arguments: graphObject(config.arguments) ? config.arguments : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project MCP ${config.server}.${config.tool} completed.` }; }
+ if (node.type === "script") { if (!project || typeof config.script_id !== "string") throw new Error("script node requires project and script_id"); return { output: await callTool("project_script_run", { project, script_id: config.script_id, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Script ${config.script_id} completed.` }; }
+ if (node.type === "agent") { if (!project || typeof config.message !== "string") throw new Error("agent node requires project and message"); const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." }; }
if (node.type === "subflow") {
- if (!project || typeof config.flow !== "string") throw new Error("subflow node requires project and flow");
- const started = await callTool("flow_run", { project, flow: config.flow, input: graphObject(config.input) ? config.input : {}, idempotency_key: `${run.id}:${node.id}`, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve) as Record<string, unknown>;
- const runId = typeof started.id === "string" ? started.id : typeof started.run_id === "string" ? started.run_id : undefined;
- if (!runId) return { output: started, log: `Subflow ${config.flow} started.` };
- let latest: unknown = started;
- for (let tries = 0; tries < 24; tries += 1) {
- latest = await callTool("flow_status", { run_id: runId, wait_ms: 25_000 }, context, resolve);
- if (graphObject(latest) && latest.state !== "running") break;
+ if (typeof config.workflowId === "string" && config.workflowId) {
+ const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow subflow requires principal");
+ const { getWorkflowGraph } = await import("./graph-store"), { startWorkflowGraph, workflowGraphRunStatus } = await import("./graph-engine"), child = await getWorkflowGraph(principal, config.workflowId);
+ if (!child) throw new Error("subflow workflow graph not found");
+ const started = await startWorkflowGraph(child, graphObject(config.input) ? config.input : {}, `${run.id}:${node.id}`, context, resolve, principal, { type: "system", receivedAt: new Date().toISOString() }, run.ancestry ?? [graph.id]);
+ let latest = started; for (let tries = 0; tries < 24 && latest.state === "running"; tries += 1) latest = await workflowGraphRunStatus(principal, latest.id, 25_000);
+ if (latest.state === "failed" || latest.state === "interrupted" || latest.state === "running") throw new Error(`subflow workflow ${child.name} did not complete successfully`);
+ return { output: latest, log: `Workflow subflow ${child.name} completed.` };
}
- if (graphObject(latest) && latest.state !== "completed") throw new Error(`subflow ${config.flow} did not complete successfully`);
- return { output: latest, log: `Subflow ${config.flow} completed.` };
+ if (!project || typeof config.flow !== "string") throw new Error("subflow node requires workflowId or project/flow"); const started = await callTool("flow_run", { project, flow: config.flow, input: graphObject(config.input) ? config.input : {}, idempotency_key: `${run.id}:${node.id}`, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve) as Record<string, unknown>;
+ const runId = typeof started.id === "string" ? started.id : typeof started.run_id === "string" ? started.run_id : undefined; if (!runId) return { output: started, log: `Subflow ${config.flow} started.` };
+ let latest: unknown = started; for (let tries = 0; tries < 24; tries += 1) { latest = await callTool("flow_status", { run_id: runId, wait_ms: 25_000 }, context, resolve); if (graphObject(latest) && latest.state !== "running") break; }
+ if (graphObject(latest) && !["completed", "completed_with_errors"].includes(String(latest.state))) throw new Error(`subflow ${config.flow} did not complete successfully`); return { output: latest, log: `Subflow ${config.flow} completed.` };
}
throw new Error(`unsupported workflow node type: ${node.type}`);
}
-
export function nodeRuntimeView(row: WorkflowGraphRunNode): WorkflowGraphRunNode { return structuredClone(row); }
export { executeNode, compact };
diff --git a/lib/workflow/graph-schema.test.ts b/lib/workflow/graph-schema.test.ts
index b73be783..93cf0b16 100644
--- a/lib/workflow/graph-schema.test.ts
+++ b/lib/workflow/graph-schema.test.ts
@@ -11,6 +11,10 @@ const base = () => ({
describe("workflow graph schema", () => {
it("accepts a bounded acyclic metadata-only graph", () => expect(parseWorkflowGraphDefinition(base()).nodes).toHaveLength(2));
- it("rejects cycles", () => expect(() => parseWorkflowGraphDefinition({ ...base(), edges: [{ id: "e1", source: "start", target: "done" }, { id: "e2", source: "done", target: "start" }] })).toThrow("cycle"));
+ it("rejects cycles", () => expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "a", name: "A", type: "tool", position: { x: 0, y: 0 }, config: { tool: "x" } }, { id: "b", name: "B", type: "output", position: { x: 200, y: 0 }, config: {} }], edges: [{ id: "e1", source: "a", target: "b" }, { id: "e2", source: "b", target: "a" }] })).toThrow("cycle"));
it("rejects secret-like config fields recursively", () => expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Start", type: "tool", position: { x: 0, y: 0 }, config: { nested: { accessToken: "x" } } }, base().nodes[1]] })).toThrow("secret_input_forbidden"));
+ it("accepts parity node types but keeps triggers root-only", () => {
+ expect(parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Schedule", type: "schedule", position: { x: 0, y: 0 }, config: { mode: "interval", everyMinutes: 5 } }, { id: "wait", name: "Wait", type: "wait", position: { x: 100, y: 0 }, config: { delayMs: 0 } }, base().nodes[1]], edges: [{ id: "a", source: "start", target: "wait" }, { id: "b", source: "wait", target: "done" }] }).nodes.map((node) => node.type)).toEqual(["schedule", "wait", "output"]);
+ expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [base().nodes[0], { id: "hook", name: "Hook", type: "webhook", position: { x: 100, y: 0 }, config: {} }], edges: [{ id: "bad", source: "start", target: "hook" }] })).toThrow("root");
+ });
});
diff --git a/lib/workflow/graph-schema.ts b/lib/workflow/graph-schema.ts
index bb27fa3f..ec804b77 100644
--- a/lib/workflow/graph-schema.ts
+++ b/lib/workflow/graph-schema.ts
@@ -69,7 +69,7 @@ function assertAcyclic(nodes: WorkflowGraphNode[], edges: WorkflowGraphEdge[]):
const id = queue.shift()!; visited += 1;
for (const target of outgoing.get(id) ?? []) { const next = (indegree.get(target) ?? 0) - 1; indegree.set(target, next); if (next === 0) queue.push(target); }
}
- if (visited !== nodes.length) throw new Error("workflow graph contains a cycle; loops are not supported in v2 MVP");
+ if (visited !== nodes.length) throw new Error("workflow graph contains a cycle; use the loop node with a subflow/body binding instead of cyclic edges");
}
function parseMetadata(value: unknown): WorkflowGraphMetadata {
@@ -77,8 +77,8 @@ function parseMetadata(value: unknown): WorkflowGraphMetadata {
if (!graphObject(value)) throw new Error("workflow metadata must be an object");
assertWorkflowMetadataOnly(value);
const out: WorkflowGraphMetadata = {};
- for (const key of ["intent", "normalizedIntent", "project", "fingerprint"] as const) if (typeof value[key] === "string" && value[key]) out[key] = String(value[key]).slice(0, 1000);
- if (["user", "learned-from-session", "clone", "import"].includes(String(value.provenance))) out.provenance = value.provenance as WorkflowGraphMetadata["provenance"];
+ for (const key of ["intent", "normalizedIntent", "project", "fingerprint", "folder", "errorWorkflowId", "timezone"] as const) if (typeof value[key] === "string" && value[key]) out[key] = String(value[key]).slice(0, 1000);
+ if (["user", "learned-from-session", "clone", "import", "template", "ai-assisted"].includes(String(value.provenance))) out.provenance = value.provenance as WorkflowGraphMetadata["provenance"];
if (Array.isArray(value.sourceDigests)) out.sourceDigests = value.sourceDigests.filter((item): item is string => typeof item === "string").slice(0, 32).map((item) => item.slice(0, 128));
if (Array.isArray(value.tags)) out.tags = value.tags.filter((item): item is string => typeof item === "string").slice(0, 32).map((item) => item.slice(0, 64));
return out;
@@ -97,6 +97,8 @@ export function parseWorkflowGraphDefinition(raw: unknown): WorkflowGraphDefinit
if (!Array.isArray(raw.edges) || raw.edges.length > 400) throw new Error("workflow graph supports up to 400 edges");
const edges = raw.edges.map((edge) => parseEdge(edge, nodeIds));
if (new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("duplicate workflow edge id");
+ const triggerIds = new Set(nodes.filter((node) => ["manual", "schedule", "webhook"].includes(node.type)).map((node) => node.id));
+ if (edges.some((edge) => triggerIds.has(edge.target))) throw new Error("trigger nodes must be workflow roots");
assertAcyclic(nodes, edges);
return { ...(typeof raw.id === "string" ? { id: raw.id } : {}), name: raw.name.trim(), description: raw.description, status: raw.status as WorkflowGraphStatus, inputs: structuredClone(raw.inputs), nodes, edges, metadata: parseMetadata(raw.metadata) };
}
diff --git a/lib/workflow/graph-store.ts b/lib/workflow/graph-store.ts
index 8151da81..b69e8080 100644
--- a/lib/workflow/graph-store.ts
+++ b/lib/workflow/graph-store.ts
@@ -6,12 +6,13 @@ import type { LearnedRecipe } from "./types";
import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
import { normalizeWorkflowIntent, parseWorkflowGraphDefinition, type WorkflowGraphDefinition } from "./graph-schema";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { saveWorkflowGraphVersion, type WorkflowGraphVersionReason } from "./graph-version-store";
-const STORE_VERSION = 1;
+const STORE_VERSION = 2;
const MAX_STORE_BYTES = 4 * 1024 * 1024;
const MAX_GRAPHS = 200;
-type WorkflowGraphStore = { version: 1; owner: string; graphs: WorkflowGraph[] };
+type WorkflowGraphStore = { version: 2; owner: string; principal: string; graphs: WorkflowGraph[] };
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
export function workflowGraphOwner(principal: string): string { return hash(principal); }
@@ -39,18 +40,20 @@ function parseStoredGraph(raw: unknown): WorkflowGraph {
return { ...definition, version: 2, id: row.id, createdAt: row.createdAt, updatedAt: row.updatedAt, revision: row.revision };
}
-async function readStore(owner: string): Promise<WorkflowGraphStore> {
+async function readStore(owner: string, principal = ""): Promise<WorkflowGraphStore> {
const target = file(owner);
try {
const stat = await fs.lstat(target);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_STORE_BYTES || (stat.mode & 0o077)) throw new Error("unsafe workflow graph store");
const parsed: unknown = JSON.parse(await fs.readFile(target, "utf8"));
if (!parsed || typeof parsed !== "object") throw new Error("invalid workflow graph store");
- const row = parsed as { version?: unknown; owner?: unknown; graphs?: unknown };
- if (row.version !== STORE_VERSION || row.owner !== owner || !Array.isArray(row.graphs) || row.graphs.length > MAX_GRAPHS) throw new Error("invalid workflow graph store");
- return { version: 1, owner, graphs: row.graphs.map(parseStoredGraph) };
+ const row = parsed as { version?: unknown; owner?: unknown; principal?: unknown; graphs?: unknown };
+ if (row.owner !== owner || !Array.isArray(row.graphs) || row.graphs.length > MAX_GRAPHS) throw new Error("invalid workflow graph store");
+ if (row.version === 1) return { version: 2, owner, principal, graphs: row.graphs.map(parseStoredGraph) };
+ if (row.version !== STORE_VERSION || typeof row.principal !== "string") throw new Error("invalid workflow graph store");
+ return { version: 2, owner, principal: row.principal, graphs: row.graphs.map(parseStoredGraph) };
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, owner, graphs: [] };
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 2, owner, principal, graphs: [] };
throw error;
}
}
@@ -81,7 +84,7 @@ function materialize(definition: WorkflowGraphDefinition, previous?: WorkflowGra
}
export async function listWorkflowGraphs(principal: string): Promise<WorkflowGraph[]> {
- const owner = workflowGraphOwner(principal), store = await readStore(owner);
+ const owner = workflowGraphOwner(principal), store = await readStore(owner, principal);
return store.graphs.slice().sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
}
@@ -89,36 +92,36 @@ export async function getWorkflowGraph(principal: string, id: string): Promise<W
return (await listWorkflowGraphs(principal)).find((graph) => graph.id === id) ?? null;
}
-export async function createWorkflowGraph(principal: string, raw: unknown): Promise<WorkflowGraph> {
+export async function createWorkflowGraph(principal: string, raw: unknown, reason: WorkflowGraphVersionReason = "create"): Promise<WorkflowGraph> {
const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
return withGraphLock(owner, async () => {
- const store = await readStore(owner);
+ const store = await readStore(owner, principal);
if (store.graphs.length >= MAX_GRAPHS) throw new Error("private workflow graph limit reached");
const graph = materialize({ ...definition, id: definition.id ?? randomUUID() });
if (store.graphs.some((row) => row.id === graph.id)) throw new Error("workflow graph id already exists");
- store.graphs.push(graph); await writeStore(store); return graph;
+ store.principal = principal; store.graphs.push(graph); await writeStore(store); await saveWorkflowGraphVersion(owner, graph, reason); return graph;
});
}
-export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown): Promise<WorkflowGraph> {
+export async function updateWorkflowGraph(principal: string, id: string, expectedRevision: string, raw: unknown, reason: WorkflowGraphVersionReason = "update"): Promise<WorkflowGraph> {
const owner = workflowGraphOwner(principal), definition = parseWorkflowGraphDefinition(raw);
return withGraphLock(owner, async () => {
- const store = await readStore(owner), index = store.graphs.findIndex((graph) => graph.id === id);
+ const store = await readStore(owner, principal), index = store.graphs.findIndex((graph) => graph.id === id);
if (index < 0) throw new Error("workflow graph not found");
const current = store.graphs[index];
if (current.revision !== expectedRevision) throw new Error("workflow graph revision changed; refresh before editing");
if (definition.id && definition.id !== id) throw new Error("workflow graph id mismatch");
- const graph = materialize({ ...definition, id }, current); store.graphs[index] = graph; await writeStore(store); return graph;
+ const graph = materialize({ ...definition, id }, current); store.principal = principal; store.graphs[index] = graph; await writeStore(store); await saveWorkflowGraphVersion(owner, graph, reason); return graph;
});
}
export async function deleteWorkflowGraph(principal: string, id: string, expectedRevision: string): Promise<{ id: string; deleted: true }> {
const owner = workflowGraphOwner(principal);
return withGraphLock(owner, async () => {
- const store = await readStore(owner), current = store.graphs.find((graph) => graph.id === id);
+ const store = await readStore(owner, principal), current = store.graphs.find((graph) => graph.id === id);
if (!current) throw new Error("workflow graph not found");
if (current.revision !== expectedRevision) throw new Error("workflow graph revision changed; refresh before deleting");
- store.graphs = store.graphs.filter((graph) => graph.id !== id); await writeStore(store); return { id, deleted: true };
+ store.principal = principal; store.graphs = store.graphs.filter((graph) => graph.id !== id); await writeStore(store); return { id, deleted: true };
});
}
@@ -158,7 +161,7 @@ export async function ensureLearnedWorkflowGraph(recipe: LearnedRecipe): Promise
if (!recipe.successes || !recipe.bestSteps.length) return null;
const principal = recipe.actor, fingerprint = learnedFingerprint(recipe), owner = workflowGraphOwner(principal);
return withGraphLock(owner, async () => {
- const store = await readStore(owner), existing = store.graphs.find((graph) => graph.metadata.fingerprint === fingerprint);
+ const store = await readStore(owner, recipe.actor), existing = store.graphs.find((graph) => graph.metadata.fingerprint === fingerprint);
if (existing) return existing;
if (store.graphs.length >= MAX_GRAPHS) return null;
const nodes = [
@@ -171,6 +174,16 @@ export async function ensureLearnedWorkflowGraph(recipe: LearnedRecipe): Promise
name: recipe.intent.slice(0, 120), description: `Learned draft from ${recipe.successes} successful session run(s).`, status: "draft",
inputs: {}, nodes, edges, metadata: { intent: recipe.intent, normalizedIntent: recipe.normalizedIntent, project: recipe.project, provenance: "learned-from-session", fingerprint, sourceDigests: [hash(recipe.id)] },
});
- const graph = materialize({ ...definition, id: randomUUID() }); store.graphs.push(graph); await writeStore(store); return graph;
+ const graph = materialize({ ...definition, id: randomUUID() }); store.principal = recipe.actor; store.graphs.push(graph); await writeStore(store); await saveWorkflowGraphVersion(owner, graph, "create"); return graph;
});
}
+
+export async function listWorkflowGraphTriggerSources(): Promise<Array<{ owner: string; principal: string; graph: WorkflowGraph }>> {
+ let owners: string[]; try { owners = await fs.readdir(root()); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
+ const out: Array<{ owner: string; principal: string; graph: WorkflowGraph }> = [];
+ for (const owner of owners.filter((value) => /^[a-f0-9]{64}$/.test(value)).slice(0, 4096)) {
+ const store = await readStore(owner).catch(() => null); if (!store?.principal) continue;
+ for (const graph of store.graphs) if (graph.status === "active" && graph.nodes.some((node) => node.type === "schedule" || node.type === "webhook")) out.push({ owner, principal: store.principal, graph });
+ }
+ return out;
+}
diff --git a/lib/workflow/graph-triggers.ts b/lib/workflow/graph-triggers.ts
new file mode 100644
index 00000000..780070b1
--- /dev/null
+++ b/lib/workflow/graph-triggers.ts
@@ -0,0 +1,21 @@
+import { createHash } from "node:crypto";
+import { createAgentSession } from "@/lib/agent/session-store";
+import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+import { listWorkflowGraphTriggerSources } from "./graph-store";
+import { scheduleBucket } from "./schedule";
+import { startWorkflowGraph, workflowGraphRunId } from "./graph-engine";
+import { readWorkflowGraphRun } from "./graph-run-store";
+
+const g=globalThis as typeof globalThis&{__msoWorkflowScheduler?:ReturnType<typeof setInterval>;__msoWorkflowSchedulerBusy?:boolean};
+function key(parts:string[]){return `trigger:${createHash("sha256").update(parts.join(":" )).digest("hex").slice(0,48)}`;}
+type Resolver=(name:string)=>CapabilityTool|undefined;
+async function runScheduled(principal:string,owner:string,graph:Awaited<ReturnType<typeof listWorkflowGraphTriggerSources>>[number]["graph"],node:WorkflowGraphNode,bucket:string,resolve:Resolver){
+ const idempotency=key([graph.id,node.id,bucket]);if(await readWorkflowGraphRun(owner,workflowGraphRunId(owner,idempotency)))return;
+ const session=await createAgentSession(principal,"cli",{title:`Schedule: ${graph.name}`,titleSource:"auto"});
+ const context={principal,actor:principal,sessionId:session.id,scope:"exec" as const};
+ await startWorkflowGraph(graph,{trigger:{type:"schedule",nodeId:node.id,bucket,at:new Date().toISOString()}},idempotency,context,resolve,principal,{type:"schedule",nodeId:node.id,receivedAt:new Date().toISOString()});
+}
+export async function tickWorkflowScheduler(resolve:Resolver,now=new Date()){if(g.__msoWorkflowSchedulerBusy)return;g.__msoWorkflowSchedulerBusy=true;try{const sources=await listWorkflowGraphTriggerSources();let started=0;for(const source of sources){for(const node of source.graph.nodes.filter((row)=>row.type==="schedule"&&!row.disabled)){if(started>=50)return;let bucket:string|null=null;try{bucket=scheduleBucket(node,now,source.graph.metadata.timezone||"UTC");}catch{continue;}if(!bucket)continue;await runScheduled(source.principal,source.owner,source.graph,node,bucket,resolve).catch(()=>undefined);started+=1;}}}finally{g.__msoWorkflowSchedulerBusy=false;}}
+export function startWorkflowScheduler(resolve:Resolver){if(process.env.NODE_ENV==="test"||g.__msoWorkflowScheduler)return;void tickWorkflowScheduler(resolve);g.__msoWorkflowScheduler=setInterval(()=>void tickWorkflowScheduler(resolve),15_000);g.__msoWorkflowScheduler.unref();}
+export async function findActiveWebhookSource(graphId:string,nodeId:string){for(const source of await listWorkflowGraphTriggerSources()){if(source.graph.id!==graphId)continue;const node=source.graph.nodes.find((row)=>row.id===nodeId&&row.type==="webhook"&&!row.disabled);if(node)return{...source,node};}return null;}
diff --git a/lib/workflow/graph-version-store.test.ts b/lib/workflow/graph-version-store.test.ts
new file mode 100644
index 00000000..743216cc
--- /dev/null
+++ b/lib/workflow/graph-version-store.test.ts
@@ -0,0 +1,8 @@
+import { afterAll, describe, expect, it } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+const dir=await mkdtemp(path.join(os.tmpdir(),"mso-workflow-version-"));process.env.OS_AGENT_SESSIONS_DIR=dir;
+const store=await import("./graph-store"),versions=await import("./graph-version-store");afterAll(()=>rm(dir,{recursive:true,force:true}));
+const def=(name:string)=>({name,description:"",status:"draft" as const,inputs:{},metadata:{},nodes:[{id:"start",name:"Start",type:"manual" as const,position:{x:0,y:0},config:{}},{id:"out",name:"Out",type:"output" as const,position:{x:200,y:0},config:{}}],edges:[{id:"e",source:"start",target:"out"}]});
+describe("workflow graph versions",()=>{it("snapshots creates and updates and can read an older revision",async()=>{const first=await store.createWorkflowGraph("version-owner",def("First")),second=await store.updateWorkflowGraph("version-owner",first.id,first.revision,def("Second"));const owner=store.workflowGraphOwner("version-owner"),history=await versions.listWorkflowGraphVersions(owner,first.id);expect(history.map((row)=>row.revision)).toEqual(expect.arrayContaining([first.revision,second.revision]));expect((await versions.readWorkflowGraphVersion(owner,first.id,first.revision))?.graph.name).toBe("First");});});
diff --git a/lib/workflow/graph-version-store.ts b/lib/workflow/graph-version-store.ts
new file mode 100644
index 00000000..616cbc23
--- /dev/null
+++ b/lib/workflow/graph-version-store.ts
@@ -0,0 +1,45 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { agentSessionsDir } from "@/lib/agent/session-paths";
+
+const MAX_VERSIONS = 100;
+const MAX_BYTES = 320 * 1024;
+export type WorkflowGraphVersionReason = "create" | "update" | "restore" | "import" | "template" | "ai-assisted";
+export type WorkflowGraphVersion = { revision: string; savedAt: string; reason: WorkflowGraphVersionReason; graph: WorkflowGraph };
+
+function safe(owner: string, graphId: string) {
+ if (!/^[a-f0-9]{64}$/.test(owner) || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/.test(graphId)) throw new Error("invalid workflow version identity");
+}
+function directory(owner: string, graphId: string) { safe(owner, graphId); return path.join(agentSessionsDir(), ".workflow-graph-versions", owner, graphId); }
+function filename(row: WorkflowGraphVersion) { return `${Date.parse(row.savedAt)}-${row.revision}.json`; }
+
+export async function saveWorkflowGraphVersion(owner: string, graph: WorkflowGraph, reason: WorkflowGraphVersionReason): Promise<void> {
+ const dir = directory(owner, graph.id); await fs.mkdir(dir, { recursive: true, mode: 0o700 }); await fs.chmod(dir, 0o700).catch(() => undefined);
+ const row: WorkflowGraphVersion = { revision: graph.revision, savedAt: new Date().toISOString(), reason, graph: structuredClone(graph) };
+ const body = JSON.stringify(row), target = path.join(dir, filename(row)), temp = `${target}.${randomUUID()}.tmp`;
+ if (Buffer.byteLength(body) > MAX_BYTES) throw new Error("workflow version snapshot too large");
+ try { await fs.writeFile(temp, body, { flag: "wx", mode: 0o600 }); await fs.rename(temp, target); } finally { await fs.unlink(temp).catch(() => undefined); }
+ const entries = (await fs.readdir(dir)).filter((name) => /^\d+-[a-f0-9]{64}\.json$/.test(name)).sort().reverse();
+ for (const name of entries.slice(MAX_VERSIONS)) await fs.unlink(path.join(dir, name)).catch(() => undefined);
+}
+
+export async function listWorkflowGraphVersions(owner: string, graphId: string) {
+ const dir = directory(owner, graphId); let entries: string[];
+ try { entries = await fs.readdir(dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
+ const rows = entries.filter((name) => /^\d+-[a-f0-9]{64}\.json$/.test(name)).sort().reverse().slice(0, MAX_VERSIONS);
+ return Promise.all(rows.map(async (name) => {
+ const row = JSON.parse(await fs.readFile(path.join(dir, name), "utf8")) as WorkflowGraphVersion;
+ return { revision: row.revision, savedAt: row.savedAt, reason: row.reason, name: row.graph.name, nodeCount: row.graph.nodes.length };
+ }));
+}
+
+export async function readWorkflowGraphVersion(owner: string, graphId: string, revision: string): Promise<WorkflowGraphVersion | null> {
+ if (!/^[a-f0-9]{64}$/.test(revision)) throw new Error("invalid workflow revision");
+ const dir = directory(owner, graphId); let entries: string[];
+ try { entries = await fs.readdir(dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
+ const name = entries.find((entry) => entry.endsWith(`-${revision}.json`)); if (!name) return null;
+ const stat = await fs.lstat(path.join(dir, name)); if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_BYTES || (stat.mode & 0o077)) throw new Error("unsafe workflow version snapshot");
+ return JSON.parse(await fs.readFile(path.join(dir, name), "utf8")) as WorkflowGraphVersion;
+}
diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.ts
new file mode 100644
index 00000000..bb993089
--- /dev/null
+++ b/lib/workflow/node-catalog.ts
@@ -0,0 +1,26 @@
+import type { WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";
+export type WorkflowNodeCatalogItem={type:WorkflowGraphNodeType;title:string;category:string;description:string;handles?:string[];defaults:Record<string,unknown>};
+export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
+ {type:"manual",title:"Manual Trigger",category:"Triggers",description:"Start from UI, CLI or MCP.",defaults:{}},
+ {type:"schedule",title:"Schedule Trigger",category:"Triggers",description:"Run by cron or minute interval on the MSO server.",defaults:{mode:"interval",everyMinutes:60}},
+ {type:"webhook",title:"Webhook Trigger",category:"Triggers",description:"Public HTTP trigger with optional private-variable bearer auth.",defaults:{methods:["POST"],responseMode:"onReceived"}},
+ {type:"condition",title:"If",category:"Flow",description:"Route to true/false handles.",handles:["true","false"],defaults:{path:"input"}},
+ {type:"switch",title:"Switch",category:"Flow",description:"Route by multiple case handles plus default.",defaults:{path:"input",cases:[]}},
+ {type:"merge",title:"Merge",category:"Flow",description:"Merge enabled incoming node outputs.",defaults:{mode:"combine"}},
+ {type:"batch",title:"Split In Batches",category:"Flow",description:"Chunk an array into deterministic batches.",defaults:{size:10}},
+ {type:"loop",title:"Loop Over Items",category:"Flow",description:"Run one bounded tool once per item without cyclic graph edges.",defaults:{concurrency:1}},
+ {type:"wait",title:"Wait",category:"Flow",description:"Delay execution or wait until a timestamp within run timeout.",defaults:{delayMs:1000}},
+ {type:"tool",title:"MSO Tool",category:"Actions",description:"Call one bounded MSO capability tool.",defaults:{}},
+ {type:"project_function",title:"Project Function",category:"Actions",description:"Call a project-owned function.",defaults:{}},
+ {type:"project_mcp",title:"Project MCP",category:"Actions",description:"Call a project-owned MCP tool.",defaults:{}},
+ {type:"integration",title:"Integration",category:"Actions",description:"Execute through an existing MSO integration connection; credentials stay outside the graph.",defaults:{}},
+ {type:"script",title:"Script",category:"Actions",description:"Run a learned RASMIC script.",defaults:{}},
+ {type:"agent",title:"Agent",category:"AI",description:"Run a focused project agent action.",defaults:{wait:true,max_scope:"write"}},
+ {type:"subflow",title:"Subflow",category:"Flow",description:"Run an existing project flow.",defaults:{}},
+ {type:"project",title:"Project",category:"Context",description:"Resolve canonical project identity/path at runtime.",defaults:{}},
+ {type:"folder",title:"Folder",category:"Context",description:"Resolve a real folder inside a canonical project.",defaults:{path:"."}},
+ {type:"skill",title:"Skill",category:"Context",description:"Search trusted skill catalog with provenance.",defaults:{}},
+ {type:"knowledge",title:"Knowledge",category:"Context",description:"Read project knowledge or memory.",defaults:{}},
+ {type:"output",title:"Output",category:"Flow",description:"Collect workflow output.",defaults:{}},
+];
+export function workflowNodeCatalog(query=""){const q=query.trim().toLowerCase();return WORKFLOW_NODE_CATALOG.filter((item)=>!q||`${item.type} ${item.title} ${item.category} ${item.description}`.toLowerCase().includes(q));}
diff --git a/lib/workflow/schedule.test.ts b/lib/workflow/schedule.test.ts
new file mode 100644
index 00000000..ac5633f3
--- /dev/null
+++ b/lib/workflow/schedule.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vitest";
+import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+import { scheduleBucket } from "./schedule";
+const node=(config:Record<string,unknown>):WorkflowGraphNode=>({id:"schedule",name:"Schedule",type:"schedule",position:{x:0,y:0},config});
+describe("workflow schedule",()=>{
+ it("matches deterministic minute intervals",()=>{const now=new Date("2026-09-15T05:30:00Z");expect(scheduleBucket(node({mode:"interval",everyMinutes:15}),now,"UTC")).toBeTruthy();expect(scheduleBucket(node({mode:"interval",everyMinutes:7}),now,"UTC")).toBeNull();});
+ it("matches five-field cron in the configured timezone",()=>{const now=new Date("2026-09-15T05:30:00Z");expect(scheduleBucket(node({mode:"cron",cron:"30 12 * * *",timezone:"Asia/Jakarta"}),now,"UTC")).toContain("Asia/Jakarta");expect(scheduleBucket(node({mode:"cron",cron:"31 12 * * *",timezone:"Asia/Jakarta"}),now,"UTC")).toBeNull();});
+ it("rejects malformed cron fields",()=>expect(()=>scheduleBucket(node({mode:"cron",cron:"* * *"}),new Date(),"UTC")).toThrow("5 fields"));
+});
diff --git a/lib/workflow/schedule.ts b/lib/workflow/schedule.ts
new file mode 100644
index 00000000..e4529c49
--- /dev/null
+++ b/lib/workflow/schedule.ts
@@ -0,0 +1,5 @@
+import type { WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+type Parts={minute:number;hour:number;day:number;month:number;weekday:number};
+function parts(date:Date,timeZone:string):Parts{const values=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone,minute:"2-digit",hour:"2-digit",day:"2-digit",month:"2-digit",weekday:"short",hourCycle:"h23"}).formatToParts(date).map(p=>[p.type,p.value]));const wd=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].indexOf(values.weekday);return{minute:Number(values.minute),hour:Number(values.hour),day:Number(values.day),month:Number(values.month),weekday:wd};}
+function field(expr:string,value:number,min:number,max:number):boolean{for(const token of expr.split(",")){const [range,stepRaw]=token.split("/"),step=stepRaw?Number(stepRaw):1;if(!Number.isInteger(step)||step<1)throw new Error("invalid cron step");let lo=min,hi=max;if(range&&range!=="*"){if(range.includes("-")){const [a,b]=range.split("-").map(Number);lo=a;hi=b;}else lo=hi=Number(range);}if(!Number.isInteger(lo)||!Number.isInteger(hi)||lo<min||hi>max||lo>hi)throw new Error("invalid cron field");if(value>=lo&&value<=hi&&(value-lo)%step===0)return true;}return false;}
+export function scheduleBucket(node:WorkflowGraphNode,now=new Date(),fallbackZone="UTC"):string|null{if(node.type!=="schedule")return null;const c=node.config,mode=String(c.mode??"interval"),zone=typeof c.timezone==="string"&&c.timezone?c.timezone:fallbackZone;const p=parts(now,zone);if(mode==="interval"){const n=Math.max(1,Math.min(10080,Math.trunc(Number(c.everyMinutes)||60)));const minute=Math.floor(now.getTime()/60000);return minute%n===0?`${zone}:${minute}`:null;}const expr=String(c.cron??"").trim(),fields=expr.split(/\s+/);if(fields.length!==5)throw new Error("cron requires 5 fields: minute hour day month weekday");const hit=field(fields[0]!,p.minute,0,59)&&field(fields[1]!,p.hour,0,23)&&field(fields[2]!,p.day,1,31)&&field(fields[3]!,p.month,1,12)&&field(fields[4]!,p.weekday,0,6);return hit?`${zone}:${Math.floor(now.getTime()/60000)}`:null;}
diff --git a/lib/workflow/templates.ts b/lib/workflow/templates.ts
new file mode 100644
index 00000000..5da8998e
--- /dev/null
+++ b/lib/workflow/templates.ts
@@ -0,0 +1,9 @@
+import { parseWorkflowGraphDefinition } from "./graph-schema";
+const edge=(id:string,source:string,target:string,sourceHandle?:string)=>({id,source,target,...(sourceHandle?{sourceHandle}:{})});
+export const WORKFLOW_TEMPLATES=[
+ {id:"scheduled-project-health",title:"Scheduled Project Health",description:"Resolve a project, inspect knowledge, then emit a receipt on a server schedule.",definition:parseWorkflowGraphDefinition({name:"Scheduled Project Health",description:"Generic server-side project health workflow.",status:"draft",inputs:{},metadata:{provenance:"template",tags:["schedule","project"]},nodes:[{id:"schedule",name:"Every Hour",type:"schedule",position:{x:60,y:120},config:{mode:"interval",everyMinutes:60}},{id:"project",name:"Project",type:"project",position:{x:320,y:120},config:{project:"PROJECT_ID"}},{id:"knowledge",name:"Knowledge",type:"knowledge",position:{x:580,y:120},config:{project:{"$ref":"nodes.project.output.id"}}},{id:"output",name:"Output",type:"output",position:{x:840,y:120},config:{}}],edges:[edge("e1","schedule","project"),edge("e2","project","knowledge"),edge("e3","knowledge","output")]} )},
+ {id:"webhook-router",title:"Webhook Router",description:"Receive a webhook and route true/false before returning output.",definition:parseWorkflowGraphDefinition({name:"Webhook Router",description:"Generic webhook routing workflow.",status:"draft",inputs:{},metadata:{provenance:"template",tags:["webhook"]},nodes:[{id:"webhook",name:"Webhook",type:"webhook",position:{x:60,y:160},config:{methods:["POST"],responseMode:"lastNode"}},{id:"if",name:"Has Body",type:"condition",position:{x:320,y:160},config:{path:"input.body"}},{id:"yes",name:"Accepted",type:"output",position:{x:600,y:100},config:{value:{accepted:true}}},{id:"no",name:"Rejected",type:"output",position:{x:600,y:240},config:{value:{accepted:false}}}],edges:[edge("e1","webhook","if"),edge("e2","if","yes","true"),edge("e3","if","no","false")]} )},
+ {id:"retry-action",title:"Retry Action",description:"Run one MSO tool with bounded retries and an error branch.",definition:parseWorkflowGraphDefinition({name:"Retry Action",description:"Generic retry/error handling starter.",status:"draft",inputs:{},metadata:{provenance:"template",tags:["retry","error"]},nodes:[{id:"manual",name:"Manual Trigger",type:"manual",position:{x:60,y:160},config:{}},{id:"action",name:"Action",type:"tool",position:{x:320,y:160},config:{tool:"PROJECT_TOOL",arguments:{},retry:{maxAttempts:3,backoffMs:1000}}},{id:"ok",name:"Success",type:"output",position:{x:600,y:100},config:{}},{id:"error",name:"Error",type:"output",position:{x:600,y:240},config:{value:{handled:true}}}],edges:[edge("e1","manual","action"),edge("e2","action","ok"),edge("e3","action","error","error")]} )},
+] as const;
+export function workflowTemplates(){return WORKFLOW_TEMPLATES.map(({id,title,description,definition})=>({id,title,description,tags:definition.metadata.tags??[],nodeCount:definition.nodes.length}));}
+export function workflowTemplate(id:string){return WORKFLOW_TEMPLATES.find((row)=>row.id===id)??null;}
diff --git a/lib/workflow/variables.test.ts b/lib/workflow/variables.test.ts
new file mode 100644
index 00000000..33490d32
--- /dev/null
+++ b/lib/workflow/variables.test.ts
@@ -0,0 +1,11 @@
+import { afterAll, beforeEach, describe, expect, it } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+const dir=await mkdtemp(path.join(os.tmpdir(),"mso-workflow-vars-"));process.env.OS_AGENT_SESSIONS_DIR=dir;
+const vars=await import("./variables");
+afterAll(()=>rm(dir,{recursive:true,force:true}));beforeEach(()=>rm(path.join(dir,".workflow-variables"),{recursive:true,force:true}));
+describe("workflow variables",()=>{
+ it("keeps values isolated by principal and hides secret values from listings",async()=>{await vars.setWorkflowVariable("alice","PUBLIC_VALUE",{ok:true});await vars.setWorkflowVariable("alice","API_TOKEN","top-secret-value",true);expect(await vars.listWorkflowVariables("alice")).toEqual(expect.arrayContaining([expect.objectContaining({key:"PUBLIC_VALUE",value:{ok:true},secret:false}),expect.not.objectContaining({key:"API_TOKEN",value:"top-secret-value"})]));expect(await vars.workflowVariableValues("bob")).toEqual({});expect(await vars.workflowVariableValues("alice")).toMatchObject({API_TOKEN:"top-secret-value"});});
+ it("rejects unsafe keys and oversized values",async()=>{await expect(vars.setWorkflowVariable("alice","bad-key","x")).rejects.toThrow("key");await expect(vars.setWorkflowVariable("alice","BIG","x".repeat(20_000))).rejects.toThrow("invalid");});
+});
diff --git a/lib/workflow/variables.ts b/lib/workflow/variables.ts
new file mode 100644
index 00000000..7b5ba288
--- /dev/null
+++ b/lib/workflow/variables.ts
@@ -0,0 +1,20 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { agentSessionsDir } from "@/lib/agent/session-paths";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { workflowGraphOwner } from "./graph-store";
+
+export type WorkflowVariableValue = string | number | boolean | null | Record<string, unknown> | unknown[];
+type Row = { value: WorkflowVariableValue; secret: boolean; updatedAt: string };
+type Store = { version: 1; owner: string; values: Record<string, Row> };
+const KEY = /^[A-Z][A-Z0-9_]{0,63}$/;
+function file(owner: string) { if (!/^[a-f0-9]{64}$/.test(owner)) throw new Error("invalid workflow variable owner"); return path.join(agentSessionsDir(), ".workflow-variables", owner, "variables.json"); }
+async function read(owner: string): Promise<Store> { try { const target=file(owner), stat=await fs.lstat(target); if(!stat.isFile()||stat.isSymbolicLink()||stat.size>256*1024||(stat.mode&0o077)) throw new Error("unsafe workflow variable store"); const row=JSON.parse(await fs.readFile(target,"utf8")) as Store; if(row.version!==1||row.owner!==owner||!row.values||typeof row.values!=="object") throw new Error("invalid workflow variable store"); return row; } catch(error){ if((error as NodeJS.ErrnoException).code==="ENOENT") return {version:1,owner,values:{}}; throw error; } }
+async function write(store: Store){ const target=file(store.owner),dir=path.dirname(target); await fs.mkdir(dir,{recursive:true,mode:0o700}); const body=JSON.stringify(store),tmp=`${target}.${randomUUID()}.tmp`; if(Buffer.byteLength(body)>256*1024) throw new Error("workflow variable store too large"); try{await fs.writeFile(tmp,body,{flag:"wx",mode:0o600});await fs.rename(tmp,target);}finally{await fs.unlink(tmp).catch(()=>undefined);} }
+function validValue(value: unknown): asserts value is WorkflowVariableValue { const body=JSON.stringify(value); if(value===undefined||!body||Buffer.byteLength(body)>16*1024) throw new Error("workflow variable value invalid"); }
+export async function listWorkflowVariables(principal:string){ const owner=workflowGraphOwner(principal),store=await read(owner); return Object.entries(store.values).sort(([a],[b])=>a.localeCompare(b)).map(([key,row])=>({key,secret:row.secret,updatedAt:row.updatedAt,...(!row.secret?{value:structuredClone(row.value)}:{})})); }
+export async function setWorkflowVariable(principal:string,key:string,value:unknown,secret=false){ if(!KEY.test(key)) throw new Error("workflow variable key must be A-Z, 0-9, underscore"); validValue(value); const owner=workflowGraphOwner(principal); return withSecurityStoreLock(file(owner),async()=>{const store=await read(owner); if(!Object.hasOwn(store.values,key)&&Object.keys(store.values).length>=128) throw new Error("workflow variable limit reached"); store.values[key]={value:structuredClone(value),secret:Boolean(secret),updatedAt:new Date().toISOString()}; await write(store); return {key,secret:Boolean(secret),updatedAt:store.values[key]!.updatedAt};}); }
+export async function deleteWorkflowVariable(principal:string,key:string){ const owner=workflowGraphOwner(principal); return withSecurityStoreLock(file(owner),async()=>{const store=await read(owner); delete store.values[key]; await write(store); return {key,deleted:true};}); }
+export async function workflowVariableValues(principal:string){ const owner=workflowGraphOwner(principal),store=await read(owner); return Object.fromEntries(Object.entries(store.values).map(([key,row])=>[key,structuredClone(row.value)])); }
+export async function workflowSecretValues(principal:string){ const owner=workflowGraphOwner(principal),store=await read(owner); return Object.values(store.values).filter((row)=>row.secret).map((row)=>row.value).filter((value):value is string=>typeof value==="string"&&value.length>=4); }
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 158bb6e8..cf806920 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -25,7 +25,7 @@ U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_doctor="doctor [--fix]"
U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"
-U_workflow="workflow list|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]"
+U_workflow="workflow list|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"
U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
diff --git a/scripts/cli/workflows.sh b/scripts/cli/workflows.sh
index e9d959fa..052500f6 100644
--- a/scripts/cli/workflows.sh
+++ b/scripts/cli/workflows.sh
@@ -1,16 +1,20 @@
#!/usr/bin/env bash
-# Workflow Graph v2 CLI. Uses the same authenticated private API as the native Workflows app.
+# Workflow Graph CLI. Same private API as native Workflows app and workflow_graph MCP tool.
run_workflow() {
- local sub="${1:-list}" id="" input='{}' key="" revision="" wait=0 body result
+ local sub="${1:-list}" id="" input='{}' key="" revision="" version="" wait=0 secret=false query="" prompt="" result body
shift || true
case "$sub" in
- show|save|clone|delete|run|status) id="${1:?workflow/run id required}"; shift ;;
+ show|save|clone|delete|run|status|runs|versions|restore|template|variable-set|variable-delete) id="${1:?workflow/id required}"; shift ;;
esac
while [ $# -gt 0 ]; do
case "$1" in
--input) input="${2:?JSON or @file required}"; shift 2 ;;
--key) key="${2:?idempotency key required}"; shift 2 ;;
- --revision) revision="${2:?revision required}"; shift 2 ;;
+ --revision) revision="${2:?current revision required}"; shift 2 ;;
+ --version) version="${2:?saved version revision required}"; shift 2 ;;
+ --query) query="${2:-}"; shift 2 ;;
+ --prompt) prompt="${2:?prompt required}"; shift 2 ;;
+ --secret) secret=true; shift ;;
--wait) wait=1; shift ;;
*) die "unknown workflow option: $1" ;;
esac
@@ -19,30 +23,24 @@ run_workflow() {
case "$sub" in
list) jget "/api/v1/workflows"; return ;;
show) jget "/api/v1/workflows?graph_id=$(enc "$id")"; return ;;
+ runs) jget "/api/v1/workflows?runs=1&graph_id=$(enc "$id")"; return ;;
+ versions) jget "/api/v1/workflows?versions=$(enc "$id")"; return ;;
+ catalog) jget "/api/v1/workflows?catalog=1&q=$(enc "$query")"; return ;;
+ templates) jget "/api/v1/workflows?templates=1"; return ;;
+ variables) jget "/api/v1/workflows?variables=1"; return ;;
status) result=$(jget "/api/v1/workflows?run_id=$(enc "$id")&wait_ms=$((wait * 1500))") ;;
- create)
- body=$(jq -n --argjson graph "$input" '{action:"create",graph:$graph}')
- jpost "/api/v1/workflows" "$body"; return ;;
- save)
- [ -n "$revision" ] || die "workflow save requires --revision from workflow show/list"
- body=$(jq -n --arg id "$id" --arg revision "$revision" --argjson graph "$input" '{action:"update",graph_id:$id,expected_revision:$revision,graph:$graph}')
- jpost "/api/v1/workflows" "$body"; return ;;
- clone)
- body=$(jq -n --arg id "$id" '{action:"clone",graph_id:$id}')
- jpost "/api/v1/workflows" "$body"; return ;;
- delete)
- [ -n "$revision" ] || die "workflow delete requires --revision from workflow show/list"
- body=$(jq -n --arg id "$id" --arg revision "$revision" '{action:"delete",graph_id:$id,expected_revision:$revision}')
- jpost "/api/v1/workflows" "$body"; return ;;
- run)
- [ -n "$key" ] || die "workflow run requires --key <unique-operation-id>; retries must reuse it"
- body=$(jq -n --arg id "$id" --arg key "$key" --argjson input "$input" '{action:"run",graph_id:$id,input:$input,idempotency_key:$key}')
- result=$(jpost "/api/v1/workflows" "$body"); id=$(jq -er .id <<<"$result") ;;
+ create) body=$(jq -n --argjson graph "$input" '{action:"create",graph:$graph}'); jpost "/api/v1/workflows" "$body"; return ;;
+ save) [ -n "$revision" ] || die "workflow save requires --revision"; body=$(jq -n --arg id "$id" --arg revision "$revision" --argjson graph "$input" '{action:"update",graph_id:$id,expected_revision:$revision,graph:$graph}'); jpost "/api/v1/workflows" "$body"; return ;;
+ clone) body=$(jq -n --arg id "$id" '{action:"clone",graph_id:$id}'); jpost "/api/v1/workflows" "$body"; return ;;
+ delete) [ -n "$revision" ] || die "workflow delete requires --revision"; body=$(jq -n --arg id "$id" --arg revision "$revision" '{action:"delete",graph_id:$id,expected_revision:$revision}'); jpost "/api/v1/workflows" "$body"; return ;;
+ restore) [ -n "$revision" ] && [ -n "$version" ] || die "workflow restore requires --revision <current> --version <saved>"; body=$(jq -n --arg id "$id" --arg current "$revision" --arg version "$version" '{action:"restore_version",graph_id:$id,expected_revision:$current,revision:$version}'); jpost "/api/v1/workflows" "$body"; return ;;
+ template) body=$(jq -n --arg id "$id" '{action:"create_from_template",template_id:$id}'); jpost "/api/v1/workflows" "$body"; return ;;
+ variable-set) body=$(jq -n --arg key "$id" --argjson value "$input" --argjson secret "$secret" '{action:"variable_set",key:$key,value:$value,secret:$secret}'); jpost "/api/v1/workflows" "$body"; return ;;
+ variable-delete) body=$(jq -n --arg key "$id" '{action:"variable_delete",key:$key}'); jpost "/api/v1/workflows" "$body"; return ;;
+ ai) [ -n "$prompt" ] || die "workflow ai requires --prompt"; body=$(jq -n --arg prompt "$prompt" '{action:"ai_suggest",prompt:$prompt}'); jpost "/api/v1/workflows" "$body"; return ;;
+ run) [ -n "$key" ] || die "workflow run requires --key <unique-operation-id>"; body=$(jq -n --arg id "$id" --arg key "$key" --argjson input "$input" '{action:"run",graph_id:$id,input:$input,idempotency_key:$key}'); result=$(jpost "/api/v1/workflows" "$body"); id=$(jq -er .id <<<"$result") ;;
*) die "usage: mso ${U_workflow:-workflow}" ;;
esac
- while [ "$wait" -eq 1 ] && [ "$(jq -r .state <<<"$result")" = running ]; do
- result=$(jget "/api/v1/workflows?run_id=$(enc "$id")&wait_ms=1500")
- done
- printf '%s\n' "$result"
- case "$(jq -r .state <<<"$result")" in failed|interrupted) return 1 ;; esac
+ while [ "$wait" -eq 1 ] && [ "$(jq -r .state <<<"$result")" = running ]; do result=$(jget "/api/v1/workflows?run_id=$(enc "$id")&wait_ms=1500"); done
+ printf '%s\n' "$result"; case "$(jq -r .state <<<"$result")" in failed|interrupted) return 1 ;; esac
}