Skip to content

Add persisted synthetic-agent and synthetic-model configuration contracts #1990

Closed

Description

@propr-dev

Context

ProPR currently persists only direct coding-agent configurations. A synthetic agent must instead expose one or more virtual models whose members reference existing direct agent:model pairs. The virtual identity must remain stable everywhere users select a model, while the physical member is resolved only when an LLM call begins.

This issue establishes the configuration and API foundation. It intentionally does not implement runtime selection or retries; those are covered by the next issue.

Requirements

  • Introduce shared, serializable contracts for synthetic agents, synthetic models, pool members, selection strategies, priorities, and optional session/weekly usage caps.
  • Model a synthetic agent as an alias containing one or more virtual models. A member may reference only a direct agent, preventing nested pools and routing cycles.
  • Treat direct and synthetic aliases as one namespace.
  • Persist synthetic configuration separately from direct agents so AgentRegistry never attempts to create a Docker runtime for a synthetic entry.
  • Add authenticated configuration endpoints:
    • GET /api/config/synthetic-agents
    • POST /api/config/synthetic-agents
  • Validate aliases, default models, duplicate members, priorities, percentage limits, direct-agent references, and supported model references.
  • Reject deletion of a direct agent that is still referenced by a synthetic model, while allowing a referenced direct agent to be disabled. Disabled members are handled as unavailable at runtime.
  • Include enabled synthetic agents in the instance catalog so existing planner/model selectors can treat them as first-class choices.
  • Preserve backward compatibility by making new catalog discriminator fields optional to older consumers.

Configuration Semantics

  • priority is an integer from 0 through 100.
  • The selector considers only the highest priority tier that currently contains an eligible member. This makes priority 0 a natural fallback tier.
  • An omitted usage cap means that window does not restrict the member.
  • A cap of 80 means the member becomes unavailable when reported usage is greater than or equal to 80%.
  • Synthetic model IDs use the same durable identity rules as other public model IDs and therefore must be safe for routing and GitHub-label generation.
  • Pool members store direct aliases rather than direct-agent UUIDs because aliases are already ProPR's durable routing identity. The API must prevent deleting a referenced alias.

