Skip to content

Self-improving AI Employees for everyone

feat(schema): Wave 6 - backend NodeSpec contract + frontend scaffolding (Phases 1-3a)

trohitg1d8670bf7b63
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index ed8500ba..d784932d 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -12,7 +12,8 @@ import {
Node,
Edge,
} from 'reactflow';
-import GenericNode from './components/GenericNode';
+import { featureFlags } from './lib/featureFlags';
+import { prefetchAllNodeSpecs } from './lib/nodeSpec';
import AIAgentNode from './components/AIAgentNode';
import ModelNode from './components/ModelNode';
import SquareNode from './components/SquareNode';
@@ -177,7 +178,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
// Any node with 'service' group uses SquareNode component
types[type] = SquareNode;
} else {
- types[type] = GenericNode;
+ types[type] = SquareNode;
}
});
@@ -462,6 +463,16 @@ const DashboardContent: React.FC = () => {
loadUIDefaults();
}, [isConnected, sendRequest, applyUIDefaults]);
+ // Wave 6 Phase 2: warm the NodeSpec cache in the background once the
+ // WS is up. No-op when VITE_NODESPEC_BACKEND is off.
+ const hasPrefetchedSpecs = React.useRef(false);
+ React.useEffect(() => {
+ if (!isConnected || hasPrefetchedSpecs.current) return;
+ if (!featureFlags.nodeSpecBackend) return;
+ hasPrefetchedSpecs.current = true;
+ void prefetchAllNodeSpecs(sendRequest);
+ }, [isConnected, sendRequest]);
+
// Update nodes with execution status classes
const styledNodes = React.useMemo(() => {
return nodes.map(node => {
diff --git a/client/src/adapters/nodeSpecToDescription.ts b/client/src/adapters/nodeSpecToDescription.ts
new file mode 100644
index 00000000..6c3e7d14
--- /dev/null
+++ b/client/src/adapters/nodeSpecToDescription.ts
@@ -0,0 +1,168 @@
+/**
+ * Adapter: backend NodeSpec (wire format) → legacy INodeTypeDescription.
+ *
+ * Wave 6 Phase 2 bridge. Consumers still read INodeTypeDescription today;
+ * this adapter lets us switch the source from frontend-owned
+ * `nodeDefinitions/*.ts` to the server-emitted NodeSpec without a big-bang
+ * refactor of every consumer. The adapter is intentionally thin — it
+ * translates JSON-Schema-shaped input properties into the
+ * INodeProperties[] array the parameter panel expects.
+ *
+ * Phase 6 (capstone) inlines this adapter once all consumers read NodeSpec
+ * directly; for now it's the seam that makes Phase 3's per-file deletions
+ * safe.
+ */
+
+import type {
+ INodeProperties,
+ INodeTypeDescription,
+ NodeConnectionType,
+} from '../types/INodeProperties';
+
+/** Wire shape emitted by GET /api/schemas/nodes/{type}/spec.json. */
+export interface NodeSpec {
+ type: string;
+ displayName: string;
+ icon: string;
+ group: string[];
+ description?: string;
+ subtitle?: string;
+ version: number;
+ /** JSON Schema 7 document describing input parameters (Pydantic-derived). */
+ inputs?: JsonSchema;
+ /** JSON Schema 7 document describing runtime output (Wave 3 contract). */
+ outputs?: JsonSchema;
+ credentials?: string[];
+ uiHints?: Record<string, unknown>;
+}
+
+interface JsonSchema {
+ type?: string;
+ properties?: Record<string, JsonSchemaProperty>;
+ required?: string[];
+ additionalProperties?: boolean | JsonSchema;
+ title?: string;
+ description?: string;
+}
+
+interface JsonSchemaProperty {
+ type?: string | string[];
+ title?: string;
+ description?: string;
+ default?: unknown;
+ enum?: unknown[];
+ minimum?: number;
+ maximum?: number;
+ format?: string;
+ anyOf?: JsonSchemaProperty[];
+ items?: JsonSchemaProperty;
+ additionalProperties?: boolean | JsonSchemaProperty;
+ /** Editor hints lifted from Pydantic Field(json_schema_extra=...). */
+ uiHints?: Record<string, unknown>;
+}
+
+type InodeType = INodeProperties['type'];
+
+/**
+ * Convert a JSON Schema property → INodeProperties.type value expected
+ * by the parameter renderer. Prefers `enum` → `options`, then falls back
+ * to the JSON Schema primitive type. Unknown shapes map to `string` so
+ * the user sees an editable field rather than a blank slot.
+ */
+function mapPropertyType(prop: JsonSchemaProperty): InodeType {
+ if (prop.enum && prop.enum.length > 0) return 'options';
+ if (prop.uiHints?.editor === 'code') return 'code';
+ if (prop.uiHints?.editor === 'json') return 'json';
+ // anyOf([T, null]) is the Pydantic Optional[T] pattern — take the non-null branch.
+ if (prop.anyOf) {
+ const nonNull = prop.anyOf.find(b => b.type && b.type !== 'null');
+ if (nonNull) return mapPropertyType(nonNull);
+ }
+ const t = Array.isArray(prop.type) ? prop.type[0] : prop.type;
+ switch (t) {
+ case 'boolean':
+ return 'boolean';
+ case 'integer':
+ case 'number':
+ return 'number';
+ case 'array':
+ return 'collection';
+ case 'object':
+ return 'fixedCollection';
+ case 'string':
+ default:
+ return 'string';
+ }
+}
+
+function toInodeProperty(name: string, prop: JsonSchemaProperty): INodeProperties {
+ const type = mapPropertyType(prop);
+ const options = prop.enum?.map(v => ({ name: String(v), value: v as string | number | boolean }));
+ const out: INodeProperties = {
+ displayName: prop.title || name,
+ name,
+ type,
+ default: prop.default,
+ description: prop.description,
+ options,
+ };
+ if (prop.minimum !== undefined || prop.maximum !== undefined) {
+ out.typeOptions = {
+ ...(prop.minimum !== undefined ? { minValue: prop.minimum } : {}),
+ ...(prop.maximum !== undefined ? { maxValue: prop.maximum } : {}),
+ };
+ }
+ // Lift Pydantic json_schema_extra hints (displayOptions, loadOptionsMethod, etc.)
+ const hints = prop.uiHints;
+ if (hints) {
+ if (hints.displayOptions) out.displayOptions = hints.displayOptions as INodeProperties['displayOptions'];
+ if (hints.loadOptionsMethod) {
+ out.typeOptions = {
+ ...out.typeOptions,
+ loadOptionsMethod: hints.loadOptionsMethod as string,
+ ...(hints.loadOptionsDependsOn ? { loadOptionsDependsOn: hints.loadOptionsDependsOn as string[] } : {}),
+ };
+ }
+ }
+ return out;
+}
+
+/**
+ * Derive the INodeTypeDescription.inputs/outputs handle shape. When the
+ * backend NodeSpec doesn't yet carry handle configs (Phase 1/2 stub),
+ * default to a single 'main' handle — matches the legacy nodeDefinitions
+ * default and keeps React Flow happy.
+ */
+function defaultHandles(): NodeConnectionType[] {
+ return ['main' as NodeConnectionType];
+}
+
+/**
+ * Top-level conversion. Adapter is pure — no side effects, no throws.
+ * Missing fields become sensible defaults so the parameter panel always
+ * has something to render.
+ */
+export function nodeSpecToDescription(spec: NodeSpec): INodeTypeDescription {
+ const propsObject = spec.inputs?.properties ?? {};
+ const properties: INodeProperties[] = Object.entries(propsObject).map(
+ ([name, prop]) => toInodeProperty(name, prop),
+ );
+
+ return {
+ displayName: spec.displayName,
+ name: spec.type,
+ icon: spec.icon,
+ group: spec.group ?? [],
+ version: spec.version ?? 1,
+ subtitle: spec.subtitle,
+ description: spec.description ?? '',
+ defaults: {
+ name: spec.displayName,
+ },
+ inputs: defaultHandles(),
+ outputs: defaultHandles(),
+ properties,
+ credentials: spec.credentials?.map(name => ({ name })),
+ uiHints: spec.uiHints as INodeTypeDescription['uiHints'],
+ };
+}
diff --git a/client/src/lib/featureFlags.ts b/client/src/lib/featureFlags.ts
new file mode 100644
index 00000000..aea76686
--- /dev/null
+++ b/client/src/lib/featureFlags.ts
@@ -0,0 +1,33 @@
+/**
+ * Feature flags read from Vite env (`import.meta.env.VITE_*`).
+ *
+ * Flags that gate in-flight migration work — flip them to `true` in
+ * `.env.local` to opt the dev build into the new path. Wave 6 uses
+ * `VITE_NODESPEC_BACKEND` to gate the backend-driven NodeSpec flow
+ * alongside the legacy `nodeDefinitions/*.ts` flow.
+ *
+ * Keep this module tiny and dep-free — it is imported from render-path
+ * components and should never force a React Query dep at top-level.
+ */
+
+const readEnv = (key: string): string | undefined => {
+ try {
+ return (import.meta as any).env?.[key];
+ } catch {
+ return undefined;
+ }
+};
+
+const isTruthy = (value: string | undefined): boolean => {
+ if (!value) return false;
+ const v = value.trim().toLowerCase();
+ return v === 'true' || v === '1' || v === 'yes' || v === 'on';
+};
+
+export const featureFlags = {
+ /** Wave 6 Phase 2: fetch NodeSpec from the backend instead of
+ * reading from client/src/nodeDefinitions/*.ts. Off by default. */
+ nodeSpecBackend: isTruthy(readEnv('VITE_NODESPEC_BACKEND')),
+} as const;
+
+export type FeatureFlags = typeof featureFlags;
diff --git a/client/src/lib/nodeSpec.ts b/client/src/lib/nodeSpec.ts
new file mode 100644
index 00000000..53ef41ca
--- /dev/null
+++ b/client/src/lib/nodeSpec.ts
@@ -0,0 +1,91 @@
+/**
+ * NodeSpec fetch + resolve utilities.
+ *
+ * Wave 6 Phase 2. Thin wrapper around TanStack Query's `fetchQuery`
+ * mirroring the Wave 3 pattern at InputSection.tsx:28-36 — no new hook
+ * file, just a shared async helper so every consumer can opt in behind
+ * the VITE_NODESPEC_BACKEND flag without duplicating boilerplate.
+ *
+ * Query key convention: ['nodeSpec', nodeType]
+ * Stale time: Infinity (node shapes only change with a deploy).
+ *
+ * See C:\\Users\\Tgroh\\.claude\\plans\\typed-splashing-crown.md.
+ */
+
+import { nodeSpecToDescription, type NodeSpec } from '../adapters/nodeSpecToDescription';
+import type { INodeTypeDescription } from '../types/INodeProperties';
+import { featureFlags } from './featureFlags';
+import { queryClient } from './queryClient';
+
+type SendRequest = (type: string, data?: any) => Promise<any>;
+
+export const nodeSpecQueryKey = (nodeType: string) => ['nodeSpec', nodeType] as const;
+
+/**
+ * Fetch a single NodeSpec via the WS handler, caching per node type.
+ * Returns `null` when the type is unknown on the backend — callers fall
+ * back to the legacy `nodeDefinitions/*` entry.
+ */
+export async function fetchNodeSpec(
+ nodeType: string,
+ sendRequest: SendRequest,
+): Promise<NodeSpec | null> {
+ return queryClient.fetchQuery({
+ queryKey: nodeSpecQueryKey(nodeType),
+ queryFn: async () => {
+ try {
+ const response = await sendRequest('get_node_spec', { node_type: nodeType });
+ return (response?.spec ?? null) as NodeSpec | null;
+ } catch {
+ return null;
+ }
+ },
+ staleTime: Infinity,
+ });
+}
+
+/**
+ * Prefetch every node type the backend knows about, in a single idle
+ * burst at editor boot. Non-blocking — failures are swallowed so a flaky
+ * WS doesn't block UI. Matches Activepieces' summary+lazy pattern.
+ */
+export async function prefetchAllNodeSpecs(sendRequest: SendRequest): Promise<void> {
+ try {
+ const response = await sendRequest('list_node_specs', {});
+ const nodeTypes: string[] = response?.node_types ?? [];
+ await Promise.all(nodeTypes.map(t => fetchNodeSpec(t, sendRequest)));
+ } catch {
+ // Prefetch is best-effort — logged by the WS layer, not us.
+ }
+}
+
+/**
+ * Synchronous read of a previously-cached NodeSpec. Used by flag-gated
+ * render paths that need a description on-demand without suspending.
+ * Returns `null` if not yet fetched.
+ */
+export function getCachedNodeSpec(nodeType: string): NodeSpec | null {
+ return queryClient.getQueryData<NodeSpec | null>(nodeSpecQueryKey(nodeType)) ?? null;
+}
+
+/**
+ * Flag-gated resolver. When `VITE_NODESPEC_BACKEND` is off (default),
+ * returns `localFallback` unchanged — legacy `nodeDefinitions/*` wins.
+ * When on, returns the adapter output from the cached NodeSpec, or
+ * falls through to `localFallback` if the spec hasn't arrived yet.
+ *
+ * Phase 3 sub-commits use this seam to delete legacy definitions one
+ * file group at a time: once a group's NodeSpec is seeded on the
+ * backend, the local fallback can drop to a minimal stub (or vanish).
+ */
+export function resolveNodeDescription(
+ nodeType: string,
+ localFallback: INodeTypeDescription | null | undefined,
+): INodeTypeDescription | null {
+ if (!featureFlags.nodeSpecBackend) {
+ return localFallback ?? null;
+ }
+ const spec = getCachedNodeSpec(nodeType);
+ if (spec) return nodeSpecToDescription(spec);
+ return localFallback ?? null;
+}
diff --git a/server/models/node_metadata.py b/server/models/node_metadata.py
new file mode 100644
index 00000000..ca51ee77
--- /dev/null
+++ b/server/models/node_metadata.py
@@ -0,0 +1,139 @@
+"""Per-node display metadata.
+
+Receives the UI-only fields (``displayName``, ``icon``, ``group``,
+``subtitle``, ``description``) that today live in the frontend
+``client/src/nodeDefinitions/*.ts`` files. Wave 6 Phase 3 migrates each
+node-definition file's display metadata into this dict; until then
+NodeSpec falls back to the node type id for missing entries.
+
+Single source of truth for everything the parameter panel + palette
+needs to render a node header. Kept as a plain dict (not Pydantic) for
+fast iteration during the migration — switch to a TypedDict / Pydantic
+model once the schema stabilises.
+"""
+
+from typing import Any, Optional, TypedDict
+
+
+class NodeMetadata(TypedDict, total=False):
+ displayName: str
+ icon: str
+ group: list[str]
+ subtitle: str
+ description: str
+ version: int
+
+
+# Seeded incrementally per Wave 6 Phase 3 sub-commit. Sub-commit 3a
+# covers utility + code + process + workflow groups (12 types). Later
+# sub-commits add messaging (3b), agents/models (3c), and the rest.
+# Source: client/src/nodeDefinitions/*.ts at the time of migration.
+NODE_METADATA: dict[str, NodeMetadata] = {
+ # Workflow group ---------------------------------------------------------
+ "start": {
+ "displayName": "Start",
+ "icon": "▶",
+ "group": ["workflow"],
+ "description": "Starting point for workflow execution. Provides initial data to connected nodes.",
+ "version": 1,
+ },
+ "taskTrigger": {
+ "displayName": "Task Completed",
+ "icon": "📨",
+ "group": ["trigger", "workflow"],
+ "description": "Triggers when a delegated child agent completes its task (success or error)",
+ "version": 1,
+ },
+ # Utility group ----------------------------------------------------------
+ "httpRequest": {
+ "displayName": "HTTP Request",
+ "icon": "🌐",
+ "group": ["utility", "tool"],
+ "description": "Make HTTP requests to external APIs",
+ "version": 1,
+ },
+ "webhookTrigger": {
+ "displayName": "Webhook Trigger",
+ "icon": "🪝",
+ "group": ["trigger"],
+ "description": "Start workflow when HTTP request is received",
+ "version": 1,
+ },
+ "webhookResponse": {
+ "displayName": "Webhook Response",
+ "icon": "↩️",
+ "group": ["utility"],
+ "description": "Send response back to webhook caller",
+ "version": 1,
+ },
+ "chatTrigger": {
+ "displayName": "Chat Trigger",
+ "icon": "💬",
+ "group": ["utility", "trigger"],
+ "description": "Trigger workflow when user sends a chat message from the console input",
+ "version": 1,
+ },
+ "console": {
+ "displayName": "Console",
+ "icon": "🖥️",
+ "group": ["utility"],
+ "description": "Log data to console panel for debugging during execution",
+ "version": 1,
+ },
+ "teamMonitor": {
+ "displayName": "Team Monitor",
+ "icon": "📊",
+ "group": ["utility", "agent"],
+ "description": "Monitor agent team operations, tasks, and messages in real-time",
+ "version": 1,
+ },
+ # Code group -------------------------------------------------------------
+ "pythonExecutor": {
+ "displayName": "Python Executor",
+ "icon": "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/python/python-original.svg",
+ "group": ["code", "tool"],
+ "description": "Execute Python code with input data access",
+ "version": 1,
+ },
+ "javascriptExecutor": {
+ "displayName": "JavaScript Executor",
+ "icon": "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/javascript/javascript-original.svg",
+ "group": ["code", "tool"],
+ "description": "Execute JavaScript code with input data access",
+ "version": 1,
+ },
+ "typescriptExecutor": {
+ "displayName": "TypeScript Executor",
+ "icon": "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/typescript/typescript-original.svg",
+ "group": ["code", "tool"],
+ "description": "Execute TypeScript code with input data access and type safety",
+ "version": 1,
+ },
+ # Process management -----------------------------------------------------
+ "processManager": {
+ "displayName": "Process Manager",
+ "icon": "⚙️",
+ "group": ["utility", "tool"],
+ "description": "Start, stop, and manage long-running processes (dev servers, watchers, build tools). Streams output to Terminal tab.",
+ "version": 1,
+ },
+}
+
+
+def get_node_metadata(node_type: str) -> Optional[NodeMetadata]:
+ """Return display metadata for a node type, or None if not seeded."""
+
+ return NODE_METADATA.get(node_type)
+
+
+def fallback_metadata(node_type: str) -> NodeMetadata:
+ """Minimal metadata for a node type without a seeded entry. Keeps
+ NodeSpec emission valid even before Phase 3 migrations land."""
+
+ return {
+ "displayName": node_type,
+ "icon": "",
+ "group": [],
+ "description": "",
+ "version": 1,
+ }
diff --git a/server/models/nodes.py b/server/models/nodes.py
index 55149589..b47fc2bc 100644
--- a/server/models/nodes.py
+++ b/server/models/nodes.py
@@ -203,6 +203,26 @@ class JavaScriptExecutorParams(BaseNodeParams):
timeout: int = Field(default=30, ge=1, le=300)
+class TypeScriptExecutorParams(BaseNodeParams):
+ """Parameters for TypeScript code executor node (compiles to JS
+ via the Node.js server with tsx)."""
+ type: Literal["typescriptExecutor"]
+ code: str = ""
+ timeout: int = Field(default=30, ge=1, le=300)
+
+
+class ProcessManagerParams(BaseNodeParams):
+ """Parameters for long-running process manager node."""
+ type: Literal["processManager"]
+ tool_name: str = Field(default="process_manager", alias="toolName")
+ tool_description: str = Field(default="", alias="toolDescription")
+ operation: Literal["start", "stop", "restart", "send_input", "list", "get_output"] = "start"
+ name: str = ""
+ command: str = ""
+ cwd: Optional[str] = None
+ input: Optional[str] = None
+
+
# =============================================================================
# HTTP NODE MODELS
# =============================================================================
@@ -233,6 +253,22 @@ class WebhookResponseParams(BaseNodeParams):
body: str = ""
+class ConsoleParams(BaseNodeParams):
+ """Parameters for console log node (passes input through)."""
+ type: Literal["console"]
+ label: str = ""
+ log_mode: Literal["full", "field", "expression"] = Field(default="full", alias="logMode")
+ field_path: str = Field(default="", alias="fieldPath")
+ expression: str = ""
+ format: Literal["json", "text", "table"] = "json"
+
+
+class TeamMonitorParams(BaseNodeParams):
+ """Parameters for agent-team monitor node."""
+ type: Literal["teamMonitor"]
+ refresh_interval: int = Field(default=0, alias="refreshInterval", ge=0, le=60_000)
+
+
# =============================================================================
# WORKFLOW CONTROL NODE MODELS
# =============================================================================
@@ -393,9 +429,13 @@ KnownNodeParams = Annotated[
# WhatsApp
WhatsAppSendParams, WhatsAppReceiveParams, WhatsAppDbParams,
# Code
- PythonExecutorParams, JavaScriptExecutorParams,
+ PythonExecutorParams, JavaScriptExecutorParams, TypeScriptExecutorParams,
+ # Process management
+ ProcessManagerParams,
# HTTP
HttpRequestParams, WebhookTriggerParams, WebhookResponseParams,
+ # Utility
+ ConsoleParams, TeamMonitorParams,
# Workflow
StartNodeParams, CronSchedulerParams, WorkflowTriggerParams,
# Triggers
diff --git a/server/routers/schemas.py b/server/routers/schemas.py
index f4229fb2..f1ab2dea 100644
--- a/server/routers/schemas.py
+++ b/server/routers/schemas.py
@@ -9,13 +9,20 @@ for the frontend consumer (useNodeOutputSchemaQuery).
from fastapi import APIRouter, HTTPException, Response
+from services.node_input_schemas import (
+ get_node_input_schema,
+ list_node_types_with_input_schema,
+)
from services.node_output_schemas import (
get_node_output_schema,
list_node_types_with_schema,
)
+from services.node_spec import get_node_spec, list_node_types_with_spec
router = APIRouter(prefix="/api/schemas", tags=["schemas"])
+_LONG_CACHE = "public, max-age=86400"
+
@router.get("/nodes/{node_type}.json")
async def get_node_schema(node_type: str, response: Response):
@@ -32,7 +39,7 @@ async def get_node_schema(node_type: str, response: Response):
schema = get_node_output_schema(node_type)
if schema is None:
raise HTTPException(status_code=404, detail=f"No schema for node type {node_type!r}")
- response.headers["Cache-Control"] = "public, max-age=86400"
+ response.headers["Cache-Control"] = _LONG_CACHE
return schema
@@ -42,3 +49,43 @@ async def list_schemas():
uses this to know which types it can query without probing 404s."""
return {"node_types": list_node_types_with_schema()}
+
+
[email protected]("/nodes/{node_type}/input.json")
+async def get_node_input(node_type: str, response: Response):
+ """Return the JSON Schema for a node type's input parameters.
+
+ Wave 6 Phase 1: parallels the output endpoint above. 404 when no
+ Pydantic model is registered for the type — frontend falls back to
+ the legacy nodeDefinitions/* properties array until Phase 3 lands.
+ """
+
+ schema = get_node_input_schema(node_type)
+ if schema is None:
+ raise HTTPException(status_code=404, detail=f"No input schema for {node_type!r}")
+ response.headers["Cache-Control"] = _LONG_CACHE
+ return schema
+
+
[email protected]("/nodes/{node_type}/spec.json")
+async def get_node_spec_endpoint(node_type: str, response: Response):
+ """Return the unified NodeSpec envelope (display metadata + input
+ schema + output schema) for a node type.
+
+ Wave 6 Phase 1: this is the single endpoint Phase 2's editor consumer
+ talks to. 404 when neither an input model nor an output schema is
+ registered (unknown type)."""
+
+ spec = get_node_spec(node_type)
+ if spec is None:
+ raise HTTPException(status_code=404, detail=f"No NodeSpec for {node_type!r}")
+ response.headers["Cache-Control"] = _LONG_CACHE
+ return spec
+
+
[email protected]("/nodes/specs")
+async def list_specs():
+ """List every node type with at least an input model or an output
+ schema. Editor uses this on boot to prefetch the full set."""
+
+ return {"node_types": list_node_types_with_spec()}
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 841d714a..441f9e1b 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -253,6 +253,31 @@ async def handle_get_node_output_schema(
return {"node_type": data["node_type"], "schema": schema}
+@ws_handler("node_type")
+async def handle_get_node_spec(
+ data: Dict[str, Any], websocket: WebSocket
+) -> Dict[str, Any]:
+ """Return the unified NodeSpec (input schema + output schema +
+ display metadata) for a node type, or ``{spec: null}`` when the
+ type is unknown. Wave 6 Phase 2 WS mirror of the REST endpoint
+ GET /api/schemas/nodes/{type}/spec.json."""
+ from services.node_spec import get_node_spec
+
+ spec = get_node_spec(data["node_type"])
+ return {"node_type": data["node_type"], "spec": spec}
+
+
+@ws_handler()
+async def handle_list_node_specs(
+ data: Dict[str, Any], websocket: WebSocket
+) -> Dict[str, Any]:
+ """Return the sorted list of node types that have a NodeSpec.
+ Editor calls this on boot to prefetch the whole set."""
+ from services.node_spec import list_node_types_with_spec
+
+ return {"node_types": list_node_types_with_spec()}
+
+
# ============================================================================
# Credential Registry Handler (Nango-style bulk fetch for 20 -> 5000 providers)
# ============================================================================
@@ -3160,6 +3185,9 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
# Node output schemas (Pydantic-backed registry; see
# docs-internal/schema_source_of_truth_rfc.md).
"get_node_output_schema": handle_get_node_output_schema,
+ # Wave 6 Phase 2: unified NodeSpec (input + output + metadata).
+ "get_node_spec": handle_get_node_spec,
+ "list_node_specs": handle_list_node_specs,
# Credential registry (Nango-style bulk catalogue for credentials panel)
"get_credential_catalogue": handle_get_credential_catalogue,
diff --git a/server/services/node_input_schemas.py b/server/services/node_input_schemas.py
new file mode 100644
index 00000000..af0b1481
--- /dev/null
+++ b/server/services/node_input_schemas.py
@@ -0,0 +1,154 @@
+"""Per-node input parameter schema registry.
+
+Mirror of services/node_output_schemas.py but for the input side. Lifts
+the Pydantic models in models/nodes.py into JSON Schema 7 documents the
+editor can drive its parameter panel from. Single source of truth: the
+discriminated-union variants registered in models.nodes. Adding a new
+node type's input schema = add a Pydantic class + register it in
+KnownNodeParams; this module discovers it automatically.
+
+Wave 6 Phase 1 — see C:\\Users\\Tgroh\\.claude\\plans\\typed-splashing-crown.md.
+"""
+
+from typing import Any, Optional
+
+from pydantic import BaseModel
+
+from constants import ANDROID_SERVICE_NODE_TYPES
+from models.nodes import (
+ AIAgentParams, AIChatModelParams, AndroidServiceParams,
+ ChatAgentParams, ChatHistoryParams, ChatSendParams, ChatTriggerParams,
+ ConsoleParams, CreateMapParams, CronSchedulerParams, FileHandlerParams,
+ GmailReceiveParams, GmapsLocationsParams, GmapsNearbyPlacesParams,
+ HttpRequestParams, JavaScriptExecutorParams, ProcessManagerParams,
+ PythonExecutorParams, SimpleMemoryParams, SpecializedAgentParams,
+ StartNodeParams, TaskTriggerParams, TeamMonitorParams,
+ TelegramReceiveParams, TextGeneratorParams, TwitterReceiveParams,
+ TypeScriptExecutorParams, WebhookResponseParams, WebhookTriggerParams,
+ WhatsAppDbParams, WhatsAppReceiveParams, WhatsAppSendParams,
+ WorkflowTriggerParams,
+)
+
+
+# ---------------------------------------------------------------------------
+# Type → Pydantic model registry
+# ---------------------------------------------------------------------------
+# Single-Literal models map directly. SpecializedAgentParams covers many
+# types via its Literal[...] union — we expand at registration time so a
+# type-id lookup is always O(1).
+
+
+_DIRECT_MODELS: dict[str, type[BaseModel]] = {
+ # AI
+ "openaiChatModel": AIChatModelParams,
+ "anthropicChatModel": AIChatModelParams,
+ "geminiChatModel": AIChatModelParams,
+ "openrouterChatModel": AIChatModelParams,
+ "groqChatModel": AIChatModelParams,
+ "cerebrasChatModel": AIChatModelParams,
+ "deepseekChatModel": AIChatModelParams,
+ "kimiChatModel": AIChatModelParams,
+ "mistralChatModel": AIChatModelParams,
+ "aiAgent": AIAgentParams,
+ "chatAgent": ChatAgentParams,
+ "simpleMemory": SimpleMemoryParams,
+ # Maps
+ "gmaps_create": CreateMapParams,
+ "gmaps_locations": GmapsLocationsParams,
+ "gmaps_nearby_places": GmapsNearbyPlacesParams,
+ # WhatsApp
+ "whatsappSend": WhatsAppSendParams,
+ "whatsappReceive": WhatsAppReceiveParams,
+ "whatsappDb": WhatsAppDbParams,
+ # Code
+ "pythonExecutor": PythonExecutorParams,
+ "javascriptExecutor": JavaScriptExecutorParams,
+ "typescriptExecutor": TypeScriptExecutorParams,
+ # Process management
+ "processManager": ProcessManagerParams,
+ # HTTP
+ "httpRequest": HttpRequestParams,
+ "webhookTrigger": WebhookTriggerParams,
+ "webhookResponse": WebhookResponseParams,
+ # Utility
+ "console": ConsoleParams,
+ "teamMonitor": TeamMonitorParams,
+ # Workflow / scheduling
+ "start": StartNodeParams,
+ "cronScheduler": CronSchedulerParams,
+ "timer": WorkflowTriggerParams,
+ # Triggers
+ "taskTrigger": TaskTriggerParams,
+ "chatTrigger": ChatTriggerParams,
+ "telegramReceive": TelegramReceiveParams,
+ "twitterReceive": TwitterReceiveParams,
+ "gmailReceive": GmailReceiveParams,
+ # Text
+ "textGenerator": TextGeneratorParams,
+ "fileHandler": FileHandlerParams,
+ # Chat
+ "chatSend": ChatSendParams,
+ "chatHistory": ChatHistoryParams,
+}
+
+
+# Specialized agents share one Pydantic class but expand across many
+# discriminator values. Pull the literal list from the model itself so
+# the registry stays in sync if the union grows.
+_SPECIALIZED_AGENT_TYPES = (
+ SpecializedAgentParams.model_fields["type"].annotation.__args__
+)
+
+
+NODE_INPUT_MODELS: dict[str, type[BaseModel]] = {
+ **_DIRECT_MODELS,
+ **{t: SpecializedAgentParams for t in _SPECIALIZED_AGENT_TYPES},
+ **{t: AndroidServiceParams for t in ANDROID_SERVICE_NODE_TYPES},
+}
+
+
+# ---------------------------------------------------------------------------
+# Lookup + post-processing
+# ---------------------------------------------------------------------------
+
+
+_schema_cache: dict[str, dict[str, Any]] = {}
+
+
+def get_node_input_schema(node_type: str) -> Optional[dict[str, Any]]:
+ """Return the JSON Schema 7 document for a node's input parameters,
+ or None if the node type has no Pydantic model. Cached per-process."""
+
+ if node_type in _schema_cache:
+ return _schema_cache[node_type]
+ model = NODE_INPUT_MODELS.get(node_type)
+ if model is None:
+ return None
+ schema = _post_process(model.model_json_schema(), node_type)
+ _schema_cache[node_type] = schema
+ return schema
+
+
+def list_node_types_with_input_schema() -> list[str]:
+ """Stable alphabetised list of types with declared input schemas."""
+
+ return sorted(NODE_INPUT_MODELS.keys())
+
+
+def _post_process(schema: dict[str, Any], node_type: str) -> dict[str, Any]:
+ """Strip the discriminator field from the surface schema and lift
+ nested ``$defs`` references inline so the editor doesn't have to
+ resolve them. The discriminator (``type``) is implicit at the
+ transport layer (URL path) and shouldn't render as a parameter."""
+
+ cleaned = dict(schema)
+ props = dict(cleaned.get("properties") or {})
+ props.pop("type", None)
+ cleaned["properties"] = props
+ required = [r for r in (cleaned.get("required") or []) if r != "type"]
+ if required:
+ cleaned["required"] = required
+ elif "required" in cleaned:
+ del cleaned["required"]
+ cleaned["title"] = node_type
+ return cleaned
diff --git a/server/services/node_spec.py b/server/services/node_spec.py
new file mode 100644
index 00000000..272c27c5
--- /dev/null
+++ b/server/services/node_spec.py
@@ -0,0 +1,81 @@
+"""Unified NodeSpec assembly.
+
+A NodeSpec is the wire contract between the editor and the backend's
+node registry — everything the editor needs to render a node into the
+canvas, palette, and parameter panel:
+
+ {
+ "type": "...",
+ "displayName": "...",
+ "icon": "...",
+ "group": ["..."],
+ "version": 1,
+ "inputs": <JSON Schema 7>, # input parameter schema (Wave 6 Phase 1)
+ "outputs": <JSON Schema 7>, # runtime output shape (Wave 3)
+ "credentials": ["..."], # provider keys, derived from handler
+ "uiHints": {...}, # opt-in panel/widget hints
+ }
+
+This module is the single point that fuses the three sources of truth:
+ services/node_input_schemas.NODE_INPUT_MODELS
+ services/node_output_schemas.NODE_OUTPUT_SCHEMAS
+ models/node_metadata.NODE_METADATA
+
+Wave 6 Phase 1 — see C:\\Users\\Tgroh\\.claude\\plans\\typed-splashing-crown.md.
+"""
+
+from typing import Any, Optional
+
+from models.node_metadata import fallback_metadata, get_node_metadata
+from services.node_input_schemas import (
+ NODE_INPUT_MODELS,
+ get_node_input_schema,
+)
+from services.node_output_schemas import (
+ NODE_OUTPUT_SCHEMAS,
+ get_node_output_schema,
+)
+
+
+_spec_cache: dict[str, dict[str, Any]] = {}
+
+
+def get_node_spec(node_type: str) -> Optional[dict[str, Any]]:
+ """Return the full NodeSpec for a node type, or None if neither an
+ input model nor an output schema is registered (i.e. unknown type).
+ Cached per-process; bust by restarting the server."""
+
+ if node_type in _spec_cache:
+ return _spec_cache[node_type]
+
+ inputs = get_node_input_schema(node_type)
+ outputs = get_node_output_schema(node_type)
+ if inputs is None and outputs is None:
+ return None
+
+ meta = get_node_metadata(node_type) or fallback_metadata(node_type)
+ spec: dict[str, Any] = {
+ "type": node_type,
+ "displayName": meta.get("displayName") or node_type,
+ "icon": meta.get("icon", ""),
+ "group": meta.get("group", []),
+ "description": meta.get("description", ""),
+ "version": meta.get("version", 1),
+ }
+ if inputs is not None:
+ spec["inputs"] = inputs
+ if outputs is not None:
+ spec["outputs"] = outputs
+ if "subtitle" in meta:
+ spec["subtitle"] = meta["subtitle"]
+
+ _spec_cache[node_type] = spec
+ return spec
+
+
+def list_node_types_with_spec() -> list[str]:
+ """Stable sorted list of every node type that has at least an input
+ model or an output schema. Editor uses this on boot to know which
+ types it can probe without 404s."""
+
+ return sorted(set(NODE_INPUT_MODELS.keys()) | set(NODE_OUTPUT_SCHEMAS.keys()))
diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.py
new file mode 100644
index 00000000..6415a49d
--- /dev/null
+++ b/server/tests/test_node_spec.py
@@ -0,0 +1,137 @@
+"""Wave 6 Phase 1 — NodeSpec contract tests.
+
+Locks in the public shape emitted by services/node_input_schemas.py,
+services/node_spec.py, and the /api/schemas/nodes/*/spec.json endpoint.
+Mirrors the Wave 3 test posture for node_output_schemas.
+"""
+
+import pytest
+
+from services.node_input_schemas import (
+ NODE_INPUT_MODELS,
+ get_node_input_schema,
+ list_node_types_with_input_schema,
+)
+from services.node_spec import get_node_spec, list_node_types_with_spec
+
+
+class TestInputSchemas:
+ def test_registry_not_empty(self):
+ assert len(NODE_INPUT_MODELS) > 50
+
+ def test_http_request_schema(self):
+ schema = get_node_input_schema("httpRequest")
+ assert schema is not None
+ props = schema["properties"]
+ assert "url" in props
+ assert props["method"]["enum"] == ["GET", "POST", "PUT", "DELETE", "PATCH"]
+ assert props["timeout"]["minimum"] == 1
+ assert props["timeout"]["maximum"] == 300
+ # Discriminator stripped from surface
+ assert "type" not in props
+
+ def test_ai_agent_schema(self):
+ schema = get_node_input_schema("aiAgent")
+ assert schema is not None
+ props = schema["properties"]
+ assert props["temperature"]["minimum"] == 0.0
+ assert props["temperature"]["maximum"] == 2.0
+ # camelCase aliases present
+ assert "apiKey" in props
+ assert "maxTokens" in props
+ assert "systemMessage" in props
+
+ def test_specialized_agents_share_schema(self):
+ # All 16 specialized agents go through SpecializedAgentParams
+ for agent_type in ["android_agent", "coding_agent", "deep_agent"]:
+ assert get_node_input_schema(agent_type) is not None
+
+ def test_android_service_nodes_covered(self):
+ for android_type in ["batteryMonitor", "wifiAutomation", "cameraControl"]:
+ assert get_node_input_schema(android_type) is not None
+
+ def test_unknown_type_returns_none(self):
+ assert get_node_input_schema("nonExistentNodeXyz") is None
+
+ def test_list_sorted(self):
+ types = list_node_types_with_input_schema()
+ assert types == sorted(types)
+
+
+class TestNodeSpec:
+ def test_http_request_spec_envelope(self):
+ spec = get_node_spec("httpRequest")
+ assert spec is not None
+ assert spec["type"] == "httpRequest"
+ assert spec["displayName"] == "HTTP Request"
+ assert "utility" in spec["group"]
+ assert "inputs" in spec
+ assert "outputs" in spec
+ assert spec["version"] == 1
+
+ def test_spec_fallback_metadata_when_unseeded(self):
+ # whatsappSend has input+output schemas but no seeded metadata yet
+ spec = get_node_spec("whatsappSend")
+ assert spec is not None
+ assert spec["type"] == "whatsappSend"
+ # Falls back to type id until Phase 3b migration
+ assert spec["displayName"] == "whatsappSend"
+ assert spec["group"] == []
+
+ def test_spec_missing_entirely(self):
+ assert get_node_spec("nonExistentNodeXyz") is None
+
+ def test_spec_count_at_or_above_100(self):
+ # input (67) + output (98) with overlap ≥ 100 unique types
+ assert len(list_node_types_with_spec()) >= 100
+
+ def test_spec_cached(self):
+ s1 = get_node_spec("httpRequest")
+ s2 = get_node_spec("httpRequest")
+ assert s1 is s2 # same dict object — cache hit
+
+
+class TestPhase3aCoverage:
+ """Phase 3a backend parity: utility + code + process + workflow groups
+ must all have full NodeSpec (input model + display metadata) before
+ Phase 3e flips the VITE_NODESPEC_BACKEND flag."""
+
+ PHASE_3A_TYPES = [
+ # utility
+ "httpRequest", "webhookTrigger", "webhookResponse",
+ "chatTrigger", "console", "teamMonitor",
+ # code
+ "pythonExecutor", "javascriptExecutor", "typescriptExecutor",
+ # process
+ "processManager",
+ # workflow
+ "start", "taskTrigger",
+ ]
+
+ def test_all_have_input_schema(self):
+ from services.node_input_schemas import get_node_input_schema
+ missing = [t for t in self.PHASE_3A_TYPES if get_node_input_schema(t) is None]
+ assert not missing, f"Phase 3a types missing input schema: {missing}"
+
+ def test_all_have_metadata(self):
+ from models.node_metadata import get_node_metadata
+ missing = [t for t in self.PHASE_3A_TYPES if get_node_metadata(t) is None]
+ assert not missing, f"Phase 3a types missing display metadata: {missing}"
+
+ def test_all_have_full_spec(self):
+ for t in self.PHASE_3A_TYPES:
+ spec = get_node_spec(t)
+ assert spec is not None, f"No spec for {t}"
+ assert spec["displayName"] != t, f"{t} fell back to id displayName — metadata missing"
+ assert spec["icon"], f"{t} missing icon"
+ assert spec["group"], f"{t} missing group"
+
+ def test_process_manager_operation_enum(self):
+ spec = get_node_spec("processManager")
+ op = spec["inputs"]["properties"]["operation"]
+ assert op["enum"] == ["start", "stop", "restart", "send_input", "list", "get_output"]
+
+ def test_console_log_mode_enum(self):
+ spec = get_node_spec("console")
+ log_mode = spec["inputs"]["properties"]["logMode"]
+ assert log_mode["enum"] == ["full", "field", "expression"]