Skip to content

Explore: making gh better for agents #12522

Open

Description

@williammartin

Description

This house believes that a lot of gh usage and growth is being driven by agentic software and over time, this is only likely to continue increasing. Since we do not have client side telemetry, it's not possible to say this with certainty, but internal signals, looking around at the current agentic environment, and direct requests leads me to this conclusion.

This issue serves as a starting point for this exploration. We have no agreed upon direction here, and the following list is just a personal brain dump of different ways we might approach answering the questions:

  • How much gh usage is driven by agents?
  • Is it worth investing in improving gh for agents?
  • What are the best opportunities for improving gh for agents?

Some ideas:

  • Start a discussion on cli/cli for users to leave feedback
  • Add client side telemetry to gh, for example, inspecting environment variables like CLAUDECODE
  • Add client side telemetry to copilot CLI (or VS Code) when it tries to invoke gh
  • Partner with third party agentic software providers to understand how we can make gh better for them
  • Use agentic software to fuzzily explore the gh interface for opportunities (e.g. desire paths)
  • Produce evals for sets of expected first class workflows (e.g. create a PR, make sure the tests are passing)
  • Explore how other CLIs are treating agents as first class consumers
  • Check in on agentic communities (e.g. discords) and request feedback
  • Look at how publicly available agentic system prompts use gh (some caution needed here since we don't want this to cause a clean room issue with copilot)
  • Explore cases in which agents prefer to use the GitHub MCP server over gh

Activity

  1. deleted a comment from cliAutomation on Jan 23, 2026
  2. toby commented on Jan 23, 2026

    @toby
  3. babakks commented on Jan 23, 2026

    @babakks
    Member

    To add to the list, this is something that I've been thinking about for the past months:

    I can imagine at times agetns will need to inspect the available commands that gh provides. I'm not talking about help docs, but a machine readable data structure (e.g. in JSON) to expose available commands and flags/options. Such a data structure can basically serve agents similar to OpenAPI/Swagger specs (often served over /swagger.json endpoint for API inspection).

    I'm not going into details now, though. But this can even be an innovation that we can make public/reusable for others to use.

  4. williammartin commented on Jan 24, 2026

    @williammartin
    MemberAuthor

    Such a data structure can basically serve agents similar to OpenAPI/Swagger specs (often served over /swagger.json endpoint for API inspection).

    Potentially something like https://fig.io/docs/getting-started

  5. BagToad commented on Feb 6, 2026

    @BagToad
    Member

    Frequently I have agents messing up complex multi-line output for things like opening a PR:

    Image

    I don't have a proposed solution for this, but it's a pain point that keeps coming up. Maybe it's the model's fault for not properly escaping quotes all the time.

  6. PabloLION commented on Feb 8, 2026

    @PabloLION

    Use case: agents need scoped file reading without gh api

    Coding agents (Claude Code, Copilot, etc.) frequently need to read single files from remote repos — checking issue templates, reading upstream docs, comparing implementations. Today the only gh option is:

    gh api repos/{owner}/{repo}/contents/PATH

    The problem: gh api is a raw API passthrough. The same command that reads a file can also delete repos, modify org settings, or merge PRs. Agent permission systems (like Claude Code's) match commands by pattern — they cannot distinguish a read-only gh api call from a destructive one. This forces a choice:

    1. Auto-approve gh api — unsafe, gives agents unrestricted API access
    2. Require confirmation for every gh api call — constant interruptions for simple reads
    3. Fall back to raw.githubusercontent.com — only works for public repos, bypasses gh entirely

    A scoped subcommand like gh repo cat or gh cp would solve this. Permission systems could auto-approve it while keeping gh api restricted.

    Prior art:

    Since mislav/gh-cp already exists and is maintained by a GitHub engineer, promoting it (or its functionality) to a core command seems low-effort and high-impact for agent workflows.

  7. williammartin commented on Feb 16, 2026

    @williammartin
    MemberAuthor

    Had an internal report that copilot really would have found sub-issue support useful.

  8. williammartin commented on Feb 24, 2026

    @williammartin
    MemberAuthor

    @meowgorithm suggested that we add gh skill that outputs a skill for using gh that we own and eval.

  9. EvanBoyle commented on Feb 26, 2026

    @EvanBoyle
  10. williammartin commented on Mar 5, 2026

    @williammartin
    MemberAuthor

    Cross linking #12839

  11. williammartin commented on Mar 12, 2026

    @williammartin
    MemberAuthor

    Cross linking #12912

  12. maxbeizer commented on Mar 15, 2026

    @maxbeizer
    Contributor

    Output Optimization for Agent Consumers

    Most of the discussion here has focused on discoverability (schema, skills) and safety (fork defaults, permission both critical. I want to add another angle: output optimization for token efficiency)

    Ben Rigby's recent post captures the pain pagination metadata gets thrown away, output is decoration-heavy, and agents pay for tokens they can't use. After digging through the codebase, here are concrete opportunities:

    The Problem

    Pain Point Example Token Cost
    Hidden pagination metadata Agent must know --include + parse Link headers to discover more pages exist Extra round-trips + header parsing
    ANSI color codes in TTY \x1b[32mOPEN\x1b[0m wraps every colored even with --json 12-15 wasted bytes per element
    Decorative output "Showing 30 of 247 in @owner/repo", # prefixes, "about 2 hours ago" ~40% of default output is decoration
    --json requires field enumeration Agent must already know field names to request them Forces help text lookup first
    Verbose help text 50+ lines per command, full doc URLs, prose descriptions ~2-3KB per --help call

    Proposed: --ai Flag (or GH_AI=1)

    A global flag that optimizes all command output for LLM/agent consumption:

    1. Auto-include pagination metadata in response body

    {
      "_pagination": { "count": 30, "hasNextPage": true, "total": 247 },
      "items": [ ... ]
    }

    This is the single highest-impact change. Agents shouldn't need to manage it's exactly the problem Ben spent a week debugging in the MCP server

    2. Strip ANSI formatting unconditionally

    Follow the existing IOStreams.SetColorEnabled(false) path. The plumbing is already there.

    3. Compact default field sets

    When --ai is used without explicit --json field selection, use curated minimal fields:

    • PR: number, title, state, author.login, baseRefName, headRefName, createdAt, url
    • Issue: number, title, state, author.login, labels, createdAt, url

    Agents can still use --ai --json field1,field2 for explicit fields.

    4. Structured JSON help

    {
      "command": "gh pr list",
      "description": "List pull requests in a repository",
      "flags": {
        "--state": { "type": "enum", "values": ["open","closed","merged","all"], "default": "open" },
        "--limit": { "type": "int", "default": 30 }
      },
      "available_json_fields": ["number", "title", "state", "author", "..."]
    }

    This connects to @babakks's schema idea but scoped to per-command help rather than a full CLI schema.

    5. Deterministic JSON errors

    { "error": true, "message": "Resource not found", "code": "NOT_FOUND" }

    No prose, no suggestions, no color-coded messages. Relates to @BagToad's point about agents struggling with complex output.

    Estimated Impact

    Scenario Current (est.) With --ai (est.) Savings
    gh pr list (30 PRs, TTY) ~4,500 tokens ~2,500 tokens ~44%
    gh pr list --json (all fields) ~12,000 tokens ~3,500 tokens (defaults) ~71%
    gh pr list --help ~800 tokens ~200 tokens ~75%
    Paginated query (5 pages) 5 calls + header parsing 1 response w/ metadata ~80% fewer calls

    Open Questions

    • Flag name: --ai is concise but --machine or --agent might be clearer. --machine has precedent in other CLIs.
    • Auto-pagination: Should --ai automatically fetch all pages up to --limit and return one response? Eliminates pagination entirely at cost of larger responses.
    • Composability: --ai should compose with --json, --jq, -- not replace them.template
    • Versioning: Should the format be versioned (--ai=v1) to allow evolution?

    This complements the schema/discoverability work discussed above. Schema tells agents what commands exist; output optimization ensures the responses are efficient to consume.

  13. labudis commented on Mar 16, 2026

    @labudis

    Linking an initiative in the same theme with the focus of making Issues and Projects a first class experience for Copilot CLI/agent work: https://github.com/github/planning-tracking/issues/2548

  14. BagToad commented on Mar 16, 2026

    @BagToad
    Member

    Hey @maxbeizer 👋 Thanks for the thorough write-up - lots of good thinking here.

    TL;DR - A couple of the ideas here are worth exploring (deterministic JSON errors, exposing totalCount in --json), but several of the pain points described are already solved by existing gh behaviour that agents get by default, so I think there are some misunderstandings to clarify.

    What's already working for agents today

    A few of the pain points in this comment assume agents see TTY output, but I don't think that is correct. When gh output is piped (which is how I believe agents invoke it), gh automatically switches to a machine-friendly mode:

    # ANSI colors - not present when piped:
    $ gh pr list -L 1 --json number,title,state | cat -v
    [{"number":1234,"state":"OPEN","title":"Add new feature"}]
    
    # Decorative output - not present when piped:
    $ gh pr list -L 1
    1234	Add new feature	user:feature-branch	OPEN	2026-03-16T13:46:53Z
    
    # Pagination - automatic for list commands:
    $ gh pr list --limit 200 --json number
    
    # ⚠️ But nested fields in --json can silently truncate:
    # gh pr view --json comments → paginates all comments ✓
    # gh pr view --json files    → silently truncates at 100 items ✗

    ANSI only appears if GH_FORCE_TTY=1 or CLICOLOR_FORCE is set - which would be agent misconfiguration, or perhaps an intentional choice, but I'm not sure why someone would choose to do that. Maybe there's a use-case we don't know about.

    So to clarify: the "~40% decoration" figure and "12-15 wasted bytes per element" appear to have been measured against TTY output, which agents don't receive. I'd encourage re-running those estimates against piped output to get accurate baselines.

    What I think is worth exploring

    Deterministic JSON errors. Today, errors are always plain text to stderr, even when --json is active:

    $ gh api repos/cli/cli/pulls/999999
    {"message":"Not Found","documentation_url":"...","status":"404"}  # stdout (API body)
    gh: Not Found (HTTP 404)                                          # stderr (prose)

    A structured error format when --json might be an improvement, but I don't think I understand the value off the extra JSON structure vs something simple like ensuring gh always prints the full help docs on a command failure when invoked by an agent.

    Exposing totalCount in --json output - this is one of two pagination gaps. List commands auto-paginate via --limit, but the total count (e.g., "247 total PRs") is only shown in the TTY header. Including it in --json output would help agents know whether they've fetched everything. That said, wrapping the response in a {"_pagination": ..., "items": [...]} envelope would be a breaking change to the --json contract - every consumer expecting an array would break, including --jq pipelines. I think we need to come up with some other ideas for this problem space; maybe we could forcibly include a _totalCount field in the existing objects when --json is used by an agent.

    Nested field pagination in --json - the other pagination gap isn't about list commands specifically. When you do gh pr view --json comments, the CLI internally paginates to fetch all comments (and reviews, statusCheckRollup, closingIssuesReferences). But gh pr view --json files or --json commits silently truncates at 100 items - there's no preload pagination for those fields (files fragment, commits fragment, preload functions that exist). An agent viewing a large PR wouldn't know it's missing file changes. I think this really just alludes to broader gh review process gaps.

    Structured JSON help - reasonable idea. This overlaps with the CLI schema discussion in #12912.

    Concerns with the --ai flag approach

    I think bundling five unrelated concerns (pagination, formatting, field defaults, help format, error format) into a single --ai flag could be confusing. Each has different tradeoffs:

    • Strip ANSI - already solved (piped output + NO_COLOR)
    • Compact field defaults - overly opinionated; who decides what's "minimal"? Different use-cases might need different fields.
    • Auto-pagination - list-level pagination already exists (--limit, --paginate), but nested field pagination has real gaps (files, commits truncate silently at 100 items). Not sure what to do about that at the moment
    • JSON errors - potentially useful, but could be --json-aware rather than needing a separate flag. Even then, I'm not sure what value having a structured error would bring beyond just ensuring the full help docs are always printed on error when invoked by an agent. The full help docs include valuable things to agents like what fields are available for --json, which is often a point of confusion that isn't exposed to an agent right now unless they trigger a --help flow
    • JSON help - sort of tracked in CLI Schema - enforcing a security policy for AI agents #12912

    The token cost estimates in the table also seem to be based on TTY baselines, so the "savings" figures are likely overstated.

    All that said, I want to like this idea of having a single "agent mode" flag that optimizes output for agents, but gh already has a comprehensive "automation output" design philosophy that I think we should look at a lot of this more from the angle of "what gaps currently exist in our automation/non-tty output?".

  15. maxbeizer commented on Mar 16, 2026

    @maxbeizer
    Contributor

    The token cost estimates in the table also seem to be based on TTY baselines, so the "savings" figures are likely overstated.

    Honestly, not surprised if this is indeed the case. As i was writing it and asking Copilot, that figure seemed suspiciously high.

    All that said, I want to like this idea of having a single "agent mode" flag that optimizes output for agents, but gh already has a comprehensive "automation output" design philosophy that I think we should look at a lot of this more from the angle of "what gaps currently exist in our automation/non-tty output?".

    This is a fair take. I think your point about five unrelated concerns rings true with me as well. Happy to discuss further if you'd like to chat about any of the points where improvements make sense

  16. ChrisRomp commented on Mar 23, 2026

    @ChrisRomp

    Adding in that my agent uses GH CLI a lot to interact with CCR/review feedback, but ultimately has to call gh api with GraphQL calls. If there were tools in there to facilitate that it could be more deterministic.

  17. williammartin commented on May 12, 2026

    @williammartin
    MemberAuthor

    @BagToad

    When gh output is piped (which is how I believe agents invoke it)

    Some agents (copilot CLI, gemini) right now execute gh with a PTY attached, so they get the experience as if a human were typing at a terminal. Other agents (claude) execute without. Of course, sometimes agents know what they want and do gh <cmd> | <other cmd> in which case, the other command gets the piped form, and that would depend on what <other cmd> is doing with the stream.

  18. BagToad commented on May 12, 2026

    @BagToad
    Member

    @williammartin I have had to recently tell my Copilot CLI to use GH_FORCE_TTY=true to get prompting to work when I want it to - maybe something is changing in that area?

    I've noticed some weird behavior in general where I get loading spinners but "prompting not possible" messages in Copilot CLI.

    It's like interactivity is on but not on fully. I haven't looked into it deeply.

  19. tolomea commented on Jul 13, 2026

    @tolomea

    @PabloLION

    A scoped subcommand like gh repo cat or gh cp would solve this. Permission systems could auto-approve it while keeping gh api restricted.

    A broader take would be a readonly slice of the api so something like gh api-read

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions