Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(plugin): json_schema_extra group= field-grouping + drop api_key from AI agent Params
trohitg85848e969279
diff --git a/client/src/adapters/__tests__/nodeSpecToDescription.test.ts b/client/src/adapters/__tests__/nodeSpecToDescription.test.tsindex d15a4669..32564485 100644--- a/client/src/adapters/__tests__/nodeSpecToDescription.test.ts+++ b/client/src/adapters/__tests__/nodeSpecToDescription.test.ts@@ -252,4 +252,101 @@ describe('nodeSpecToDescription contract', () => {});expect(def.uiHints).toEqual({ isMasterSkillEditor: true, hasCodeEditor: false });});++ // ---- json_schema_extra group convention ---------------------------------++ it('lifts group="X" fields into a synthetic type="collection" parent', () => {+ const def = nodeSpecToDescription({+ type: 'groupedNode',+ displayName: 'Grouped Node',+ icon: 'ποΈ',+ group: ['utility'],+ version: 1,+ inputs: {+ properties: {+ prompt: { type: 'string', title: 'Prompt' },+ temperature: { type: 'number', default: 0.7, group: 'options' },+ max_tokens: { type: 'integer', default: 1000, group: 'options' },+ },+ },+ });+ // prompt stays top-level; temperature + max_tokens absorbed into Options.+ expect(def.properties).toHaveLength(2);+ expect(def.properties[0].name).toBe('prompt');+ const options = def.properties[1];+ expect(options.name).toBe('options');+ expect(options.type).toBe('collection');+ expect(options.displayName).toBe('Options'); // title-cased default+ expect(options.placeholder).toBe('Add Option');+ expect(options.default).toEqual({});+ expect(options.options?.map(o => o.name)).toEqual(['temperature', 'max_tokens']);+ // Children don't carry the private marker.+ expect((options.options?.[0] as any).__group).toBeUndefined();+ });++ it('honours class-level groups metadata overrides', () => {+ const def = nodeSpecToDescription({+ type: 'customGroupsNode',+ displayName: 'Custom Groups',+ icon: 'ποΈ',+ group: ['utility'],+ version: 1,+ inputs: {+ properties: {+ name: { type: 'string' },+ x: { type: 'string', group: 'advanced' },+ y: { type: 'string', group: 'advanced' },+ },+ groups: {+ advanced: { display_name: 'Advanced', placeholder: 'Add Advanced' },+ },+ },+ });+ const advanced = def.properties.find(p => p.name === 'advanced')!;+ expect(advanced).toBeDefined();+ expect(advanced.displayName).toBe('Advanced');+ expect(advanced.placeholder).toBe('Add Advanced');+ expect(advanced.options?.map(o => o.name)).toEqual(['x', 'y']);+ });++ it('places the collection at the position of the first grouped field', () => {+ const def = nodeSpecToDescription({+ type: 'orderedNode',+ displayName: 'Ordered Node',+ icon: 'π',+ group: ['utility'],+ version: 1,+ inputs: {+ properties: {+ a: { type: 'string' },+ grouped1: { type: 'string', group: 'g' },+ b: { type: 'string' },+ grouped2: { type: 'string', group: 'g' },+ c: { type: 'string' },+ },+ },+ });+ // Expected order: a, g (takes grouped1's slot), b, c+ expect(def.properties.map(p => p.name)).toEqual(['a', 'g', 'b', 'c']);+ const g = def.properties.find(p => p.name === 'g')!;+ expect(g.options?.map(o => o.name)).toEqual(['grouped1', 'grouped2']);+ });++ it('leaves ungrouped schemas flat (no regression for legacy plugins)', () => {+ const def = nodeSpecToDescription({+ type: 'flatNode',+ displayName: 'Flat',+ icon: 'β«οΈ',+ group: ['utility'],+ version: 1,+ inputs: {+ properties: {+ a: { type: 'string' },+ b: { type: 'number' },+ },+ },+ });+ expect(def.properties.map(p => p.name)).toEqual(['a', 'b']);+ expect(def.properties.every(p => p.type !== 'collection')).toBe(true);+ });});diff --git a/client/src/adapters/nodeSpecToDescription.ts b/client/src/adapters/nodeSpecToDescription.tsindex 8b5a863c..0459fb6c 100644--- a/client/src/adapters/nodeSpecToDescription.ts+++ b/client/src/adapters/nodeSpecToDescription.ts@@ -61,6 +61,22 @@ interface JsonSchema {additionalProperties?: boolean | JsonSchema;title?: string;description?: string;+ /**+ * Field-group metadata lifted from the Pydantic Params class's+ * ``model_config = ConfigDict(json_schema_extra={"groups": {...}})``.+ *+ * Each field that carries ``json_schema_extra={"group": "<key>"}`` gets+ * nested into a synthetic ``type: "collection"`` INodeProperty at+ * adapter time. ``groups[<key>]`` lets the Params class override the+ * display name and placeholder; missing keys fall back to title-cased+ * defaults.+ */+ groups?: Record<string, GroupMetadata>;+}++interface GroupMetadata {+ display_name?: string;+ placeholder?: string;}interface JsonSchemaProperty {@@ -188,9 +204,103 @@ function toInodeProperty(if (Object.keys(lifted).length > 0) {out.typeOptions = { ...out.typeOptions, ...lifted } as INodeProperties['typeOptions'];}+ // Stash the group key on the INodeProperty if set β picked up by+ // ``collectGroups`` in the grouping pass. Not consumed by the+ // renderer directly.+ const groupKey = readHint<string>('group');+ if (groupKey) (out as any).__group = groupKey;return out;}+/**+ * Convert `snake_case` / `kebab-case` / `camelCase` to Title Case.+ * Adapter defaults for group display names when the Params class didn't+ * declare explicit metadata.+ */+function titleCase(key: string): string {+ return key+ .replace(/[_-]+/g, ' ')+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .split(' ')+ .filter(Boolean)+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))+ .join(' ');+}++/**+ * Collapse properties marked with ``json_schema_extra={"group": "X"}``+ * into a synthetic ``type: "collection"`` parent. Ungrouped properties+ * keep their original positions; the collection container takes the+ * position of the **first** field with that group key so schema order+ * is preserved.+ *+ * The convention is opt-in β plugins that don't declare groups get the+ * same flat output as before. See docs-internal/plugin_system.md for the+ * convention spec.+ */+function groupProperties(+ properties: INodeProperties[],+ groupsMeta: Record<string, GroupMetadata>,+): INodeProperties[] {+ // First pass: figure out group membership + first-position index per group.+ const groupKeyOf = (p: INodeProperties): string | undefined =>+ (p as any).__group as string | undefined;+ const firstIndex = new Map<string, number>();+ for (let i = 0; i < properties.length; i++) {+ const g = groupKeyOf(properties[i]);+ if (g && !firstIndex.has(g)) firstIndex.set(g, i);+ }+ if (firstIndex.size === 0) {+ // Clean up the private marker before returning.+ return properties.map(p => {+ const { __group, ...rest } = p as any;+ return rest as INodeProperties;+ });+ }++ const collected: Record<string, INodeProperties[]> = {};+ const emitted = new Set<string>();+ const result: INodeProperties[] = [];++ for (let i = 0; i < properties.length; i++) {+ const p = properties[i];+ const g = groupKeyOf(p);+ // Strip marker before storing.+ const { __group, ...clean } = p as any;+ const childProp = clean as INodeProperties;++ if (!g) {+ result.push(childProp);+ continue;+ }+ collected[g] = collected[g] || [];+ collected[g].push(childProp);+ if (firstIndex.get(g) === i && !emitted.has(g)) {+ emitted.add(g);+ // Placeholder; filled in after all children are collected.+ result.push({ __groupPlaceholder: g } as unknown as INodeProperties);+ }+ }++ // Second pass: replace placeholders with the collection wrapper.+ return result.map(p => {+ const placeholder = (p as any).__groupPlaceholder as string | undefined;+ if (!placeholder) return p;+ const meta = groupsMeta[placeholder] || {};+ const displayName = meta.display_name || titleCase(placeholder);+ const defaultPlaceholder = `Add ${displayName.replace(/s$/, '') || displayName}`;+ const collection: INodeProperties = {+ displayName,+ name: placeholder,+ type: 'collection',+ placeholder: meta.placeholder || defaultPlaceholder,+ default: {},+ options: collected[placeholder],+ };+ return collection;+ });+}+/*** Derive the INodeTypeDescription.inputs/outputs handle shape. When the* backend NodeSpec doesn't yet carry handle configs (Phase 1/2 stub),@@ -209,9 +319,15 @@ function defaultHandles(): NodeConnectionType[] {export function nodeSpecToDescription(spec: NodeSpec): INodeTypeDescription {const propsObject = spec.inputs?.properties ?? {};const requiredSet = new Set(spec.inputs?.required ?? []);- const properties: INodeProperties[] = Object.entries(propsObject).map(+ const flatProperties: INodeProperties[] = Object.entries(propsObject).map(([name, prop]) => toInodeProperty(name, prop, requiredSet.has(name)),);+ // Lift ``json_schema_extra={"group": "X"}`` fields into synthetic+ // ``type: "collection"`` containers. Group display metadata comes from+ // ``model_config.json_schema_extra.groups`` on the Pydantic Params+ // class; unspecified groups get a title-cased default.+ const groupsMeta = spec.inputs?.groups ?? {};+ const properties = groupProperties(flatProperties, groupsMeta);return {displayName: spec.displayName,diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex b085ed98..5c96d79d 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -177,6 +177,74 @@ editor, set those via `json_schema_extra` keys the adapter lifts into`dynamicOptions`, `loadOptionsMethod`, `numberStepSize`, `widget`,`accept`.+### Field grouping (collapsible collections)++Mark a field with `json_schema_extra={"group": "<key>"}` to nest it+under a collapsible **collection** container in the parameter panel+(same UX as an n8n "Options" accordion). Group membership is opt-in β+plugins that don't declare any group render flat exactly like today.++```python+class AIAgentParams(BaseModel):+ # Top-level fields (always visible)+ provider: Literal[...] = "openai"+ model: str = Field(default="")+ prompt: str = Field(default="", json_schema_extra={"rows": 4})+ system_message: Optional[str] = Field(default="")++ # "Options" group β collapsed by default, "Add Option" reveals them+ temperature: float = Field(+ default=0.7, ge=0.0, le=2.0,+ json_schema_extra={"group": "options"},+ )+ max_tokens: Optional[int] = Field(+ default=1000, ge=1, le=200000,+ json_schema_extra={"group": "options"},+ )++ # Class-level metadata (optional β title-cased defaults otherwise)+ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )+```++**Adapter behaviour** (`client/src/adapters/nodeSpecToDescription.ts`):++- Fields with the same `group` key are collected into a single+ `type: "collection"` INodeProperty. The collection is positioned at+ the **first** child's slot in the original schema order; subsequent+ children slot into its `options` array.+- Missing class-level `groups[<key>]` metadata falls back to+ `display_name = titleCase(key)` (e.g. `"options"` β `"Options"`) and+ `placeholder = f"Add {displayName.rstrip('s')}"` (e.g. `"Add Option"`).+- Multiple groups per class are supported β just declare each key.++**When to use it:** cluster advanced / rarely-tuned knobs (temperature,+max_tokens, thinking params) behind an "Add Option" button so the+default panel stays small. Main-entry fields (provider, prompt,+required inputs) stay at the top level.++### Credentials vs. Params++`api_key` is never a declared Params field. Credentials live in the+credentials DB via `ApiKeyCredential` / `OAuthCredential` subclasses;+`services/node_executor._inject_api_keys()` resolves them at execution+time and puts them in the raw parameters dict. Plugins that need the+injected key read `ctx.raw["_raw_parameters"]["api_key"]` (stashed by+`BaseNode.execute` before Pydantic validation strips it).++If you find yourself declaring an `api_key: str = Field(...)` on a+Params class, stop: add an `ApiKeyCredential` subclass instead and wire+it via the `credentials = (...)` tuple on the node class.+### Operations (`@Operation`)A multi-op node declares multiple methods, each decorated withdiff --git a/server/nodes/README.md b/server/nodes/README.mdindex a18ec7d6..390ffe3f 100644--- a/server/nodes/README.md+++ b/server/nodes/README.md@@ -232,6 +232,18 @@ Run: `pytest server/tests/test_plugin_contract.py -q`.Pydantic models or `Union`, the LLM-schema emission will add `$defs`and fail the invariant. Keep tool-facing Params flat; move nestedtypes to `Output` instead.+- **Collapse advanced options with `group="..."`.** Tag rarely-tuned+ fields with `json_schema_extra={"group": "options"}` and they get+ lifted into a collapsible "Options" collection in the parameter+ panel (adapter-side). Declare custom display name / placeholder via+ `model_config = ConfigDict(json_schema_extra={"groups": {...}})`.+ Main-entry fields stay top-level. Full spec in+ [`docs-internal/plugin_system.md`](../../docs-internal/plugin_system.md).+- **Never declare `api_key` as a Params field.** Credentials live in+ the credentials DB via `ApiKeyCredential` / `OAuthCredential`+ subclasses and auto-inject at execution time. Plugins that need the+ injected key read `ctx.raw["_raw_parameters"]["api_key"]` β it's+ stashed before Pydantic validation strips it.---diff --git a/server/nodes/agent/_inline.py b/server/nodes/agent/_inline.pyindex 77b38fe0..7a32ac6e 100644--- a/server/nodes/agent/_inline.py+++ b/server/nodes/agent/_inline.py@@ -49,6 +49,16 @@ async def prepare_agent_call("""Run the 3-step pre-dispatch flow and return a kwargs dict readyto splat into ``AIService.execute_agent`` or ``execute_chat_agent``."""+ # api_key is NOT a declared Params field on aiAgent/chatAgent/+ # specialized agents β credentials live in the credentials DB and+ # node_executor._inject_api_keys puts the resolved key into the+ # *raw* parameters dict before Pydantic validation strips it. Recover+ # it from context so ai_service.execute_[chat_]agent receives the+ # key it reads via ``flattened.get('api_key')``.+ raw_params = context.get("_raw_parameters") or {}+ if "api_key" in raw_params and "api_key" not in parameters:+ parameters = {**parameters, "api_key": raw_params["api_key"]}+memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(node_id, context, database, log_prefix=log_prefix,)diff --git a/server/nodes/agent/_specialized.py b/server/nodes/agent/_specialized.pyindex 781a1c95..fc8fe663 100644--- a/server/nodes/agent/_specialized.py+++ b/server/nodes/agent/_specialized.py@@ -21,7 +21,12 @@ from ._handles import STD_AGENT_HINTS, std_agent_handlesclass SpecializedAgentParams(BaseModel):- """Identical to AIAgentParams β full LLM tuning surface."""+ """Identical to AIAgentParams β full LLM tuning surface.++ Mirrors AIAgentParams: no ``api_key`` field (credentials come from the+ credentials DB via runtime injection), tuning fields live in the+ "options" group so the panel renders a collapsible Options collection.+ """prompt: str = Field(default="",@@ -37,18 +42,32 @@ class SpecializedAgentParams(BaseModel):model: str = Field(default="", json_schema_extra={"placeholder": "Select a model..."},)- temperature: float = Field(default=0.7, ge=0.0, le=2.0)- max_tokens: Optional[int] = Field(default=1000, ge=1, le=200000)system_message: Optional[str] = Field(default="You are a helpful assistant",json_schema_extra={"rows": 3},)- api_key: Optional[str] = Field(- default=None,- json_schema_extra={"password": True},++ # ---- "Options" group (collapsed by default in the parameter panel) ----+ temperature: float = Field(+ default=0.7, ge=0.0, le=2.0,+ json_schema_extra={"group": "options"},+ )+ max_tokens: Optional[int] = Field(+ default=1000, ge=1, le=200000,+ json_schema_extra={"group": "options"},)- model_config = ConfigDict(extra="ignore")+ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )class SpecializedAgentOutput(BaseModel):diff --git a/server/nodes/agent/ai_agent.py b/server/nodes/agent/ai_agent.pyindex a927c721..b2ec6eaf 100644--- a/server/nodes/agent/ai_agent.py+++ b/server/nodes/agent/ai_agent.py@@ -18,6 +18,19 @@ from ._handles import STD_AGENT_HINTS, std_agent_handlesclass AIAgentParams(BaseModel):+ """AI Agent tuning surface.++ ``api_key`` is intentionally NOT a node field β credentials are stored+ via the credentials DB and auto-injected at execution time by+ ``services/node_executor._inject_api_keys`` (see AI_MODEL_TYPES in+ ``server/constants.py``).++ Tuning fields use the ``group="options"`` convention so the parameter+ panel nests them in a collapsible "Options" collection rather than+ rendering flat beside provider/model/prompt. See+ ``docs-internal/plugin_system.md`` for the convention spec.+ """+prompt: str = Field(default="",json_schema_extra={@@ -32,21 +45,32 @@ class AIAgentParams(BaseModel):model: str = Field(default="", json_schema_extra={"placeholder": "Select a model..."},)- temperature: float = Field(- default=0.7, ge=0.0, le=2.0,- json_schema_extra={"numberStepSize": 0.1},- )- max_tokens: Optional[int] = Field(default=1000, ge=1, le=200000)system_message: Optional[str] = Field(default="You are a helpful assistant",json_schema_extra={"rows": 3},)- api_key: Optional[str] = Field(- default=None,- json_schema_extra={"password": True},++ # ---- "Options" group (collapsed by default in the parameter panel) ----+ temperature: float = Field(+ default=0.7, ge=0.0, le=2.0,+ json_schema_extra={"numberStepSize": 0.1, "group": "options"},+ )+ max_tokens: Optional[int] = Field(+ default=1000, ge=1, le=200000,+ json_schema_extra={"group": "options"},)- model_config = ConfigDict(extra="ignore")+ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )class AIAgentOutput(BaseModel):diff --git a/server/nodes/agent/chat_agent.py b/server/nodes/agent/chat_agent.pyindex a02f535a..78eb817a 100644--- a/server/nodes/agent/chat_agent.py+++ b/server/nodes/agent/chat_agent.py@@ -17,6 +17,14 @@ from ._handles import STD_AGENT_HINTS, std_agent_handlesclass ChatAgentParams(BaseModel):+ """Zeenie tuning surface.++ Matches AIAgentParams: no ``api_key`` field (credentials auto-injected+ at execution time), tuning fields grouped under "options" for+ collapsible rendering. See docs-internal/plugin_system.md for the+ convention.+ """+provider: Literal["openai", "anthropic", "gemini", "openrouter","groq", "cerebras", "deepseek", "kimi", "mistral",@@ -34,14 +42,28 @@ class ChatAgentParams(BaseModel):system_message: Optional[str] = Field(default="", json_schema_extra={"rows": 3},)- temperature: float = Field(default=0.7, ge=0.0, le=2.0)- max_tokens: Optional[int] = Field(default=1000, ge=1, le=200000)- api_key: Optional[str] = Field(- default=None,- json_schema_extra={"password": True},++ # ---- "Options" group (collapsed by default in the parameter panel) ----+ temperature: float = Field(+ default=0.7, ge=0.0, le=2.0,+ json_schema_extra={"group": "options"},+ )+ max_tokens: Optional[int] = Field(+ default=1000, ge=1, le=200000,+ json_schema_extra={"group": "options"},)- model_config = ConfigDict(extra="ignore")+ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )class ChatAgentOutput(BaseModel):diff --git a/server/services/plugin/base.py b/server/services/plugin/base.pyindex 0aeeda93..274e11fe 100644--- a/server/services/plugin/base.py+++ b/server/services/plugin/base.py@@ -209,6 +209,14 @@ class BaseNode:"""start_time = time.time()+ # Stash the raw (pre-validation) parameters dict in context.raw+ # so plugins can recover values the Pydantic extra="ignore" policy+ # would drop β e.g. ``api_key`` injected by node_executor's+ # _inject_api_keys that isn't a declared Params field for AI agent+ # nodes. Plugins that need it: ``ctx.raw["_raw_parameters"]``.+ if isinstance(context.raw, dict):+ context.raw["_raw_parameters"] = parameters+try:params_obj = self._validate_params(parameters)except ValidationError as e:diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.pyindex 2c5d570f..935f0ad2 100644--- a/server/tests/test_node_spec.py+++ b/server/tests/test_node_spec.py@@ -37,11 +37,27 @@ class TestInputSchemas:props = schema["properties"]assert props["temperature"]["minimum"] == 0.0assert props["temperature"]["maximum"] == 2.0- # snake_case keys per Wave 11.E.4+ convention- assert "api_key" in props+ # snake_case keys per Wave 11.E.4+ convention.+ # NB: ``api_key`` is NOT a declared field β credentials live in+ # the credentials DB and are auto-injected at execution time.+ assert "api_key" not in propsassert "max_tokens" in propsassert "system_message" in props+ def test_ai_agent_options_group(self):+ """temperature + max_tokens carry ``group=\"options\"`` so the+ frontend adapter lifts them into a collapsible Options collection.+ Class-level ``groups`` metadata customises the display name /+ placeholder. See docs-internal/plugin_system.md for the+ convention."""+ schema = get_node_input_schema("aiAgent")+ props = schema["properties"]+ assert props["temperature"]["group"] == "options"+ assert props["max_tokens"]["group"] == "options"+ # Class-level groups metadata is emitted at the schema root.+ assert schema["groups"]["options"]["display_name"] == "Options"+ assert schema["groups"]["options"]["placeholder"] == "Add Option"+def test_specialized_agents_share_schema(self):# All 16 specialized agents go through SpecializedAgentParamsfor agent_type in ["android_agent", "coding_agent", "deep_agent"]:@@ -547,20 +563,23 @@ class TestDisplayOptionsEnrichment:assert prompt["placeholder"] == "Enter your prompt or use template variables..."assert prompt["rows"] == 4- def test_ai_agent_api_key_password_masked(self):+ def test_ai_agent_has_no_api_key_field(self):+ # Credentials live in the credentials DB and are auto-injected by+ # node_executor._inject_api_keys at execution time β they must+ # NOT surface as a user-editable node parameter.spec = get_node_spec("aiAgent")- api_key = spec["inputs"]["properties"]["api_key"]- assert api_key["password"] is True+ assert "api_key" not in spec["inputs"]["properties"]def test_specialized_agent_shares_ai_agent_tuning_surface(self):# SpecializedAgentParams mirrors AIAgentParams β same provider,- # model, temperature, max_tokens, system_message, api_key fields.- # Thinking/reasoning mode is surfaced via AIAgentOutput.thinking,- # not as a Params toggle.+ # model, temperature, max_tokens, system_message fields. No+ # api_key (injected at runtime). Thinking mode surfaces via+ # AIAgentOutput.thinking, not as a Params toggle.spec = get_node_spec("coding_agent")props = spec["inputs"]["properties"]- for field in ("provider", "model", "temperature", "max_tokens", "system_message", "api_key"):+ for field in ("provider", "model", "temperature", "max_tokens", "system_message"):assert field in props, f"coding_agent missing {field}"+ assert "api_key" not in propsdef test_chat_model_password_masked(self):spec = get_node_spec("openaiChatModel")