Acceptance Criteria

  • Valid synthetic configurations round-trip through the API without changing member order or defaults.
  • Invalid priorities, percentages, aliases, missing defaults, duplicate member IDs, duplicate physical pairs, and references to unknown models return HTTP 400 with an actionable message.
  • A synthetic alias that conflicts with a direct alias is rejected.
  • Deleting a referenced direct agent returns HTTP 409 and identifies the synthetic agent/model that references it.
  • Disabling a referenced direct agent remains allowed.
  • /api/instance/catalog returns enabled synthetic agents with kind: "synthetic", their virtual model IDs, and their configured default model.
  • A synthetic model with no currently enabled valid member is omitted from the operational catalog, without deleting its saved configuration.
  • Existing direct-agent configuration and catalog tests continue to pass.
  • Unit tests cover schema validation, reference validation, persistence, catalog projection, and deletion protection.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 29, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Store synthetic agents in their own system_configs document instead of extending the existing AgentConfig union. A synthetic agent has no CLI type, image, credential path, or version, so mixing it into direct agent configuration would force synthetic-only branches into image preparation, login, health-check, and Docker code. A separate document keeps those invariants intact while still exposing pools through the shared operational catalog.

    A normalized virtual identity is synthetic-agent-alias:synthetic-model-id. Pool members reference direct agentAlias:model identities. Nested synthetic references are deliberately rejected because they complicate cycle detection, quota accounting, context guarantees, and failure reporting without adding a necessary first-version capability.

    Deterministic priority tiers are used instead of probabilistic weights. Weights were considered, but strict priority plus round-robin tie-breaking directly supports main/fallback configurations and is easier to explain, test, and diagnose.

    File: packages/shared/src/syntheticAgents.ts (new file)

    Why this file: Shared contracts are required by the backend, UI, CLI, and tests. Defining the schema once prevents each layer from interpreting percentages, defaults, or member identities differently.

    import { z } from 'zod';
    
    export const SYNTHETIC_SELECTION_STRATEGIES = [
      'round_robin',
      'usage_based',
    ] as const;
    
    export type SyntheticSelectionStrategy =
      (typeof SYNTHETIC_SELECTION_STRATEGIES)[number];
    
    export const syntheticUsageLimitsSchema = z.object({
      // Omitted windows are intentionally unrestricted. Requiring explicit caps
      // would make ordinary round-robin pools depend on Agent Tank availability.
      sessionMaxPercent: z.number().finite().min(1).max(100).optional(),
      weeklyMaxPercent: z.number().finite().min(1).max(100).optional(),
    }).strict();
    
    export const syntheticModelMemberSchema = z.object({
      id: z.string().uuid(),
      directAgentAlias: z.string().min(1),
      model: z.string().min(1),
      enabled: z.boolean().default(true),
      // A bounded integer produces predictable priority tiers and avoids subtle
      // floating-point comparisons in the runtime selector.
      priority: z.number().int().min(0).max(100).default(100),
      usageLimits: syntheticUsageLimitsSchema.optional(),
    }).strict();
    
    export const syntheticModelConfigSchema = z.object({
      id: z.string().regex(
        /^[a-z0-9][a-z0-9-]{0,62}$/,
        'Synthetic model IDs must use lowercase letters, numbers, and hyphens',
      ),
      displayName: z.string().trim().min(1).max(100).optional(),
      enabled: z.boolean().default(true),
      strategy: z.enum(SYNTHETIC_SELECTION_STRATEGIES).default('round_robin'),
      members: z.array(syntheticModelMemberSchema).min(1),
    }).strict().superRefine((model, context) => {
      const memberIds = new Set<string>();
      const physicalPairs = new Set<string>();
    
      model.members.forEach((member, index) => {
        if (memberIds.has(member.id)) {
          context.addIssue({
            code: z.ZodIssueCode.custom,
            path: ['members', index, 'id'],
            message: `Duplicate synthetic member ID '${member.id}'`,
          });
        }
        memberIds.add(member.id);
    
        // A direct pair must appear at most once in a virtual model. Duplicating it
        // would give one subscription extra selection weight accidentally.
        const pair = JSON.stringify([member.directAgentAlias, member.model]);
        if (physicalPairs.has(pair)) {
          context.addIssue({
            code: z.ZodIssueCode.custom,
            path: ['members', index],
            message: `Duplicate direct member '${member.directAgentAlias}:${member.model}'`,
          });
        }
        physicalPairs.add(pair);
      });
    });
    
    export const syntheticAgentConfigSchema = z.object({
      id: z.string().uuid(),
      alias: z.string().regex(
        /^[a-z0-9][a-z0-9-]{0,62}$/,
        'Synthetic aliases must use lowercase letters, numbers, and hyphens',
      ),
      enabled: z.boolean().default(true),
      defaultModel: z.string().min(1),
      models: z.array(syntheticModelConfigSchema).min(1),
    }).strict().superRefine((agent, context) => {
      const modelIds = new Set<string>();
      agent.models.forEach((model, index) => {
        if (modelIds.has(model.id)) {
          context.addIssue({
            code: z.ZodIssueCode.custom,
            path: ['models', index, 'id'],
            message: `Duplicate synthetic model ID '${model.id}'`,
          });
        }
        modelIds.add(model.id);
      });
    
      // Validate the default here so every persisted agent is internally usable,
      // independent of whether its direct members happen to be enabled today.
      if (!agent.models.some(model => model.id === agent.defaultModel && model.enabled)) {
        context.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['defaultModel'],
          message: `Default model '${agent.defaultModel}' is missing or disabled`,
        });
      }
    });
    
    export const syntheticAgentConfigsSchema = z.array(syntheticAgentConfigSchema)
      .superRefine((agents, context) => {
        const aliases = new Set<string>();
        agents.forEach((agent, index) => {
          if (aliases.has(agent.alias)) {
            context.addIssue({
              code: z.ZodIssueCode.custom,
              path: [index, 'alias'],
              message: `Duplicate synthetic alias '${agent.alias}'`,
            });
          }
          aliases.add(agent.alias);
        });
      });
    
    export type SyntheticUsageLimits = z.infer<typeof syntheticUsageLimitsSchema>;
    export type SyntheticModelMember = z.infer<typeof syntheticModelMemberSchema>;
    export type SyntheticModelConfig = z.infer<typeof syntheticModelConfigSchema>;
    export type SyntheticAgentConfig = z.infer<typeof syntheticAgentConfigSchema>;
    
    export interface SyntheticDirectAgentReference {
      alias: string;
      enabled: boolean;
      supportedModels: string[];
    }
    
    export interface SyntheticReferenceValidationResult {
      errors: string[];
      warnings: string[];
    }
    
    export function parseSyntheticAgentConfigs(value: unknown): SyntheticAgentConfig[] {
      // Parsing at every persistence boundary prevents malformed legacy or manually
      // edited JSON from reaching runtime selection code.
      return syntheticAgentConfigsSchema.parse(value);
    }
    
    export function validateSyntheticAgentReferences(
      syntheticAgents: SyntheticAgentConfig[],
      directAgents: SyntheticDirectAgentReference[],
    ): SyntheticReferenceValidationResult {
      const errors: string[] = [];
      const warnings: string[] = [];
      const directByAlias = new Map(directAgents.map(agent => [agent.alias, agent]));
      const directAliases = new Set(directAgents.map(agent => agent.alias));
    
      for (const syntheticAgent of syntheticAgents) {
        if (directAliases.has(syntheticAgent.alias)) {
          errors.push(
            `Synthetic alias '${syntheticAgent.alias}' conflicts with a direct agent alias`,
          );
        }
    
        for (const syntheticModel of syntheticAgent.models) {
          let enabledMembers = 0;
          for (const member of syntheticModel.members) {
            const directAgent = directByAlias.get(member.directAgentAlias);
            if (!directAgent) {
              errors.push(
                `${syntheticAgent.alias}:${syntheticModel.id} references unknown direct agent '${member.directAgentAlias}'`,
              );
              continue;
            }
            if (!directAgent.supportedModels.includes(member.model)) {
              errors.push(
                `${syntheticAgent.alias}:${syntheticModel.id} references unsupported model ` +
                `'${member.directAgentAlias}:${member.model}'`,
              );
              continue;
            }
            if (member.enabled && directAgent.enabled) enabledMembers += 1;
          }
    
          // Disabling a direct agent should remain a reversible operation. Warn and
          // hide the virtual model operationally instead of corrupting saved config.
          if (syntheticModel.enabled && enabledMembers === 0) {
            warnings.push(
              `${syntheticAgent.alias}:${syntheticModel.id} has no enabled direct members`,
            );
          }
        }
      }
    
      return { errors, warnings };
    }
    
    export function findSyntheticReferencesToDirectAgent(
      syntheticAgents: SyntheticAgentConfig[],
      directAgentAlias: string,
    ): string[] {
      return syntheticAgents.flatMap(agent => agent.models.flatMap(model =>
        model.members.some(member => member.directAgentAlias === directAgentAlias)
          ? [`${agent.alias}:${model.id}`]
          : [],
      ));
    }

    File: packages/shared/src/index.ts

    Why this file: The shared package barrel is the stable import boundary used by the API, UI, and CLI. Re-exporting the contracts prevents deep imports that would become compatibility liabilities.

    --- a/packages/shared/src/index.ts
    +++ b/packages/shared/src/index.ts
    @@
     export {
       type InstanceCatalogAgent,
       type InstanceCatalogRepository,
       type InstanceCatalogResponse,
     } from './instanceCatalog.js';
    +
    +// Synthetic pools are configuration-level routing objects rather than Docker
    +// agent types, so their contracts live in a dedicated shared module.
    +export {
    +  SYNTHETIC_SELECTION_STRATEGIES,
    +  syntheticAgentConfigsSchema,
    +  parseSyntheticAgentConfigs,
    +  validateSyntheticAgentReferences,
    +  findSyntheticReferencesToDirectAgent,
    +  type SyntheticSelectionStrategy,
    +  type SyntheticUsageLimits,
    +  type SyntheticModelMember,
    +  type SyntheticModelConfig,
    +  type SyntheticAgentConfig,
    +  type SyntheticDirectAgentReference,
    +  type SyntheticReferenceValidationResult,
    +} from './syntheticAgents.js';

    File: packages/core/src/config/configManagerSyntheticAgents.ts (new file)

    Why this file: Core owns database-backed configuration. Keeping persistence here gives daemon, API, workers, and tests one normalized loading path while avoiding a schema migration for a JSON configuration document.

    import type { Knex } from 'knex';
    import {
      parseSyntheticAgentConfigs,
      type SyntheticAgentConfig,
    } from '@propr/shared';
    import { getConfig, getConfigWithClient, saveConfig } from './configStore.js';
    
    const SYNTHETIC_AGENTS_CONFIG_KEY = 'synthetic_agents';
    const DEFAULT_SYNTHETIC_AGENTS: SyntheticAgentConfig[] = [];
    
    export async function loadSyntheticAgents(
      client?: Knex | Knex.Transaction,
    ): Promise<SyntheticAgentConfig[]> {
      const value = client
        ? await getConfigWithClient<unknown>(
            SYNTHETIC_AGENTS_CONFIG_KEY,
            DEFAULT_SYNTHETIC_AGENTS,
            client,
          )
        : await getConfig<unknown>(
            SYNTHETIC_AGENTS_CONFIG_KEY,
            DEFAULT_SYNTHETIC_AGENTS,
          );
    
      // Re-parse database content because deployments can contain hand-edited or
      // pre-release values that did not pass through the current API validator.
      return parseSyntheticAgentConfigs(value);
    }
    
    export async function saveSyntheticAgents(
      value: unknown,
      client?: Knex | Knex.Transaction,
    ): Promise<SyntheticAgentConfig[]> {
      const normalized = parseSyntheticAgentConfigs(value);
      await saveConfig(SYNTHETIC_AGENTS_CONFIG_KEY, normalized, client);
      return normalized;
    }

    File: packages/core/src/config/configManager.ts

    Why this file: Existing callers import configuration functions through this barrel. Exporting the new manager here makes it available through @propr/core without exposing the underlying config-store key.

    --- a/packages/core/src/config/configManager.ts
    +++ b/packages/core/src/config/configManager.ts
    @@
    +// Keep synthetic routing configuration separate from direct agent runtime
    +// configuration so image preparation never sees a non-Docker agent.
    +export {
    +  loadSyntheticAgents,
    +  saveSyntheticAgents,
    +} from './configManagerSyntheticAgents.js';

    File: packages/api/routes/configRoutesSyntheticAgents.ts (new file)

    Why this file: A focused handler module keeps validation and referential-integrity rules out of the already large general configuration route. The existing config router should mount these handlers under its administrator-only middleware.

    import type { Request, Response } from 'express';
    import { ZodError } from 'zod';
    import {
      loadAgents,
      loadSyntheticAgents,
      saveSyntheticAgents,
    } from '@propr/core';
    import {
      parseSyntheticAgentConfigs,
      validateSyntheticAgentReferences,
    } from '@propr/shared';
    
    function validationMessage(error: unknown): string {
      if (error instanceof ZodError) {
        // Return paths with the message so the nested pool editor can associate the
        // failure with the correct model or member row.
        return error.issues
          .map(issue => `${issue.path.join('.') || 'synthetic_agents'}: ${issue.message}`)
          .join('; ');
      }
      return error instanceof Error ? error.message : 'Invalid synthetic agent configuration';
    }
    
    export function createSyntheticAgentConfigHandlers() {
      async function getSyntheticAgents(_req: Request, res: Response): Promise<void> {
        try {
          res.json({ synthetic_agents: await loadSyntheticAgents() });
        } catch (error) {
          console.error('Failed to load synthetic agents:', error);
          res.status(500).json({ error: 'Failed to load synthetic agents' });
        }
      }
    
      async function updateSyntheticAgents(req: Request, res: Response): Promise<void> {
        try {
          const syntheticAgents = parseSyntheticAgentConfigs(req.body?.synthetic_agents);
          const directAgents = await loadAgents();
          const validation = validateSyntheticAgentReferences(syntheticAgents, directAgents);
          if (validation.errors.length > 0) {
            res.status(400).json({ error: validation.errors.join('; ') });
            return;
          }
    
          const saved = await saveSyntheticAgents(syntheticAgents);
          res.json({
            success: true,
            synthetic_agents: saved,
            // Warnings communicate reversible availability problems without making
            // it impossible to prepare a pool before every account is enabled.
            warnings: validation.warnings,
          });
        } catch (error) {
          res.status(400).json({ error: validationMessage(error) });
        }
      }
    
      return { getSyntheticAgents, updateSyntheticAgents };
    }

    File: packages/api/routes/configRoutes.ts

    Why this file: This is where the existing administrator-only configuration endpoints are assembled. Mounting the handlers here ensures synthetic credentials and routing rules inherit the same authorization and demo-mode protections as direct agents.

    --- a/packages/api/routes/configRoutes.ts
    +++ b/packages/api/routes/configRoutes.ts
    @@
    +import { createSyntheticAgentConfigHandlers } from './configRoutesSyntheticAgents.js';
    @@
     export function createConfigRoutes(/* existing dependencies */) {
    +  const syntheticHandlers = createSyntheticAgentConfigHandlers();
    @@
    +  // Use the existing administrator configuration middleware here; pool changes
    +  // can redirect paid LLM work and therefore must not be member-writable.
    +  router.get('/synthetic-agents', syntheticHandlers.getSyntheticAgents);
    +  router.post('/synthetic-agents', syntheticHandlers.updateSyntheticAgents);

    In the direct-agent save handler, load the current synthetic configuration before committing removals. Compare the previous and proposed direct alias sets. For every removed alias, call findSyntheticReferencesToDirectAgent; return HTTP 409 with the referencing virtual identities when the list is non-empty. Do not apply this block when only enabled changes.

    File: packages/shared/src/instanceCatalog.ts

    Why this file: Planner and member-facing model selectors consume this sanitized catalog. The discriminator lets newer UIs render a pool icon while optional fields preserve compatibility with older clients.

    --- a/packages/shared/src/instanceCatalog.ts
    +++ b/packages/shared/src/instanceCatalog.ts
    @@
     export interface InstanceCatalogAgent {
    +  /** Stable configuration ID used by playground requests. */
    +  id?: string;
    +  /** Omitted by older servers; consumers should treat omission as direct. */
    +  kind?: 'direct' | 'synthetic';
       alias: string;
    @@
     }

    File: packages/api/routes/instanceCatalogRoutes.ts

    Why this file: This route is the operational projection used by ordinary workflows. It must expose only virtual models that have at least one currently enabled and valid direct member.

    --- a/packages/api/routes/instanceCatalogRoutes.ts
    +++ b/packages/api/routes/instanceCatalogRoutes.ts
    @@
       loadAgents,
    +  loadSyntheticAgents,
    @@
     function catalogAgent(agent: AgentConfig): InstanceCatalogAgent {
       return {
    +    id: agent.id,
    +    kind: 'direct',
         alias: agent.alias,
    @@
     }
    +
    +function catalogSyntheticAgents(
    +  syntheticAgents: Awaited<ReturnType<typeof loadSyntheticAgents>>,
    +  directAgents: AgentConfig[],
    +): InstanceCatalogAgent[] {
    +  const directByAlias = new Map(directAgents.map(agent => [agent.alias, agent]));
    +  return syntheticAgents.flatMap(syntheticAgent => {
    +    if (!syntheticAgent.enabled) return [];
    +    const supportedModels = syntheticAgent.models.flatMap(model => {
    +      if (!model.enabled) return [];
    +      const usable = model.members.some(member => {
    +        const direct = directByAlias.get(member.directAgentAlias);
    +        return member.enabled
    +          && direct?.enabled === true
    +          && direct.supportedModels.includes(member.model);
    +      });
    +      // Hide temporarily unusable models instead of advertising selections that
    +      // are guaranteed to fail before an LLM call starts.
    +      return usable ? [model.id] : [];
    +    });
    +    if (supportedModels.length === 0) return [];
    +    return [{
    +      id: syntheticAgent.id,
    +      kind: 'synthetic' as const,
    +      alias: syntheticAgent.alias,
    +      enabled: true,
    +      supportedModels,
    +      ...(supportedModels.includes(syntheticAgent.defaultModel)
    +        ? { defaultModel: syntheticAgent.defaultModel }
    +        : {}),
    +    }];
    +  });
    +}
    @@
    -      const [agents, repositories, settings] = await Promise.all([
    +      const [agents, syntheticAgents, repositories, settings] = await Promise.all([
             services.loadAgents(),
    +        loadSyntheticAgents(),
    @@
    -      const catalogAgents = agents.filter(agent => agent.enabled).map(catalogAgent);
    +      const catalogAgents = [
    +        ...agents.filter(agent => agent.enabled).map(catalogAgent),
    +        ...catalogSyntheticAgents(syntheticAgents, agents),
    +      ];

    Files: test/syntheticAgentConfig.test.ts and test/instanceCatalogSynthetic.test.ts (new files)

    Why these files: Configuration is a public routing contract. Tests must pin both persisted validation and the sanitized operational projection before runtime selection is introduced.

    Add table-driven tests for every acceptance criterion, including a direct-agent deletion conflict, a disabled member warning, alias collisions, malformed percentages, duplicate physical pairs, and catalog omission when all members are disabled.

  2. propr-dev commented on Aug 29, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1990/gpt-5.6-sol-add-persisted-synthetic-a-20260829-2324-okp
    • Base Branch: 1990-epic-synthetic-pool-eus
    • Worktree: issue-1990-20260829-2324-gpt-5.6-sol-okp

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 29, 2026
  4. added a commit that references this issue on Aug 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions