Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

21.5 KB
Raw Blame
import assert from 'node:assert/strict';
import { describe, it } from 'vitest';

import {
  createHarnessBuilderServer,
  modelProviderLogosByName,
  toModelSelection,
} from '@/plugins/trueforge-agent-server-adapter/builderServer.js';

function isAgentsCollectionUrl(url: string): boolean {
  return new URL(url).pathname.endsWith('/api/v1/agents');
}

describe('harnessBuilderServer', () => {
  it('modelProviderLogosByName maps well-known catalog logos by type', () => {
    const logos = modelProviderLogosByName([
      {
        type: 'openai',
        logo: 'https://assets.example/openai.svg',
        models: [{ modelId: 'gpt', name: 'gpt', properties: {} }],
      },
      {
        type: 'anthropic',
        models: [{ modelId: 'claude', name: 'claude', properties: {} }],
      },
      { type: 'custom', supportedReasoningEfforts: ['low'] },
    ]);
    assert.equal(logos.get('openai'), 'https://assets.example/openai.svg');
    assert.equal(logos.has('anthropic'), false);
    assert.equal(logos.has('custom'), false);
  });

  it('toModelSelection maps nested provider + properties and optional logo', () => {
    assert.deepEqual(
      toModelSelection({
        model: {
          modelId: 'o3',
          name: 'openai/o3',
          provider: { name: 'openai' },
          properties: {
            contextLength: 200_000,
            maxOutputTokens: 100_000,
            reasoningEfforts: ['low', 'medium', 'high'],
          },
        },
        logo: 'https://assets.example/openai.svg',
      }),
      {
        id: 'o3',
        name: 'openai/o3',
        provider: { name: 'openai', logo: 'https://assets.example/openai.svg' },
        properties: {
          contextLength: 200_000,
          maxOutputTokens: 100_000,
          reasoningEfforts: ['low', 'medium', 'high'],
        },
      },
    );
    assert.deepEqual(
      toModelSelection({
        model: {
          modelId: 'gpt-4o',
          name: 'openai/gpt-4o',
          provider: { name: 'openai' },
          properties: {},
        },
      }),
      {
        id: 'gpt-4o',
        name: 'openai/gpt-4o',
        provider: { name: 'openai' },
        properties: {},
      },
    );
  });

  it('getModels joins catalog logos onto provider', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (url.endsWith('/api/v1/models')) {
        return Response.json({
          data: [
            {
              model_id: 'gpt-5-6-sol',
              name: 'openai/gpt-5-6-sol',
              provider: { name: 'openai' },
              properties: {},
            },
            {
              model_id: 'local-llama',
              name: 'internal/local-llama',
              provider: { name: 'internal' },
              properties: {},
            },
          ],
        });
      }
      if (url.endsWith('/api/v1/catalogs/model-providers')) {
        return Response.json({
          data: [
            {
              type: 'openai',
              logo: 'https://assets.example/openai.svg',
              models: [{ model_id: 'gpt-5.6-sol', name: 'gpt-5-6-sol', properties: {} }],
            },
            { type: 'custom', supported_reasoning_efforts: ['low'] },
          ],
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    assert.deepEqual(await builder.getModels(), [
      {
        id: 'gpt-5-6-sol',
        name: 'openai/gpt-5-6-sol',
        provider: { name: 'openai', logo: 'https://assets.example/openai.svg' },
        properties: {},
      },
      {
        id: 'local-llama',
        name: 'internal/local-llama',
        provider: { name: 'internal' },
        properties: {},
      },
    ]);
  });

  it('getModels still returns models when the catalog request fails', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (url.endsWith('/api/v1/models')) {
        return Response.json({
          data: [
            {
              model_id: 'gpt-5-6-sol',
              name: 'openai/gpt-5-6-sol',
              provider: { name: 'openai' },
              properties: {},
            },
          ],
        });
      }
      if (url.endsWith('/api/v1/catalogs/model-providers')) {
        return new Response('catalog unavailable', { status: 500 });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    assert.deepEqual(await builder.getModels(), [
      {
        id: 'gpt-5-6-sol',
        name: 'openai/gpt-5-6-sol',
        provider: { name: 'openai' },
        properties: {},
      },
    ]);
  });

  it('getMcpConnector loads the live per-user auth status', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (url.endsWith('/api/v1/mcp-servers/github%20enterprise')) {
        return Response.json({
          data: {
            name: 'github enterprise',
            url: 'https://github.example/mcp',
            auth: { type: 'dcr' },
            auth_status: { status: 'auth_required' },
          },
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    if (builder.getMcpConnector === undefined) throw new Error('expected getMcpConnector');

    assert.deepEqual(await builder.getMcpConnector({ connectorId: 'github enterprise' }), {
      id: 'github enterprise',
      name: 'github enterprise',
      description: 'https://github.example/mcp',
      url: 'https://github.example/mcp',
      auth: { type: 'dcr' },
      requiresAuth: true,
      authenticated: false,
    });
  });

  it('getMcpTools loads connector tools and normalizes untrusted rows', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (url.endsWith('/api/v1/mcp-servers/github/tools')) {
        return Response.json({
          data: [
            { id: 'ignored', name: 'search', description: 'Search repositories' },
            { name: 'read_file', description: 42 },
            { id: 'missing-name', description: null },
          ],
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    if (builder.getMcpTools === undefined) throw new Error('expected getMcpTools');

    assert.deepEqual(await builder.getMcpTools({ connectorId: 'github' }), [
      { id: 'search', name: 'search', description: 'Search repositories' },
      { id: 'read_file', name: 'read_file', description: '' },
    ]);
  });

  it('gets capabilities through the configured harness client', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (url.endsWith('/api/v1/capabilities')) {
        return Response.json({
          data: {
            sandbox: { enabled: false },
            skill: { enabled: false, reason: 'Configure a sandbox provider' },
            settings: { enabled: true },
          },
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });

    assert.deepEqual(await builder.getCapabilities(), {
      data: {
        sandbox: { enabled: false },
        skill: { enabled: false, reason: 'Configure a sandbox provider' },
        settings: { enabled: true },
      },
    });
  });

  it('maps registry skill metadata and loads versions on demand', async () => {
    const urls: string[] = [];
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      urls.push(url);
      if (url.endsWith('/api/v1/skills')) {
        return Response.json({
          data: [
            {
              name: 'agent-skill:acme/team-a/echo:3',
              description: 'Echo skill',
              metadata: {
                display_name: 'echo',
                repository_name: 'team-a',
                version: '3',
              },
            },
          ],
        });
      }
      if (url.includes('/api/v1/skills/versions?')) {
        return Response.json({
          data: [
            {
              name: 'agent-skill:acme/team-a/echo:1',
              display_name: 'echo',
              description: 'v1',
              version: 1,
            },
          ],
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const [skill] = await createHarnessBuilderServer({ fetch: fetchMock }).getSkills();
    if (skill === undefined) throw new Error('expected skill');
    assert.equal(skill.id, 'agent-skill:acme/team-a/echo:3');
    assert.equal(skill.name, 'echo');
    assert.equal(Reflect.get(skill, 'skillRepoName'), 'team-a');
    assert.equal(Reflect.get(skill, 'version'), 3);
    assert.equal(urls.length, 1);

    const loadVersions = Reflect.get(skill, 'loadVersions');
    if (typeof loadVersions !== 'function') throw new Error('expected version loader');
    assert.deepEqual(await Reflect.apply(loadVersions, skill, []), [
      {
        name: 'agent-skill:acme/team-a/echo:1',
        displayName: 'echo',
        description: 'v1',
        version: 1,
      },
    ]);
    assert.equal(urls.length, 2);
  });

  it('searchAgents maps registry rows to library entries with agentId + agentSpec', async () => {
    const requestedAgentNames: Array<string | null> = [];
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (isAgentsCollectionUrl(url)) {
        const agentName = new URL(url).searchParams.get('agent_name');
        requestedAgentNames.push(agentName);
        return Response.json({
          data:
            agentName === 'write'
              ? [
                  {
                    id: 'agt_2',
                    name: 'writer',
                    description: 'Writes docs.',
                    manifest: { model: { name: 'test/model' } },
                  },
                ]
              : [
                  {
                    id: 'agt_1',
                    name: 'reviewer',
                    description: 'Reviews pull requests.',
                    created_by_subject: {
                      subject_id: 'user-1',
                      subject_type: 'user',
                      subject_display_name: 'Alice',
                    },
                    manifest: {
                      model: { name: 'test/model' },
                      instructions: 'Review carefully.',
                      skills: [{ name: 'review' }],
                      mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],
                    },
                  },
                  {
                    id: 'agt_2',
                    name: 'writer',
                    description: 'Writes docs.',
                    manifest: { model: { name: 'test/model' } },
                  },
                ],
          pagination: { limit: 25 },
        });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    const all = await builder.searchAgents();
    assert.equal(all.data.length, 2);
    assert.deepEqual(all.data[0], {
      name: 'reviewer',
      agentId: 'agt_1',
      createdBySubject: {
        subjectId: 'user-1',
        subjectType: 'user',
        subjectDisplayName: 'Alice',
      },
      description: 'Reviews pull requests.',
      agentSpec: {
        model: { name: 'test/model' },
        instructions: 'Review carefully.',
        skills: [{ name: 'review', preload: false }],
        mcpServers: [{ name: 'github', enableTools: ['@all'] }],
      },
    });

    const filtered = await builder.searchAgents({ query: ' write ' });
    assert.deepEqual(
      filtered.data.map(row => row.name),
      ['writer'],
    );
    assert.deepEqual(requestedAgentNames, [null, 'write']);
  });

  it('searchAgents advances via pageToken on a later API page', async () => {
    const fetchMock: typeof fetch = async input => {
      const url = String(input instanceof Request ? input.url : input);
      const parsed = new URL(url);
      if (!parsed.pathname.endsWith('/api/v1/agents')) {
        return new Response(`Unexpected request: ${url}`, { status: 500 });
      }
      const agentName = parsed.searchParams.get('agent_name');
      if (agentName !== 'a') {
        return new Response(`Unexpected agent_name: ${String(agentName)}`, { status: 500 });
      }
      const pageToken = parsed.searchParams.get('page_token');
      if (pageToken == null || pageToken === '') {
        return Response.json({
          data: [{ id: 'agt_1', name: 'alpha', manifest: { model: { name: 'test/model' } } }],
          pagination: { limit: 1, next_page_token: 'tok_2' },
        });
      }
      if (pageToken === 'tok_2') {
        return Response.json({
          data: [{ id: 'agt_2', name: 'beta', manifest: { model: { name: 'test/model' } } }],
          pagination: { limit: 1, previous_page_token: 'tok_1' },
        });
      }
      return new Response(`Unexpected page_token: ${pageToken}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    const page = await builder.searchAgents({ query: 'a', limit: 1, pageToken: 'tok_2' });
    assert.deepEqual(
      page.data.map(row => row.name),
      ['beta'],
    );
    assert.equal(page.previousPageToken, 'tok_1');
    assert.equal(page.nextPageToken, undefined);
  });

  it('searchAgents caps limit at 100', async () => {
    const urls: string[] = [];
    const fetchMock: typeof fetch = async input => {
      const url = String(input instanceof Request ? input.url : input);
      urls.push(url);
      if (isAgentsCollectionUrl(url)) {
        return Response.json({ data: [], pagination: { limit: 100 } });
      }
      return new Response(`Unexpected request: ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    await builder.searchAgents({ limit: 200 });
    const parsed = new URL(urls[0] ?? '');
    assert.equal(parsed.searchParams.get('limit'), '100');
  });

  it('saveAgent creates when the name is new', async () => {
    const requests: { method: string; url: string; body?: unknown }[] = [];
    const fetchMock: typeof fetch = async (input, init) => {
      const url = input instanceof Request ? input.url : String(input);
      const method = init?.method ?? 'GET';
      if (url.endsWith('/api/v1/agents') && method === 'POST' && typeof init?.body === 'string') {
        requests.push({ method, url, body: JSON.parse(init.body) });
        return Response.json({
          data: {
            id: 'agt_new',
            name: 'saved-agent',
            manifest: { model: { name: 'test/model' } },
          },
        });
      }
      return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    const result = await builder.saveAgent({
      agentName: 'saved-agent',
      agentSpec: {
        model: { name: 'test/model' },
        skills: [{ name: 'review' }],
      },
      intent: 'create',
    });

    assert.deepEqual(result, { agentId: 'agt_new' });
    assert.deepEqual(requests.at(-1)?.body, {
      name: 'saved-agent',
      description: 'saved-agent',
      manifest: {
        model: { name: 'test/model' },
        skills: [{ name: 'review', preload: false }],
      },
    });
  });

  it('saveAgent create sends top-level description and strips it from the manifest', async () => {
    const requests: { method: string; url: string; body?: unknown }[] = [];
    const fetchMock: typeof fetch = async (input, init) => {
      const url = input instanceof Request ? input.url : String(input);
      const method = init?.method ?? 'GET';
      if (url.endsWith('/api/v1/agents') && method === 'POST' && typeof init?.body === 'string') {
        requests.push({ method, url, body: JSON.parse(init.body) });
        return Response.json({
          data: {
            id: 'agt_desc',
            name: 'described-agent',
            description: 'Helps with reviews.',
            manifest: { model: { name: 'test/model' } },
          },
        });
      }
      return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    await builder.saveAgent({
      agentName: 'described-agent',
      description: 'Helps with reviews.',
      agentSpec: {
        model: { name: 'test/model' },
        skills: [{ name: 'review' }],
      },
      intent: 'create',
    });

    assert.deepEqual(requests.at(-1)?.body, {
      name: 'described-agent',
      description: 'Helps with reviews.',
      manifest: {
        model: { name: 'test/model' },
        skills: [{ name: 'review', preload: false }],
      },
    });
  });

  it('saveAgent updates when the name already exists', async () => {
    const requests: { method: string; url: string; body?: unknown }[] = [];
    const fetchMock: typeof fetch = async (input, init) => {
      const url = input instanceof Request ? input.url : String(input);
      const method = init?.method ?? 'GET';
      if (isAgentsCollectionUrl(url) && method === 'GET') {
        return Response.json({
          data: [{ id: 'agt_1', name: 'writer', manifest: { model: { name: 'test/model' } } }],
          pagination: { limit: 25 },
        });
      }
      if (url.endsWith('/api/v1/agents/agt_1') && method === 'PUT' && typeof init?.body === 'string') {
        requests.push({ method, url, body: JSON.parse(init.body) });
        return Response.json({
          data: {
            id: 'agt_1',
            name: 'writer',
            manifest: {
              model: { name: 'test/model' },
              instructions: 'Write release notes.',
            },
          },
        });
      }
      return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    const result = await builder.saveAgent({
      agentName: 'writer',
      agentSpec: {
        model: { name: 'test/model' },
        instructions: 'Write release notes.',
      },
      intent: 'update',
    });

    assert.deepEqual(result, { agentId: 'agt_1' });
    assert.equal(requests.length, 1);
    assert.deepEqual(requests[0]?.body, {
      manifest: {
        model: { name: 'test/model' },
        instructions: 'Write release notes.',
      },
    });
  });

  it('deleteAgent deletes by name via list + DELETE', async () => {
    const requests: { method: string; url: string }[] = [];
    const fetchMock: typeof fetch = async (input, init) => {
      const url = input instanceof Request ? input.url : String(input);
      const method = init?.method ?? 'GET';
      requests.push({ method, url });
      if (isAgentsCollectionUrl(url) && method === 'GET') {
        return Response.json({
          data: [{ id: 'agt_1', name: 'writer', manifest: { model: { name: 'test/model' } } }],
          pagination: { limit: 25 },
        });
      }
      if (url.endsWith('/api/v1/agents/agt_1') && method === 'DELETE') {
        return Response.json({});
      }
      return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    await builder.deleteAgent?.({ agentName: 'writer' });

    assert.equal(requests.length, 2);
    assert.equal(requests[0]?.method, 'GET');
    assert.equal(requests[1]?.method, 'DELETE');
    assert.ok(requests[1]?.url.endsWith('/api/v1/agents/agt_1'));
  });

  it('deleteAgent is a no-op when the name is missing', async () => {
    const requests: { method: string; url: string }[] = [];
    const fetchMock: typeof fetch = async (input, init) => {
      const url = input instanceof Request ? input.url : String(input);
      const method = init?.method ?? 'GET';
      requests.push({ method, url });
      if (isAgentsCollectionUrl(url) && method === 'GET') {
        return Response.json({ data: [], pagination: { limit: 25 } });
      }
      return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    await builder.deleteAgent?.({ agentName: 'missing' });

    assert.equal(requests.length, 1);
    assert.equal(requests[0]?.method, 'GET');
  });

  it('getMcp returns the complete catalog in one request', async () => {
    let calls = 0;
    const fetchMock: typeof fetch = async input => {
      const url = input instanceof Request ? input.url : String(input);
      if (!url.includes('/api/v1/mcp-servers')) {
        return new Response(`Unexpected request: ${url}`, { status: 500 });
      }
      calls += 1;
      return Response.json({
        data: [
          {
            name: 'a',
            url: 'https://a.example/mcp',
            auth_status: { status: 'authenticated' },
          },
          {
            name: 'b',
            url: 'https://b.example/mcp',
            auth_status: { status: 'authenticated' },
          },
        ],
      });
    };

    const builder = createHarnessBuilderServer({ fetch: fetchMock });
    const all = await builder.getMcp();
    assert.deepEqual(
      all.map(row => row.name),
      ['a', 'b'],
    );
    assert.equal(calls, 1);
  });
});