Skip to content

CustomAgents - Ignores agents loaded from .github/agents folder #1889

Open

Description

@shudles

When you set SessionConfig.CustomAgents all agents that would be otherwise loaded from the workspace .github/agent folder are ignored

This simple examples shows the behaviour

using GitHub.Copilot;

// path to .github folder containing agents folder
const string WorkingDirectory = @"C:\SomeWorkspace";

await using var client = new CopilotClient();

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    WorkingDirectory = WorkingDirectory,
    EnableConfigDiscovery = true, // Note that this has to be true to get any agents to load from disk - (see https://github.com/github/copilot-sdk/issues/1887)
    CustomAgents = [ // Remove this property and you'll see that all agents are loaded from the .github/agents folder
        new() {
            Name = "Custom"
        }
    ]
});

var agentsList = await session.Rpc.Agent.ListAsync();

foreach (var agent in agentsList.Agents)
{
    // You'll only see the "Custom" agent.
    Console.WriteLine(agent.Name);
}

Agent file I was using in a .github/agents/sample.agent.md file:

---
name: sample
description: Sample Agent
---

You are an sample agent for this repository, you're just happy to be here!

The agent list isn't merged together like skills, instructions and MCPs are.

Additionally, are there any plans to bring the agents loaded in via the CustomAgents property into full parity with agents loaded from the .github/agents folder? It seems that not all properties are supported, like Handoffs, which means no SessionHandoffEvent can ever be raised and agent passing can only happen via sub-agents via the task tool.

