Token Management API
Token Management API Reference
Section titled “Token Management API Reference”The token management module provides automatic token switching based on repository organization. It eliminates manual token management when working across multiple GitHub organizations by routing API calls to the correct credentials.
Import
Section titled “Import”import { // Configuration getTokenConfig, setTokenConfig, resetTokenConfig, addOrganization, removeOrganization,
// Token resolution getTokenForRepo, getTokenForOrg, getTokenEnvVar, getPRReviewToken, getPRReviewTokenEnvVar,
// Organization helpers extractOrg, getOrgConfig, getConfiguredOrgs, isOrgConfigured,
// Validation validateTokens, hasTokenForOrg, hasTokenForRepo,
// Subprocess helpers getEnvForRepo, getEnvForPRReview,
// Debugging getTokenSummary,} from '@jbcom/agentic';Configuration
Section titled “Configuration”Token configuration can be set through three methods, listed in priority order:
- Programmatic:
setTokenConfig()/addOrganization() - Config file:
agentic.config.jsonwith"tokens"section - Environment variables:
AGENTIC_ORG_<NAME>_TOKENpattern
TokenConfig Schema
Section titled “TokenConfig Schema”interface TokenConfig { /** Mapping of org name to configuration */ organizations: Record<string, OrganizationConfig>; /** Default token env var when org is unknown (default: "GITHUB_TOKEN") */ defaultTokenEnvVar: string; /** Token env var for PR reviews -- ensures consistent identity (default: "GITHUB_TOKEN") */ prReviewTokenEnvVar: string;}
interface OrganizationConfig { /** Organization name (e.g., "my-org") */ name: string; /** Environment variable name for the token */ tokenEnvVar: string; /** Default branch for repos in this org */ defaultBranch?: string; /** Whether this is a GitHub Enterprise org */ isEnterprise?: boolean;}Configuration Functions
Section titled “Configuration Functions”setTokenConfig()
Section titled “setTokenConfig()”Set or merge token configuration. Organizations are merged (not replaced) with existing config.
setTokenConfig(config: Partial<TokenConfig>): voidimport { setTokenConfig } from '@jbcom/agentic';
setTokenConfig({ organizations: { 'my-company': { name: 'my-company', tokenEnvVar: 'GITHUB_COMPANY_TOKEN', }, 'partner-org': { name: 'partner-org', tokenEnvVar: 'PARTNER_GH_PAT', }, }, defaultTokenEnvVar: 'GITHUB_TOKEN', prReviewTokenEnvVar: 'GITHUB_BOT_TOKEN',});getTokenConfig()
Section titled “getTokenConfig()”Get the current token configuration. Returns a shallow copy.
getTokenConfig(): TokenConfigconst config = getTokenConfig();console.log('Configured orgs:', Object.keys(config.organizations));console.log('Default token:', config.defaultTokenEnvVar);console.log('PR review token:', config.prReviewTokenEnvVar);resetTokenConfig()
Section titled “resetTokenConfig()”Reset configuration to defaults and reload from environment variables. Useful for testing.
resetTokenConfig(): voidaddOrganization()
Section titled “addOrganization()”Add or update a single organization configuration.
addOrganization(org: OrganizationConfig): voidimport { addOrganization } from '@jbcom/agentic';
addOrganization({ name: 'my-company', tokenEnvVar: 'GITHUB_MYCOMPANY_TOKEN', defaultBranch: 'main', isEnterprise: true,});
// Token is now available for repos in this orgconst token = getTokenForRepo('my-company/my-repo');removeOrganization()
Section titled “removeOrganization()”Remove an organization from the configuration.
removeOrganization(orgName: string): voidToken Resolution
Section titled “Token Resolution”getTokenForRepo()
Section titled “getTokenForRepo()”Get the actual token value for a repository URL. This is the primary resolution function.
getTokenForRepo(repoUrl: string): string | undefinedResolution order:
- Extract organization from the URL using
extractOrg() - Look up the organization in
config.organizations(case-insensitive) - If found, return
process.env[org.tokenEnvVar] - If not found, return
process.env[config.defaultTokenEnvVar]
import { getTokenForRepo, addOrganization } from '@jbcom/agentic';
addOrganization({ name: 'my-company', tokenEnvVar: 'GITHUB_COMPANY_TOKEN',});
// By owner/name formatconst token1 = getTokenForRepo('my-company/my-repo');// Returns value of GITHUB_COMPANY_TOKEN
// By full URLconst token2 = getTokenForRepo('https://github.com/my-company/my-repo');// Same result
// By SSH URLconst token3 = getTokenForRepo('git@github.com:my-company/my-repo.git');// Same result
// Unknown org falls back to defaultconst token4 = getTokenForRepo('unknown-org/repo');// Returns value of GITHUB_TOKENgetTokenForOrg()
Section titled “getTokenForOrg()”Get the token value for an organization name directly (without URL parsing).
getTokenForOrg(org: string): string | undefinedconst token = getTokenForOrg('my-company');// Returns process.env[configured_env_var] or process.env[default]getTokenEnvVar()
Section titled “getTokenEnvVar()”Get the environment variable name (not the value) for an organization. Case-insensitive lookup with exact match priority.
getTokenEnvVar(org: string): stringconst envVar = getTokenEnvVar('my-company');// Returns "GITHUB_COMPANY_TOKEN" (or defaultTokenEnvVar if not configured)getPRReviewToken()
Section titled “getPRReviewToken()”Get the token designated for PR review operations. This ensures all PR reviews use a consistent identity (e.g., a bot account).
getPRReviewToken(): string | undefinedconst token = getPRReviewToken();// Returns process.env[prReviewTokenEnvVar]getPRReviewTokenEnvVar()
Section titled “getPRReviewTokenEnvVar()”Get the environment variable name for the PR review token.
getPRReviewTokenEnvVar(): stringOrganization Helpers
Section titled “Organization Helpers”extractOrg()
Section titled “extractOrg()”Extract the organization name from a repository URL or owner/repo string. Uses safe regex patterns to prevent ReDoS attacks.
extractOrg(repoUrl: string): string | nullSupported formats:
extractOrg('https://github.com/my-org/my-repo'); // "my-org"extractOrg('my-org/my-repo'); // "my-org"extractOrg('git@github.com:my-org/my-repo.git'); // "my-org"extractOrg('not-a-repo'); // nullgetOrgConfig()
Section titled “getOrgConfig()”Get the full organization configuration object. Case-insensitive lookup with exact match priority.
getOrgConfig(org: string): OrganizationConfig | undefinedgetConfiguredOrgs()
Section titled “getConfiguredOrgs()”List all configured organization names.
getConfiguredOrgs(): string[]const orgs = getConfiguredOrgs();console.log('Configured orgs:', orgs);// ["my-company", "partner-org"]isOrgConfigured()
Section titled “isOrgConfigured()”Check if an organization has been configured (case-insensitive).
isOrgConfigured(org: string): booleanValidation
Section titled “Validation”validateTokens()
Section titled “validateTokens()”Validate that all configured tokens are actually available as environment variables.
validateTokens(orgs?: string[]): Result<string[]>Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
orgs | string[] | All configured orgs | Specific organizations to validate |
Returns: Result<string[]> where data contains the list of missing tokens and success is true if no tokens are missing.
Validates:
- All specified organization tokens
- The PR review token
- The default token
import { validateTokens } from '@jbcom/agentic';
const result = validateTokens();if (!result.success) { console.error('Missing tokens:'); for (const missing of result.data ?? []) { console.error(` - ${missing}`); } // e.g., "my-company: GITHUB_COMPANY_TOKEN not set" // e.g., "PR Review: GITHUB_TOKEN not set" process.exit(1);}hasTokenForOrg()
Section titled “hasTokenForOrg()”Quick check if a valid (non-empty) token is available for an organization.
hasTokenForOrg(org: string): booleanhasTokenForRepo()
Section titled “hasTokenForRepo()”Quick check if a valid token is available for a repository.
hasTokenForRepo(repoUrl: string): booleanSubprocess Helpers
Section titled “Subprocess Helpers”getEnvForRepo()
Section titled “getEnvForRepo()”Create an environment variables object for child processes targeting a specific repository. Sets both GH_TOKEN and GITHUB_TOKEN.
getEnvForRepo(repoUrl: string): Record<string, string>import { spawnSync } from 'node:child_process';import { getEnvForRepo } from '@jbcom/agentic';
const proc = spawnSync('gh', ['pr', 'list'], { env: { ...process.env, ...getEnvForRepo('my-company/my-repo') },});// Uses GITHUB_COMPANY_TOKEN for GH_TOKEN and GITHUB_TOKENgetEnvForPRReview()
Section titled “getEnvForPRReview()”Create environment variables for PR review operations using the PR review token.
getEnvForPRReview(): Record<string, string>const proc = spawnSync('gh', ['pr', 'review', '42', '--approve'], { env: { ...process.env, ...getEnvForPRReview() },});// Uses the PR review token identityDebugging
Section titled “Debugging”getTokenSummary()
Section titled “getTokenSummary()”Get a summary of all configured tokens and their availability. Useful for diagnostic output.
getTokenSummary(): Record<string, { envVar: string; available: boolean; configured: boolean;}>import { getTokenSummary } from '@jbcom/agentic';
const summary = getTokenSummary();for (const [name, info] of Object.entries(summary)) { const status = info.available ? 'OK' : 'MISSING'; console.log(`${name}: ${info.envVar} [${status}]`);}// my-company: GITHUB_COMPANY_TOKEN [OK]// partner-org: PARTNER_GH_PAT [MISSING]// _default: GITHUB_TOKEN [OK]// _pr_review: GITHUB_BOT_TOKEN [OK]Environment Variable Patterns
Section titled “Environment Variable Patterns”Automatic Organization Loading
Section titled “Automatic Organization Loading”On module initialization, the token system scans process.env for variables matching the pattern AGENTIC_ORG_<NAME>_TOKEN and automatically registers them.
# Pattern: AGENTIC_ORG_<UPPERCASE_NAME>_TOKEN=<TOKEN_ENV_VAR_NAME>export AGENTIC_ORG_MYCOMPANY_TOKEN=GITHUB_MYCOMPANY_TOKENexport AGENTIC_ORG_PARTNER_TOKEN=PARTNER_GH_PATThe <NAME> portion is converted to lowercase and underscores become hyphens:
AGENTIC_ORG_MYCOMPANY_TOKENregisters orgmycompanyAGENTIC_ORG_MY_COMPANY_TOKENregisters orgmy-company
Override Variables
Section titled “Override Variables”# Override the default token env varexport AGENTIC_DEFAULT_TOKEN=GITHUB_TOKEN
# Override the PR review token env varexport AGENTIC_PR_REVIEW_TOKEN=GITHUB_BOT_TOKENConfig File Format
Section titled “Config File Format”Token configuration in agentic.config.json:
{ "tokens": { "organizations": { "my-company": { "name": "my-company", "tokenEnvVar": "GITHUB_COMPANY_TOKEN", "defaultBranch": "main", "isEnterprise": false }, "open-source": { "name": "open-source", "tokenEnvVar": "GITHUB_OSS_TOKEN" } }, "defaultTokenEnvVar": "GITHUB_TOKEN", "prReviewTokenEnvVar": "GITHUB_BOT_TOKEN" }}Token Resolution Flow
Section titled “Token Resolution Flow”Repository: "https://github.com/my-company/my-repo" | v +-------------------------------+ | extractOrg() -> "my-company" | +---------------+---------------+ | +-------+-------+ | | Configured Not Found | | v v +---------------+ +-------------------+ | Return value | | Return value | | of configured | | of default | | tokenEnvVar | | tokenEnvVar | +---------------+ +-------------------+ | | v v GITHUB_COMPANY_TOKEN GITHUB_TOKENUsage with Fleet
Section titled “Usage with Fleet”The Fleet class automatically uses token management for all GitHub operations:
import { Fleet, addOrganization } from '@jbcom/agentic';
// Configure organizationsaddOrganization({ name: 'my-company', tokenEnvVar: 'GITHUB_COMPANY_TOKEN',});
const fleet = new Fleet();
// Fleet uses GITHUB_COMPANY_TOKEN automatically for this repoawait fleet.spawn({ repository: 'https://github.com/my-company/my-repo', task: 'Fix the authentication bug', target: { autoCreatePr: true },});CLI Commands
Section titled “CLI Commands”# Show token status for all configured organizationsagentic tokens status
# Validate that all configured tokens are setagentic tokens validate
# Get the token env var for a specific repoagentic tokens for-repo my-org/my-repoBest Practices
Section titled “Best Practices”Use Fine-Grained Tokens
Section titled “Use Fine-Grained Tokens”Create separate GitHub Personal Access Tokens with minimal scopes:
# Personal repos -- full accessexport GITHUB_TOKEN="ghp_personal..."
# Work repos -- only repo scopeexport GITHUB_WORK_TOKEN="ghp_work..."
# Open source contributions -- only public reposexport GITHUB_OSS_TOKEN="ghp_oss..."Use a Bot Account for PR Reviews
Section titled “Use a Bot Account for PR Reviews”Configure a dedicated bot identity so all automated PR reviews appear consistently:
{ "tokens": { "prReviewTokenEnvVar": "GITHUB_BOT_TOKEN" }}Validate on Startup
Section titled “Validate on Startup”Check token availability early to fail fast:
import { validateTokens } from '@jbcom/agentic';
const result = validateTokens();if (!result.success) { console.error('Missing tokens:', result.data); process.exit(1);}Never Hardcode Tokens
Section titled “Never Hardcode Tokens”// Bad -- hardcoded tokenconst token = 'ghp_xxx...';
// Good -- resolved from configurationconst token = getTokenForRepo('my-org/my-repo');Related Pages
Section titled “Related Pages”- Configuration API — Full config schema reference
- Fleet API Reference — Fleet management
- Getting Started: Configuration — Setup guide