Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): host-scope, bound, and provider-defer the GH_TOKEN probe
[._.]/ Adam Eivy5510b2eb9ddf
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 4d5f344072..f284ce2a72 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -264,6 +264,21 @@ export function isOllamaClaudeProvider(provider, command = provider?.command) {return provider?.ollamaBacked === true && isClaudeCommand(command);}+/**+ * True when a provider explicitly configures its own GitHub credential+ * (`GH_TOKEN` or `GITHUB_TOKEN`) in `envVars`. Agent-spawn paths that would+ * otherwise inject a repo-owner-pinned `GH_TOKEN` skip that injection when this+ * returns true, so the provider's explicit credential wins — `gh` prefers+ * `GH_TOKEN` over `GITHUB_TOKEN`, so an injected `GH_TOKEN` would silently+ * shadow a provider's configured `GITHUB_TOKEN` otherwise.+ * @param {{envVars?: Record<string,unknown>}} provider+ * @returns {boolean}+ */+export function providerSuppliesGithubToken(provider) {+ const env = provider?.envVars;+ return !!env && ('GH_TOKEN' in env || 'GITHUB_TOKEN' in env);+}+/*** Lean-context flags for local-model Claude Code sessions:* - `--bare` — skip hooks, plugin sync, auto-memory, and CLAUDE.mddiff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex d3d54d5790..83aeb08233 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -19,10 +19,28 @@ import {isOllamaClaudeProvider,applyLeanClaudeArgs,LEAN_CLAUDE_ARGS,- commandBasename+ commandBasename,+ providerSuppliesGithubToken} from './providerModels.js';describe('providerModels', () => {+ describe('providerSuppliesGithubToken', () => {+ it('is true when envVars carries GH_TOKEN or GITHUB_TOKEN (even if empty-string)', () => {+ expect(providerSuppliesGithubToken({ envVars: { GH_TOKEN: 'x' } })).toBe(true);+ expect(providerSuppliesGithubToken({ envVars: { GITHUB_TOKEN: 'x' } })).toBe(true);+ // `in` check, not truthiness: an intentionally-empty override still counts.+ expect(providerSuppliesGithubToken({ envVars: { GH_TOKEN: '' } })).toBe(true);+ });++ it('is false when the provider has no github credential in envVars', () => {+ expect(providerSuppliesGithubToken({ envVars: { OTHER: 'x' } })).toBe(false);+ expect(providerSuppliesGithubToken({ envVars: {} })).toBe(false);+ expect(providerSuppliesGithubToken({})).toBe(false);+ expect(providerSuppliesGithubToken(null)).toBe(false);+ expect(providerSuppliesGithubToken(undefined)).toBe(false);+ });+ });+describe('commandBasename', () => {it('strips directory prefixes, lowercases, and drops a .exe suffix', () => {expect(commandBasename('grok')).toBe('grok');diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex b81d66d2f9..c9970dd349 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -27,7 +27,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';-import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';+import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { resolveForgeTokenEnv } from './git.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';@@ -435,10 +435,13 @@ export async function spawnDirectly({// ~/.claude/settings.json Bedrock config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE,// etc., present even if PM2 lacks them) and the repo-owner-pinned GH_TOKEN// (so the agent's own `gh pr create` auths as the right account — see- // resolveForgeTokenEnv; `{}` when there's no owner match).+ // resolveForgeTokenEnv; `{}` when there's no owner match). Skip the token probe+ // entirely when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so its+ // explicit credential wins (gh prefers GH_TOKEN, so injecting one would shadow a+ // provider GITHUB_TOKEN).const [claudeSettingsEnv, forgeTokenEnv] = await Promise.all([isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),- resolveForgeTokenEnv(cwd),+ providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(cwd),]);// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT withdiff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 7d7c26b6b3..28f5315a5d 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -521,6 +521,25 @@ describe('stream error containment', () => {await spawnPromise.catch(() => {});});+ it('skips the owner-token probe when the provider supplies its own GITHUB_TOKEN', async () => {+ const { resolveForgeTokenEnv } = await import('./git.js');+ vi.mocked(resolveForgeTokenEnv).mockClear();+ vi.mocked(spawn).mockClear();++ const args = { ...minimalArgs, provider: { ...minimalArgs.provider, envVars: { GITHUB_TOKEN: 'ghp_provider_bot' } } };+ const spawnPromise = spawnDirectly(args);+ await new Promise((r) => setTimeout(r, 10));++ // gh prefers GH_TOKEN over GITHUB_TOKEN — injecting the owner GH_TOKEN would+ // shadow the provider's explicit bot credential, so the probe is skipped.+ expect(resolveForgeTokenEnv).not.toHaveBeenCalled();+ const env = vi.mocked(spawn).mock.calls.at(-1)[2].env;+ expect(env.GITHUB_TOKEN).toBe('ghp_provider_bot');++ fakeProcess.emit('close', 0);+ await spawnPromise.catch(() => {});+ });+describe('initialization timeout — 3-second phase transition', () => {it('calls updateAgent with working phase after 3s when agent has not started working', async () => {const { activeAgents } = await import('./agentState.js');diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 82b0015548..4170337294 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -22,7 +22,7 @@ import { determineLane, acquire, release } from './executionLanes.js';import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';-import { isOllamaClaudeProvider, isClaudeCommand } from '../lib/providerModels.js';+import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';@@ -632,10 +632,12 @@ export async function spawnViaRunner(agentId, task, opts) {// Two independent async env lookups, resolved together: Claude's// ~/.claude/settings.json Bedrock config, and the repo-owner-pinned GH_TOKEN// (so the runner-spawned agent's own `gh pr create` auths as the right- // account — see resolveForgeTokenEnv; `{}` when there's no owner match).+ // account — see resolveForgeTokenEnv; `{}` when there's no owner match). Skip+ // the token probe when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so+ // its explicit credential wins.const [claudeSettingsEnv, forgeTokenEnv] = await Promise.all([isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),- resolveForgeTokenEnv(workspacePath),+ providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(workspacePath),]);// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with thediff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 3d2de8bf5e..98c4295db0 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -20,7 +20,7 @@ import { PATHS } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';import * as git from './git.js';import { shellQuote } from '../lib/shellQuote.js';-import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';+import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { isAntigravityCommand } from '../lib/antigravity.js';@@ -804,7 +804,11 @@ export async function spawnTuiAgent({// Repo-owner-pinned GH_TOKEN for the agent's own `gh pr create` (see// resolveForgeTokenEnv). Resolved here since createAgentTuiSession is sync.- const forgeTokenEnv = await git.resolveForgeTokenEnv(cwd);+ // Skip when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so its explicit+ // credential wins.+ const forgeTokenEnv = providerSuppliesGithubToken(provider)+ ? {}+ : await git.resolveForgeTokenEnv(cwd);const session = createAgentTuiSession({agentId,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 2557c61dc8..8567e6472e 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -446,20 +446,20 @@ describe('spawnTuiAgent runtime', () => {await completeDone;});- it('lets an explicit provider GH_TOKEN override win over the owner-pinned token (spread order matches the CLI/runner paths)', async () => {+ it('skips the owner-token probe when the provider supplies its own GITHUB_TOKEN so the explicit credential wins', async () => {let resolveComplete;const completeDone = new Promise((r) => { resolveComplete = r; });vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });- vi.mocked(gitService.resolveForgeTokenEnv).mockResolvedValueOnce({ GH_TOKEN: 'ghp_owner_pinned' });- runSpawn({ provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', envVars: { GH_TOKEN: 'ghp_provider_override' } } });+ runSpawn({ provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', envVars: { GITHUB_TOKEN: 'ghp_provider_bot' } } });await flushMicrotasks();- // provider.envVars.GH_TOKEN must win — forgeTokenEnv is spread first.- expect(shellService.createShellSession).toHaveBeenCalledWith(- null,- expect.objectContaining({ env: expect.objectContaining({ GH_TOKEN: 'ghp_provider_override' }) }),- );+ // gh prefers GH_TOKEN over GITHUB_TOKEN, so injecting an owner GH_TOKEN would+ // shadow the provider's bot credential — the probe must be skipped entirely.+ expect(gitService.resolveForgeTokenEnv).not.toHaveBeenCalled();+ const env = vi.mocked(shellService.createShellSession).mock.calls[0][1].env;+ expect(env.GITHUB_TOKEN).toBe('ghp_provider_bot');+ expect(env.GH_TOKEN).toBeUndefined();await capturedOnExit({ exitCode: 0, killed: false });await completeDone;diff --git a/server/services/git.js b/server/services/git.jsindex ac6a93b915..3a3170c18b 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -364,22 +364,41 @@ export async function resolveForgeForRepo(dir) {* `hosts.yml` active user; (2) even when inherited, the ambient token can be* the wrong account in a multi-login setup ("must be a collaborator").*- * Returns `{ GH_TOKEN }` only when a repo-owner-matched account and token were- * found; otherwise `{}` so the child keeps whatever gh auth it would have used.- * Best-effort: never throws, so a spawn is never blocked by remote/auth probes.+ * Returns `{ GH_TOKEN }` only when a github.com repo-owner-matched account and+ * token were found; otherwise `{}` so the child keeps whatever gh auth it would+ * have used. Best-effort and bounded: never throws, and a stalled `gh` probe+ * times out to `{}` so a spawn is never blocked.* @param {string} dir - Repo (or worktree) root+ * @param {object} [opts]+ * @param {number} [opts.timeoutMs=10000] - Cap on the git+gh probe before giving up* @returns {Promise<{ GH_TOKEN?: string }>}*/-export async function resolveForgeTokenEnv(dir) {- const resolved = await resolveForgeForRepo(dir).catch(() => null);- // resolveForgeForRepo returns a NEW env object (`{ ...process.env, GH_TOKEN }`)- // ONLY when it successfully minted an owner-matched token; every other branch- // (unparseable remote, glab, no account match, token fetch failed) returns the- // ambient `process.env` by reference. So an identity check on the env object is- // the precise "a pinned token was minted" signal — keying on `account` alone- // would wrongly re-emit the ambient GH_TOKEN when the account matched but the- // token fetch failed (that branch keeps `account` set but env === process.env).- const token = resolved && resolved.env !== process.env ? resolved.env.GH_TOKEN : null;+export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {+ // resolveForgeForRepo shells out to git + `gh auth status` + `gh auth token`+ // with no internal timeout, and this runs on the critical agent-spawn path.+ // Race it against a timer so a stalled gh (network/keychain hang) can't leave+ // a task marked in-progress forever with no child process — a timeout falls+ // through to `{}` (ambient auth) exactly like any other miss. The timer is+ // unref'd so it never itself keeps the event loop alive.+ let timer;+ const resolved = await Promise.race([+ resolveForgeForRepo(dir).catch(() => null),+ new Promise((r) => { timer = setTimeout(() => r(null), timeoutMs); timer.unref?.(); }),+ ]);+ clearTimeout(timer);+ // Overlay a token ONLY for a genuinely-minted github.com credential. Two gates:+ // - host === 'github.com': detectForgeCli defaults an unrecognized/GHES host to+ // `gh`, and resolveForgeForRepo's account/token probes are hardcoded to+ // `-h github.com`. Without this gate, a Bitbucket/GHES repo whose owner segment+ // happens to match a local github.com login would get that github.com token+ // injected into every agent — the wrong (or a leaked) credential.+ // - env !== process.env: resolveForgeForRepo returns a NEW env object+ // (`{ ...process.env, GH_TOKEN }`) ONLY on a successful mint; every other+ // branch (no match, token fetch failed) returns the ambient `process.env` by+ // reference. Keying on `account` alone would re-emit the ambient GH_TOKEN when+ // the account matched but the token fetch failed.+ const minted = resolved && resolved.host === 'github.com' && resolved.env !== process.env;+ const token = minted ? resolved.env.GH_TOKEN : null;return token ? { GH_TOKEN: token } : {};}