Activity

  1. github-actions commented on Jul 2, 2026

    @github-actions
    Contributor

    Investigation findings

    Thanks for the detailed report. I investigated the relevant code in the .NET SDK (dotnet/src/Types.cs, dotnet/src/Client.cs) and the documentation (docs/features/custom-agents.md) to understand this behavior.

    What I found

    The non-merging behavior is by design, not a bug. The EnableConfigDiscovery property's documentation explicitly describes what it merges:

    When true, automatically discovers MCP server configurations (e.g. .mcp.json, .vscode/mcp.json) and skill directories from the working directory and merges them with any explicitly provided McpServers and SkillDirectories, with explicit values taking precedence on name collision.

    Agents from .github/agents are not listed among what gets merged. The SDK simply passes both customAgents and enableConfigDiscovery as separate parameters to the Copilot CLI runtime — no merge is performed on the SDK side either. The runtime treats programmatic CustomAgents and workspace-discovered agents as distinct, non-combined sources.

    This asymmetry is real — MCPs and skills are merged, but agents are not — but it reflects the current design rather than a defect.

    On the Handoffs / SessionHandoffEvent parity concern

    You are correct that CustomAgentConfig (in dotnet/src/Types.cs) does not expose a Handoffs property. The current public properties are: Name, DisplayName, Description, Tools, Prompt, McpServers, Infer, Skills, and Model. SessionHandoffEvent exists in the generated session events, but it can only be raised by workspace-file-based agents today.

    Reclassification

    Both observations — merging workspace agents with CustomAgents when EnableConfigDiscovery is true, and adding Handoffs support and other missing properties to CustomAgentConfig — represent new capabilities beyond what is currently designed and documented. I'm relabelling this as an enhancement request.

    The workaround today, as you noted, is to either:

    • Use only CustomAgents (and duplicate any workspace agents programmatically), or
    • Use only EnableConfigDiscovery = true without setting CustomAgents (relying entirely on .github/agents files).

    Agent merging and full CustomAgentConfig parity with workspace agents would be a valuable addition to the SDK. Leaving this open for the team to evaluate.

    Generated by Bug Handler for issue #1889 · sonnet46 2M · ◷

  2. patniko commented on Oct 26, 2026

    @patniko
    Contributor

    Thanks for the report. We've shipped fixes in this area since this was filed, and we believe this may now be resolved. Could you retest on the latest release (Copilot SDK v1.0.26, which bundles Copilot CLI v1.0.103) and let us know whether you still see it? If we don't hear back in a couple of weeks, we may close this issue — you can always reopen it.

    Triaged as part of a Copilot SDK backlog review, with help from GitHub Copilot.

  3. roji commented on Nov 18, 2026

    @roji
    Member

    I executed the original .NET discovery scenario against the published GitHub.Copilot.SDK 1.0.34 NuGet package and runtime 1.0.112. The workspace agent is now merged with the explicitly supplied agent:

    Configuration Actual agent names
    Workspace .github/agents/sample.agent.md only sample
    Same workspace plus CustomAgents=[new(){Name="Custom"}] Custom, sample

    The fixture uses the default CopilotCli client mode, EnableConfigDiscovery=true, an isolated Git-initialized workspace, and no CustomAgentsLocalOnly override. It does not need model inference. Equivalent Node checks passed on SDK/runtime 1.0.34/1.0.112 and 2.0.0/1.0.113.

    This supersedes the earlier comment's claim that explicit and discovered agents are intentionally never merged.

    Leaving this issue open: its additional request for full programmatic-agent property parity, specifically Handoffs / SessionHandoffEvent, is distinct. The list-merging check neither demonstrates nor implements that feature, so a passing original repro is not proof that the whole issue is addressed.

    Executed .NET project (published NuGet 1.0.34)

    Save as sdk-dotnet-discovery-repro/Check.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <NoWarn>$(NoWarn);GHCP001</NoWarn>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="GitHub.Copilot.SDK" Version="1.0.34" />
      </ItemGroup>
    </Project>

    Save as sdk-dotnet-discovery-repro/Program.cs:

    using GitHub.Copilot;
    using System.Diagnostics;
    using System.Text.Json;
    
    var directory = Path.Combine(args[0], $"discovery-{Guid.NewGuid():N}");
    Directory.CreateDirectory(Path.Combine(directory, "tmp"));
    Directory.CreateDirectory(Path.Combine(directory, ".github", "agents"));
    File.WriteAllText(Path.Combine(directory, ".github", "agents", "sample.agent.md"),
        "---\nname: sample\ndescription: Sample workspace agent\n---\nYou are the workspace discovery fixture.\n");
    using (var git = Process.Start(new ProcessStartInfo("git")
    {
        ArgumentList = { "init", "--quiet", directory },
        UseShellExecute = false,
    })!)
    {
        await git.WaitForExitAsync();
        if (git.ExitCode != 0) throw new Exception("git init failed");
    }
    await using var client = new CopilotClient(new CopilotClientOptions
    {
        Connection = RuntimeConnection.ForStdio(args[1]),
        Mode = CopilotClientMode.CopilotCli,
        BaseDirectory = directory,
        WorkingDirectory = directory,
        UseLoggedInUser = false,
        Environment = new Dictionary<string, string>
        {
            ["PATH"] = Environment.GetEnvironmentVariable("PATH")!,
            ["HOME"] = directory,
            ["TMPDIR"] = Path.Combine(directory, "tmp"),
        },
    });
    var results = new List<object>();
    foreach (var explicitAgents in new[] { false, true })
    {
        await using var session = await client.CreateSessionAsync(new SessionConfig
        {
            Model = "gpt-4.1",
            Provider = new ProviderConfig { Type = "openai", BaseUrl = "http://127.0.0.1:9/v1", ApiKey = "local" },
            WorkingDirectory = directory,
            EnableConfigDiscovery = true,
            AvailableTools = [],
            OnPermissionRequest = PermissionHandler.ApproveAll,
            CustomAgents = explicitAgents ? [new() { Name = "Custom" }] : null,
        });
        var listed = await session.Rpc.Agent.ListAsync();
        var names = listed.Agents.Select(agent => agent.Name).ToArray();
        if (!names.Contains("sample") || (explicitAgents && !names.Contains("Custom")))
            throw new Exception(JsonSerializer.Serialize(names));
        results.Add(new { explicitAgents, agents = names });
    }
    var output = JsonSerializer.Serialize(new { issue = 1889, sdk = "GitHub.Copilot.SDK 1.0.34", results });
    File.WriteAllText(Path.Combine(directory, "result.json"), output);
    Console.WriteLine(output);

    Run with dotnet run --project sdk-dotnet-discovery-repro -- <writable-fixture-parent-directory> <path-to-copilot-runtime>. The runtime used here is the published 1.0.112 binary bundled with @github/[email protected]; no inference or credentials are required.

    Runnable reproduction / diagnostic (repro-1889.mjs)

    Put the files below together in an otherwise empty directory. Install the exact packages and run:

    npm install --save-exact @github/[email protected] @microsoft/[email protected]
    node repro-1889.mjs
    node repro-1889.mjs --v2

    repro-1889.mjs:

    import assert from "node:assert/strict";
    import { mkdir, writeFile } from "node:fs/promises";
    import { execFileSync } from "node:child_process";
    import { fixture, isV2 } from "./repro-support.mjs";
    
    const f = await fixture(1889);
    const results = [];
    try {
      execFileSync("git", ["init", "--quiet", f.directory]);
      await mkdir(`${f.directory}/.github/agents`, { recursive: true });
      await writeFile(`${f.directory}/.github/agents/workspace-agent.agent.md`,
        "---\nname: workspace-agent\ndescription: Workspace discovery witness\n---\nYou are the workspace discovery fixture.\n");
      for (const explicit of [false, true]) {
        const definitions = [{ name: "supplied-agent", description: "SDK definition", prompt: "You are the SDK fixture." }];
        const session = await f.client.createSession(f.options({
          workingDirectory: f.directory, enableConfigDiscovery: true,
          ...(isV2 ? { agents: { localDiscoveryOnly: false, ...(explicit ? { definitions } : {}) } }
            : { customAgentsLocalOnly: false, ...(explicit ? { customAgents: definitions } : {}) }),
        }));
        const list = await session.rpc.agent.list();
        const names = list.agents.map((agent) => agent.name);
        if (!explicit) assert(names.includes("workspace-agent"), JSON.stringify(list));
        results.push({ explicitAgents: explicit, agents: names });
        await session.disconnect();
      }
      await f.finish(results);
    } catch (error) { await f.finish(results, error); }

    The shared fixture below supplies the isolated spawned runtime and loopback endpoint. Its Responses/Completions replies only drive the runtime through the operation; they are not claims about live provider behavior.

    repro-support.mjs:

    import { createServer } from "node:http";
    import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
    import { fileURLToPath } from "node:url";
    import * as v1 from "@github/copilot-sdk";
    import * as v2 from "@microsoft/copilot-sdk";
    
    export const isV2 = process.argv.includes("--v2");
    export const sdk = isV2 ? v2 : v1;
    export const version = isV2 ? "2.0.0" : "1.0.34";
    export const root = fileURLToPath(new URL(".", import.meta.url)).replace(/\/$/, "");
    
    export async function fixture(issue, respond) {
      const directory = await mkdtemp(`${root}/repro-${issue}-v${isV2 ? 2 : 1}-`);
      await mkdir(`${directory}/tmp`);
      const requests = [];
      const server = createServer(async (req, res) => {
        try {
          let raw = "";
          for await (const chunk of req) raw += chunk;
          const body = raw ? JSON.parse(raw) : {};
          requests.push({ path: req.url, body });
          if (respond) return await respond(req, res, body, requests);
          if (req.url.includes("/responses")) responses(res, body);
          else completion(res, body);
        } catch (error) {
          res.writeHead(500, { "content-type": "application/json" });
          res.end(JSON.stringify({ error: { message: error.message } }));
        }
      });
      await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
      const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;
      const env = { PATH: process.env.PATH, HOME: directory, TMPDIR: `${directory}/tmp` };
      const client = new sdk.CopilotClient(isV2 ? {
        runtime: sdk.RuntimeConnection.forSpawnedStdio({ baseDirectory: directory, env, workingDirectory: directory }),
        mode: "empty", github: { useLoggedInUser: false },
      } : {
        connection: sdk.RuntimeConnection.forStdio(), mode: "empty",
        baseDirectory: directory, workingDirectory: directory, env, useLoggedInUser: false,
      });
      const record = { issue, sdk: version, platform: process.platform, arch: process.arch, directory };
      await client.start();
      record.runtime = await client.getStatus();
      function options({ model = "gpt-4.1", wireApi = "completions", provider = {}, modelConfig = {}, capabilities, ...extra } = {}) {
        if (!isV2) return {
          model, provider: { type: "openai", baseUrl, apiKey: "local-fixture", wireApi, ...provider },
          availableTools: [], onPermissionRequest: sdk.approveAll,
          infiniteSessions: { enabled: false }, enableSessionStore: false,
          ...(capabilities ? { modelCapabilities: capabilities } : {}), ...extra,
        };
        const { modelId = model, wireModel = model, ...connection } = provider;
        return {
          model: "fixture/test",
          inference: {
            providers: [{ name: "fixture", type: "openai", baseUrl, apiKey: "local-fixture", wireApi, ...connection }],
            models: [{ id: "test", provider: "fixture", modelId, wireModel, ...modelConfig }],
            ...(capabilities ? { capabilities } : {}),
          },
          github: { capi: { enabled: false } },
          tools: { availableTools: [] }, permissions: { onRequest: sdk.approveAll },
          state: { infiniteSessions: { enabled: false }, enableCrossSessionStore: false }, ...extra,
        };
      }
      async function finish(result, error) {
        record.result = result;
        if (error) record.error = error.stack;
        const errors = await client.stop();
        record.teardownErrors = errors.map(String);
        server.closeAllConnections();
        await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
        await writeFile(`${directory}/requests.json`, `${JSON.stringify(requests, null, 2)}\n`);
        await writeFile(`${directory}/result.json`, `${JSON.stringify(record, null, 2)}\n`);
        console.log(JSON.stringify(record));
        if (error || errors.length) process.exitCode = 1;
      }
      return { client, directory, baseUrl, requests, options, finish };
    }
    
    export function completion(res, body, { content = "fixture-complete", toolCalls } = {}) {
      const message = { role: "assistant", content: toolCalls ? null : content, ...(toolCalls ? { tool_calls: toolCalls } : {}) };
      if (!body.stream) {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion", created: 1, model: body.model,
          choices: [{ index: 0, message, finish_reason: toolCalls ? "tool_calls" : "stop" }],
          usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 } }));
        return;
      }
      res.writeHead(200, { "content-type": "text/event-stream" });
      for (const [delta, finish_reason] of [[message, null], [{}, toolCalls ? "tool_calls" : "stop"]]) {
        res.write(`data: ${JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 1, model: body.model,
          choices: [{ index: 0, delta: { ...delta, ...(toolCalls ? { tool_calls: toolCalls.map((call, index) => ({ index, ...call })) } : {}) }, finish_reason }] })}\n\n`);
      }
      res.end("data: [DONE]\n\n");
    }
    
    export function responses(res, body) {
      const content = { type: "output_text", text: "fixture-complete", annotations: [] };
      const item = { id: "msg_fixture", type: "message", status: "completed", role: "assistant", content: [content] };
      const response = { id: "resp_fixture", object: "response", created_at: 1, status: "completed",
        model: body.model, output: [item], usage: { input_tokens: 10, output_tokens: 4, total_tokens: 14 } };
      if (!body.stream) {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(JSON.stringify(response));
        return;
      }
      res.writeHead(200, { "content-type": "text/event-stream" });
      const events = [
        { type: "response.created", response: { ...response, status: "in_progress", output: [] } },
        { type: "response.output_item.added", output_index: 0, item: { ...item, status: "in_progress", content: [] } },
        { type: "response.content_part.added", item_id: item.id, output_index: 0, content_index: 0, part: { ...content, text: "" } },
        { type: "response.output_text.delta", item_id: item.id, output_index: 0, content_index: 0, delta: content.text },
        { type: "response.output_text.done", item_id: item.id, output_index: 0, content_index: 0, text: content.text },
        { type: "response.content_part.done", item_id: item.id, output_index: 0, content_index: 0, part: content },
        { type: "response.output_item.done", output_index: 0, item },
        { type: "response.completed", response },
      ];
      events.forEach((event, sequence_number) => res.write(`event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`));
      res.end();
    }
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