Agentic auth improvements: lazy login, --json consistency, and pc target fixes#83
Merged
austin-denoble merged 7 commits intomainfrom Apr 6, 2026
Merged
Conversation
…, same as login, when pc target needs to authenticate the URL is output to stdout properly, add shorthand --json flag for needed commands
…show/--clear are now not blocked by auth state
…e sure auth local-keys is not blocked by auth logic, remove duplicated output
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
target TTY detection, add shorthand --json | -j flag--json consistency, and pc target fixes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Problem
After previous changes to daemonize the login flow and improve overall I/O, there were still some rough edges when working with the CLI through an agent. Lack of consistent
--jsonflag representation was still an issue for a few flags, primarily around not supporting a shorthand option. Thepc targetcommand also needed changes to better support "headless", or agentic operation effectively. In-client documentation around the specifics of some of these operations also need to be improved to better guide users and agents when authenticating.Solution
This PR improves the CLI's behavior in agentic/non-TTY contexts (Claude Code, Cursor, other AI coding agents). It builds on the daemon-backed login flow from #82
-jshorthand added to login commandspc loginandpc auth loginwere missing the-jshorthand for--json, inconsistent with every other command. Fixed.Lazy auth completion
Added
login.EnsureAuthenticated, called from aPersistentPreRunhook on the root command. After a successful browser login, the next command run — any command — automatically detects the completed session, reloads credentials, and initializes the target org/project context. A secondpc login --jsoncall is no longer required before running other commands.Commands that don't require authentication are explicitly exempted:
pc login,pc logout,pc auth login/logout/configure/clear/status/_daemon,pc auth local-keys/list,pc target(which handles its own auth after local-state early returns),pc version, and allpc configsubcommands.pc targetfixespc targetnow detects non-TTY stdout and enables JSON mode automatically, consistent withpc login.pc target --jsonwith no targeting flags now returns the current target context as JSON (equivalent to--show --json) instead of an error. This early return is correctly placed before auth and API calls, so it works for API-key users and requires no credentials.--showand--clearunblocked — These are local-state-only operations; they now return before the auth gate and before any API calls.pc targettriggers an org-switch re-auth, the auth URL is printed to stderr only. Stdout remains a single JSON document, keeping output compatible withjq .and other single-document parsers.returnafterexit.Error— Addedreturnguards after allexit.Errorcalls in target and root pre-run, preventing fall-through when the exit handler is mocked in tests.applyAuthContext/RunPostAuthSetuprefactorExtracted the org/project state-setting logic from
RunPostAuthSetupinto a newapplyAuthContexthelper that returns the user's email. This eliminates a redundantoauth.Token+ParseClaimsUnverifiedcall thatRunPostAuthSetupwas making immediately afterapplyAuthContexthad already fetched the same data.applyAuthContextnow also always writesstate.TargetProj(clearing it when the org has no projects), preventing stale project data from a previous session from appearing in the authenticated JSON response.Root pre-run JSON error output
EnsureAuthenticatederrors in the rootPersistentPreRunnow check both TTY state and the command's own--json/-jflag, so auth errors are machine-readable when a caller explicitly requests JSON even in a TTY context.Deduplication
Extracted
printTargetContextJSON()intarget.go, replacing three identical blocks that each readstate.GetTargetContext(), masked the API key, and printed JSON.Documentation
Updated
pc login,pc auth login, andpc targethelp text to document the interactive vs. agentic flows, the two-call pending/authenticated pattern, session resumability, and the lazy context initialization behavior. Also fixed a typo inpc target's example (-project→--project).Type of Change
Test Plan
Interactive login (TTY)
pc loginopens a browser and completes auth, sets target org/project, prints success messagepc auth loginsame as aboveAgentic login (non-TTY /
--json)pc login --jsonreturns{"status":"pending","url":"...","session_id":"..."}and exits immediately-jshorthand works identically on bothpc loginandpc auth loginpc login --jsonafter completing browser auth returns{"status":"authenticated",...}with org/project populatedpc index list --json) after browser auth — without a secondpc logincall — succeeds and sets target context automaticallypc login | cat) triggers non-TTY path automatically without needing--jsonLazy auth /
EnsureAuthenticatedpc login --json+ browser auth,pc index list --jsonworks without a second login callpc auth statusworks with no credentials (not blocked by auth gate)pc auth local-keys listworks with no credentials (not blocked by auth gate)pc versionworks with no credentialspc configsubcommands work with no credentialspc targetpc target --showworks with no credentialspc target --clearworks with no credentialspc target --json(no flags) returns current target context as JSON, works with no credentialspc target --json --org "name"sets org and returns updated context as JSONpc target --json --org "name" --project "name"sets both and returns updated contextpc targetin a TTY launches interactive selector as beforepc targetin a non-TTY (or with--json) without targeting flags returns current context rather than erroringAuth errors
{"error":"..."}to stdout when stdout is non-TTY--jsonflag returns{"error":"..."}to stdout even in a TTYNote
Medium Risk
Adds a global authentication pre-check for most commands and changes login/target behavior in non-TTY JSON mode, which could affect automation and command execution paths if the skip list or auth detection is incorrect.
Overview
Adds a root-level auth gate for most commands.
pcnow runslogin.EnsureAuthenticated()inPersistentPreRun, with a curated skip list for commands that manage credentials/local state, and auto-detects JSON mode (non-TTY stdout or--json/-j) to format auth errors appropriately.Improves non-interactive/agentic UX.
loginandauth logingain-jshorthand and updated help/examples;targetnow auto-enables JSON mode in non-TTY contexts, supportspc target --jsonas an auth-free “show current context” path, and centralizes JSON context printing.Refactors and extends post-auth setup. Login utilities split context initialization into
applyAuthContext(), ensure target project state is cleared when no projects exist, keep stdout clean during wait-mode by printing auth URLs to stderr, and introduceEnsureAuthenticated()to lazily complete pending daemon sessions and auto-initialize org/project context after successful browser auth.Reviewed by Cursor Bugbot for commit ddb7ecd. Bugbot is set up for automated code reviews on this repo. Configure here.