You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implement user-configurable "self-contained agents" - bundled configurations of model + knowledge + system prompt + tools that can be created, shared, and used by teams within an organization.
Similar to: ChatGPT Custom GPTs, OpenWebUI Workspaces, GitHub Copilot Custom Agents
Design Decisions
Decision
Choice
Integration
Users can select any agent directly in chat UI (routing agent OR specific agents)
Sharing
Organization-internal only (no marketplace)
Versioning
Required for MVP - full version history with rollback
Implement user-configurable "self-contained agents" — bundled configurations of model + knowledge + system prompt + tools that can be created, shared, and used by teams within an organization.
Similar to: ChatGPT Custom GPTs, OpenWebUI Workspaces, GitHub Copilot Custom Agents
Design Decisions
Decision
Choice
Integration
Users can select any agent directly in chat UI (routing agent OR specific agents)
Sharing
Organization-internal only (no marketplace)
Versioning
Required for MVP — full version history with rollback
Plan B: Team as Context — single teamId ownership, global team filter in UI, knowledge auto-scoped to team
Team Architecture
Decision: Team as Context (Plan B)
New modules (custom agents, and future team-scoped resources) use a single teamId field for team ownership. A global team filter in the UI controls which resources the user sees.
teamId: null → org-wide (visible to all members)
teamId: 'team-sales' → belongs to Sales team (visible when user is in Sales or "All Teams")
How the global team filter works:
User selects "All Teams" → sees org-wide resources + resources from all their teams
User selects "Sales" → sees org-wide resources + Sales resources only
Visibility is automatic — no per-resource visibility field needed
Knowledge scope is automatic: When an agent belongs to a team, its RAG search is automatically narrowed to that team's knowledge. No separate knowledgeScopeMode field needed.
Unified Team Fields
All team-scoped tables (including documents after migration) use the same two fields:
// Standard team fields for all team-scoped tables
teamId: v.optional(v.string()),// Primary team (null = org-wide)sharedWithTeamIds: v.optional(v.array(v.string()))// Additional teams with access
Before running migration: Query data distribution to validate assumptions:
// How many documents have 2+ team tags?constmulti=docs.filter(d=>(d.teamTags?.length??0)>1);
Architecture: Reuse Strategy
The existing codebase already provides the full execution pipeline used by all 6 built-in agents. Custom agents plug into it via a thin conversion layer — no new execution engine needed.
DB record → SerializableAgentConfig conversion (thin mapping)
chatWithCustomAgent mutation
Entry point: load from DB → call startAgentChat()
hasTeamAccess()
Shared team access helper (teamId + sharedWithTeamIds)
Documents teamTags migration
Migrate existing documents to unified team fields
AgentType extension
Add 'custom' to the type union + context config
CRUD mutations/queries
Create, update, delete, duplicate, list, version management
Frontend management UI
Agent editor, tool picker, chat selector, global team filter
Current State
Tale already has:
6 hardcoded agents (chat/routing, CRM, document, web, workflow, integration), all following the same SerializableAgentConfig → startAgentChat() → generateAgentResponse() pattern
27 tools in a centralized registry (convex/agent_tools/tool_registry.ts)
Hook system for context injection (beforeContext, beforeGenerate, onError)
Knowledge base with RAG/vector search (documents, websites, products, customers)
Tone of Voice per organization
Team-based data isolation for knowledge access (userTeamIds in RAG)
Environment-based model selection with preset support
What's missing:
Database-stored agent configurations
Per-agent model selection (via presets)
Global team context in UI (teams exist but have no active selection)
createCustomAgent — Create new agent config + initial version snapshot
updateCustomAgent — Edit config + auto-create new version
deleteCustomAgent — Soft delete (isActive: false)
duplicateCustomAgent — Clone an agent
rollbackCustomAgentVersion — Create new version from historical snapshot
convex/custom_agents/queries.ts:
listCustomAgents — List active agents for org, filtered by hasTeamAccess()
getCustomAgent — Get single agent by ID
getCustomAgentVersions — Version history for an agent
getAvailableTools — List tools with descriptions from TOOL_REGISTRY for picker UI
5. Required Change to startAgentChat
Add an optional userTeamIds parameter to StartAgentChatArgs:
// convex/lib/agent_chat/start_agent_chat.ts — small additionexportinterfaceStartAgentChatArgs{// ... existing fields .../** Override user team IDs (for custom agent team-scoped knowledge) */userTeamIds?: string[];}// In the function body, prefer the override when provided:constteamIds=args.userTeamIds??(thread?.userId ? awaitgetUserTeamIds(ctx,thread.userId) : []);constuserTeamIds=args.userTeamIds
? args.userTeamIds// Already includes org prefix
: [`org_${organizationId}`, ...teamIds];
This is backward-compatible — all existing agents omit the parameter and get the current behavior.
6. Router Integration (Optional Enhancement)
To let the routing agent automatically dispatch to custom agents:
Dynamically inject custom agent descriptions into routing instructions
Register custom agents as sub-agent tools (following the existing crm_assistant, web_assistant pattern)
Frontend Implementation
1. Global Team Filter
Add a team selector to the dashboard header (similar to the existing org context from URL):
"All Teams" (default) → shows org-wide resources + resources from all user's teams
Specific team → shows org-wide resources + that team's resources only
Persisted in URL or local state (e.g., query param ?team=team-sales)
Affects all team-scoped modules: custom agents, and future team-scoped resources
Documents use the same hasTeamAccess() helper after migration
2. Agent Management Pages
List View (/settings/agents):
Table of custom agents with name, team, status, tools count, last modified
Tool picker (checkboxes grouped by category, data from TOOL_REGISTRY)
Model preset selector
Knowledge settings
Version history sidebar with rollback
Phase 3: Chat Integration & Team Filter
Add global team filter to dashboard header
Add agent selector dropdown in chat interface
Show built-in agents + custom agents (filtered by team)
Wire selector to call chatWithCustomAgent mutation
Persist selected agent per conversation
Phase 4: Polish & Enhancements
Test/preview mode in agent editor
Duplicate agent functionality
Pre-built starter templates
Router integration — auto-dispatch to custom agents via routing agent
Workflow LLM node integration — allow LLM steps to reference a customAgentId to load agent config instead of manual prompt/tools configuration
Model Presets
Predefined presets mapped to existing environment variables and SerializableAgentConfig fields:
Preset
Env Variable
Use Case
SerializableAgentConfig Mapping
fast
OPENAI_FAST_MODEL
Quick responses, simple tasks
useFastModel: true
standard
OPENAI_MODEL
Balanced quality and speed
Default (no override)
advanced
OPENAI_CODING_MODEL
Complex reasoning, code generation
model: process.env.OPENAI_CODING_MODEL
vision
OPENAI_VISION_MODEL
Image analysis tasks
model: process.env.OPENAI_VISION_MODEL
UI: Radio buttons or dropdown with descriptions of each preset's strengths.
Security Considerations
Tool Access: Validate that selected tools exist in TOOL_REGISTRY
Prompt Injection: Sanitize user instructions (or accept risk with warning)
Model Access: Only allow presets the org has access to
Data Isolation: Team membership check before agent access; knowledge auto-scoped to agent's team — users can never access data from teams they don't belong to
Rate Limiting: Apply same rate limits as built-in agents (existing middleware)
Workflow Integration (Phase 4 Enhancement)
Custom agents can also be referenced within workflows by extending the LLM node:
Add optional customAgentId field to LLMNodeConfig
When set, load agent's systemInstructions + toolNames + modelPreset from DB
Override the LLM step's manual configuration with the agent's saved config
This lets workflow users select a pre-configured agent instead of manually writing prompts and picking tools per step
This reuses the custom agent definitions without modifying the workflow execution engine.
Verification Plan
Unit Tests: Test hasTeamAccess() with teamId only, teamId + sharedWithTeamIds, and org-wide resources
Unit Tests: Test toSerializableConfig() with various presets and configurations
Migration Tests: Verify documents migration preserves all access patterns:
Activity
larryro commentedon Jan 31, 2026
Self-Contained Agents Feature Plan
Overview
Implement user-configurable "self-contained agents" — bundled configurations of model + knowledge + system prompt + tools that can be created, shared, and used by teams within an organization.
Similar to: ChatGPT Custom GPTs, OpenWebUI Workspaces, GitHub Copilot Custom Agents
Design Decisions
startAgentChat→generateAgentResponse)teamIdownership, global team filter in UI, knowledge auto-scoped to teamTeam Architecture
Decision: Team as Context (Plan B)
New modules (custom agents, and future team-scoped resources) use a single
teamIdfield for team ownership. A global team filter in the UI controls which resources the user sees.How the global team filter works:
visibilityfield neededKnowledge scope is automatic: When an agent belongs to a team, its RAG search is automatically narrowed to that team's knowledge. No separate
knowledgeScopeModefield needed.Unified Team Fields
All team-scoped tables (including documents after migration) use the same two fields:
Shared access helper used by all modules:
Documents Migration (
teamTags→teamId+sharedWithTeamIds)Documents currently use
teamTags: string[]. We migrate to the unified model:teamTagsteamIdsharedWithTeamIdsundefined/[]nullundefined['sales']'sales'undefined['sales', 'marketing']'sales'['marketing']Migration steps (additive, with transition period):
teamId+sharedWithTeamIdsfields to documents schema (alongside existingteamTags)teamTagsget_documents_cursor.tsandrls_rules.tsto use new fieldsteamTagsfieldBefore running migration: Query data distribution to validate assumptions:
Architecture: Reuse Strategy
The existing codebase already provides the full execution pipeline used by all 6 built-in agents. Custom agents plug into it via a thin conversion layer — no new execution engine needed.
Existing components reused directly
SerializableAgentConfigconvex/lib/agent_chat/types.tscreateAgentConfig()convex/lib/create_agent_config.tsstartAgentChat()convex/lib/agent_chat/start_agent_chat.tsgenerateAgentResponse()convex/lib/agent_response/generate_response.tsconvex/agent_tools/tool_registry.tsAGENT_CONTEXT_CONFIGSconvex/lib/context_management/constants.tsgetDefaultAgentRuntimeConfig()convex/lib/agent_runtime_config.tsAgentHooksConfig)convex/lib/agent_chat/types.tsgetUserTeamIds()convex/lib/get_user_teams.tsNew code required
customAgents+customAgentVersionstablestoSerializableConfig()SerializableAgentConfigconversion (thin mapping)chatWithCustomAgentmutationstartAgentChat()hasTeamAccess()teamId+sharedWithTeamIds)teamTagsmigrationAgentTypeextension'custom'to the type union + context configCurrent State
Tale already has:
SerializableAgentConfig→startAgentChat()→generateAgentResponse()patternconvex/agent_tools/tool_registry.ts)userTeamIdsin RAG)What's missing:
Data Model
New Table:
customAgentsNew Table:
customAgentVersionsVersion behavior:
customAgents.currentVersionpoints to active versionBackend Implementation
1. DB Config → SerializableAgentConfig Conversion
Create
convex/custom_agents/config.ts— a thin mapping layer:2. New Mutation:
chatWithCustomAgentCreate
convex/custom_agents/mutations.ts— follows the exact same pattern as all built-in agents:3. Extend AgentType
Modify
convex/lib/context_management/constants.ts:4. CRUD Operations
convex/custom_agents/mutations.ts(additional):createCustomAgent— Create new agent config + initial version snapshotupdateCustomAgent— Edit config + auto-create new versiondeleteCustomAgent— Soft delete (isActive: false)duplicateCustomAgent— Clone an agentrollbackCustomAgentVersion— Create new version from historical snapshotconvex/custom_agents/queries.ts:listCustomAgents— List active agents for org, filtered byhasTeamAccess()getCustomAgent— Get single agent by IDgetCustomAgentVersions— Version history for an agentgetAvailableTools— List tools with descriptions fromTOOL_REGISTRYfor picker UI5. Required Change to
startAgentChatAdd an optional
userTeamIdsparameter toStartAgentChatArgs:This is backward-compatible — all existing agents omit the parameter and get the current behavior.
6. Router Integration (Optional Enhancement)
To let the routing agent automatically dispatch to custom agents:
crm_assistant,web_assistantpattern)Frontend Implementation
1. Global Team Filter
Add a team selector to the dashboard header (similar to the existing org context from URL):
?team=team-sales)hasTeamAccess()helper after migration2. Agent Management Pages
List View (
/settings/agents):Detail/Edit View (
/settings/agents/[id]):TOOL_REGISTRY)3. Agent Selector in Chat
4. Tool Picker Component
Reusable component showing:
TOOL_REGISTRY)Key Files to Modify
convex/schema.tscustomAgents,customAgentVersionstablesconvex/lib/context_management/constants.tscustomtoAGENT_CONTEXT_CONFIGSconvex/agent_tools/tool_registry.tsconvex/lib/agent_chat/start_agent_chat.tsuserTeamIdsoverride parameterconvex/agents/chat/agent.tsconvex/documents/schema.tsteamId+sharedWithTeamIds, later removeteamTagsconvex/documents/get_documents_cursor.tsteamTagstohasTeamAccess()convex/lib/rls/helpers/rls_rules.tsconvex/lib/team_access.tshasTeamAccess()helper (teamId+sharedWithTeamIds)convex/custom_agents/config.tstoSerializableConfig()conversionconvex/custom_agents/mutations.tschatWithCustomAgentconvex/custom_agents/queries.tsapp/routes/settings/agents/*components/agents/*components/team-filter/*Not modified:
generateAgentResponse(),createAgentConfig(),runAgentGeneration— these are reused as-is.Phased Implementation
Phase 0: Team Fields Unification (prerequisite)
hasTeamAccess()helper inconvex/lib/team_access.tsteamId+sharedWithTeamIdsfields to documents schema (alongsideteamTags)teamTagsget_documents_cursor.tsandrls_rules.tsto usehasTeamAccess()teamTagsfield from documents schemaPhase 1: Data Model & Backend Core
customAgentsandcustomAgentVersionstables to schema (using unifiedteamId+sharedWithTeamIds)'custom'toAGENT_CONTEXT_CONFIGStoSerializableConfig()— DB record toSerializableAgentConfiguserTeamIdsoverride toStartAgentChatArgs(backward-compatible)chatWithCustomAgentmutation (reusesstartAgentChat())Phase 2: Agent Management UI
/settings/agents)TOOL_REGISTRY)Phase 3: Chat Integration & Team Filter
chatWithCustomAgentmutationPhase 4: Polish & Enhancements
customAgentIdto load agent config instead of manual prompt/tools configurationModel Presets
Predefined presets mapped to existing environment variables and
SerializableAgentConfigfields:fastOPENAI_FAST_MODELuseFastModel: truestandardOPENAI_MODELadvancedOPENAI_CODING_MODELmodel: process.env.OPENAI_CODING_MODELvisionOPENAI_VISION_MODELmodel: process.env.OPENAI_VISION_MODELUI: Radio buttons or dropdown with descriptions of each preset's strengths.
Security Considerations
TOOL_REGISTRYWorkflow Integration (Phase 4 Enhancement)
Custom agents can also be referenced within workflows by extending the LLM node:
customAgentIdfield toLLMNodeConfigsystemInstructions+toolNames+modelPresetfrom DBThis reuses the custom agent definitions without modifying the workflow execution engine.
Verification Plan
hasTeamAccess()withteamIdonly,teamId+sharedWithTeamIds, and org-wide resourcestoSerializableConfig()with various presets and configurationsteamTags: []→teamId: null(org-wide access unchanged)teamTags: ['sales']→teamId: 'sales'(single-team access unchanged)teamTags: ['sales', 'marketing']→teamId: 'sales', sharedWithTeamIds: ['marketing'](multi-team access unchanged)teamId: null) visible to all membersteamId: 'sales') visible only to Sales team membersteamId: 'sales', sharedWithTeamIds: ['marketing']) visible to both teamsfeat: unify team fields on documents with teamId + sharedWithTeamIds (#…
feat: custom agents backend - schema, CRUD, chat, versioning (#316)
feat: custom agents frontend - settings UI, chat agent selector, team…
feat: add built-in agent registry and direct agent selection (#316)
feat: unify team fields on documents with teamId + sharedWithTeamIds (#…
feat: custom agents backend - schema, CRUD, chat, versioning (#316)
feat: custom agents frontend - settings UI, chat agent selector, team…
feat: add built-in agent registry and direct agent selection (#316)
feat: custom agents detail pages with auto-save, knowledge, and versi…
feat: unify team fields on documents with teamId + sharedWithTeamIds (#…
feat: custom agents backend - schema, CRUD, chat, versioning (#316)
feat: custom agents frontend - settings UI, chat agent selector, team…
feat: add built-in agent registry and direct agent selection (#316)
feat: custom agents detail pages with auto-save, knowledge, and versi…
feat: add webhook support for custom agents (#316)
refactor: extract tool names into leaf module to break circular depen…
feat: unify team fields on documents with teamId + sharedWithTeamIds (#…
feat: custom agents backend - schema, CRUD, chat, versioning (#316)
feat: custom agents frontend - settings UI, chat agent selector, team…
feat: add built-in agent registry and direct agent selection (#316)
feat: custom agents detail pages with auto-save, knowledge, and versi…
feat: add webhook support for custom agents (#316)
refactor: extract tool names into leaf module to break circular depen…
feat: custom agents - backend, frontend, settings, webhooks, and vers…
feat: custom agents - backend, frontend, settings, webhooks, and vers…
feat: custom agents - backend, frontend, settings, webhooks, and vers…