Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Detect an ACP agent by its existing sign-in, not just PATH (#3769)
mike-inkeepa326bab7a4cb
diff --git a/.changeset/acp-harness-credential-signal.md b/.changeset/acp-harness-credential-signal.mdnew file mode 100644index 000000000..ad42316e8--- /dev/null+++ b/.changeset/acp-harness-credential-signal.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++OpenKnowledge now suggests Codex in the agent picker when you are already signed into Codex Desktop, even if you have never installed the `codex` command line tool. Previously the only thing that could put an agent in the "In app" list unprompted was finding its CLI on your PATH, which meant a Codex Desktop user saw no Codex row despite having everything needed to use it — the adapter brings its own runtime, and Codex Desktop and the CLI share the same sign-in. The catalog now reports an existing sign-in as a second, independent signal alongside the PATH check, and either one is enough.++The signal only ever adds an agent to the list, never removes one. Not finding a sign-in means nothing, since Codex can keep credentials in a system keyring with nothing on disk to find; and finding one is not proof the session still works, since an expired sign-in stays on disk until you run `codex logout`. So a suggested agent may still ask you to sign in. Agents you have turned on yourself are unaffected, as always.diff --git a/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx b/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsxindex 99fb602d3..af6be004f 100644--- a/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx+++ b/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx@@ -41,7 +41,7 @@ const catalog: AgentCatalog = {source: 'registry',supported: true,featured: true,- harness: { cli: 'claude', availability: 'unknown' },+ harness: { cli: 'claude', availability: 'unknown', credentials: 'unknown' },},{id: 'opencode-acp',@@ -50,7 +50,7 @@ const catalog: AgentCatalog = {source: 'registry',supported: false,featured: false,- harness: { cli: 'opencode', availability: 'not-found' },+ harness: { cli: 'opencode', availability: 'not-found', credentials: 'unknown' },},// Not harness-mapped and not enabled → collapsed behind "Show more".{@@ -73,7 +73,7 @@ const catalog: AgentCatalog = {featured: false,description: 'ACP wrapper for Cursor',license: 'Apache-2.0',- harness: { cli: 'cursor', availability: 'not-found' },+ harness: { cli: 'cursor', availability: 'not-found', credentials: 'unknown' },},// Supported + harness present → detected → defaults on.{@@ -84,7 +84,7 @@ const catalog: AgentCatalog = {supported: true,featured: false,description: 'ACP wrapper for Gemini',- harness: { cli: 'pi', availability: 'present' },+ harness: { cli: 'pi', availability: 'present', credentials: 'unknown' },},],stale: false,@@ -221,6 +221,25 @@ describe('ConfigureAgentsSection', () => {expect(notFound.getAttribute('data-disabled')).toBeNull();});+ test('an existing sign-in detects an agent whose CLI is not on PATH', async () => {+ // The Codex Desktop case. The adapter brings its own runtime, so a harness+ // the PATH probe ruled out is still ready to run when its credential+ // namespace already holds a sign-in: the row defaults on and stays above+ // the fold, exactly as a PATH-present one does.+ const cursor = catalog.agents.find((a) => a.id === 'cursor');+ const restore = cursor?.harness?.credentials;+ if (cursor?.harness) cursor.harness.credentials = 'present';+ try {+ renderSection();+ const row = await screen.findByTestId('configure-agents-in-app-registry:cursor');+ expect(row.getAttribute('aria-checked')).toBe('true');+ // Above the fold without expanding — no `expandInApp()` above.+ expect(screen.getByText('ACP wrapper for Cursor')).toBeTruthy();+ } finally {+ if (cursor?.harness && restore) cursor.harness.credentials = restore;+ }+ });+test('collapses to agents the probe has not ruled out, with a Show more toggle for the rest', async () => {renderSection();// Default view = harness-mapped agents the probe did NOT rule out: Gemini@@ -307,6 +326,35 @@ describe('ConfigureAgentsSection', () => {}});+ test('a credentials-only agent lifts the In app group above one with nothing', async () => {+ // The group tier scores on `isHarnessDetected`, not PATH presence alone.+ // Scoring it on PATH would sink In app below External apps for the Codex+ // Desktop user this signal exists to serve: every harness ruled out by the+ // probe, yet one of them signed in and ready to run.+ const patched = catalog.agents.filter((a) => a.harness !== undefined);+ const restore = patched.map((a) => ({ a, ...a.harness }));+ for (const a of patched) {+ if (a.harness) a.harness.availability = 'not-found';+ }+ const cursor = catalog.agents.find((a) => a.id === 'cursor');+ if (cursor?.harness) cursor.harness.credentials = 'present';+ try {+ renderSection();+ // Cursor is the only agent left above the fold, and it got there on the+ // credential signal alone — waiting on it proves the catalog landed and+ // that the row-level arm fired, before scoring the group order.+ await screen.findByText('ACP wrapper for Cursor');+ expect(groupOrder()).toEqual(['In app', 'External apps']);+ } finally {+ for (const r of restore) {+ if (r.a.harness && r.availability && r.credentials) {+ r.a.harness.availability = r.availability;+ r.a.harness.credentials = r.credentials;+ }+ }+ }+ });+test('groups keep their declared order when both have something present', async () => {renderSection();await screen.findByText('Claude Agent');diff --git a/packages/app/src/components/settings/ConfigureAgentsSection.tsx b/packages/app/src/components/settings/ConfigureAgentsSection.tsxindex ae2f31000..cfeb9bf44 100644--- a/packages/app/src/components/settings/ConfigureAgentsSection.tsx+++ b/packages/app/src/components/settings/ConfigureAgentsSection.tsx@@ -36,7 +36,12 @@ import {isInAppAgentEnabled,isTerminalCliEnabled,} from '@/lib/acp/agent-visibility';-import { type CatalogAgent, fetchAgentCatalog, harnessPresenceRank } from '@/lib/acp/catalog';+import {+ type CatalogAgent,+ fetchAgentCatalog,+ harnessPresenceRank,+ isHarnessDetected,+} from '@/lib/acp/catalog';import {desktopEnabledKey,inAppEnabledKey,@@ -220,7 +225,7 @@ export function ConfigureAgentsSection(): ReactNode {// use, so this list and every launcher agree.const inAppChecked = (agent: CatalogAgent): boolean => {const isRegistered = registeredKeys.has(`${agent.source}:${agent.id}`);- const isDetected = agent.supported === true && agent.harness?.availability === 'present';+ const isDetected = isHarnessDetected(agent);return isInAppAgentEnabled(overrides,agent.source,@@ -267,9 +272,15 @@ export function ConfigureAgentsSection(): ReactNode {const terminalHiddenCount =terminalFoldable && !searching ? terminalClis.length - terminalPrimary.length : 0;- // Group ordering: a group holding something present sorts above one that does- // not. Two tiers, matching the rule this file already applies per row rather- // than inventing a third for ordering.+ // Group ordering: a group holding something this host can use sorts above one+ // that does not. Two tiers, matching the rule this file already applies per+ // row rather than inventing a third for ordering. Each group scores on its+ // own notion of usable, and the three deliberately differ.+ //+ // In app is DETECTED, not merely PATH-present: `isHarnessDetected` also+ // counts an existing sign-in, so a harness whose CLI was never installed+ // still lifts the group. Scoring this one on PATH alone would sink In app+ // below External apps for exactly the user that signal exists to serve.//// Terminal is FAIL-OPEN (`cliPresent`, `!== false`): a terminal row only opens// a shell we own, so a probe that has not answered holds its place rather than@@ -282,8 +293,7 @@ export function ConfigureAgentsSection(): ReactNode {// In app is held up entirely while its catalog is in flight — the rows arrive// asynchronously, and scoring the group on a not-yet-populated list would sort// it to the bottom and visibly jump it back on every open of this tab.- const inAppHasPresent =- !catalogReady || inAppAgents.some((a) => a.harness?.availability === 'present');+ const inAppHasDetected = !catalogReady || inAppAgents.some(isHarnessDetected);const terminalHasPresent = terminalClis.some(cliPresent);const desktopHasPresent = desktopTargets.some((tg) => states[tg.id]?.installed === true);@@ -454,7 +464,7 @@ export function ConfigureAgentsSection(): ReactNode {// Each group carries its own `key`, so React reconciles them across a reorder// instead of remounting whichever section happens to land in a given slot.const groups = [- { node: inAppGroup, hasPresent: inAppHasPresent },+ { node: inAppGroup, hasPresent: inAppHasDetected },{ node: terminalGroup, hasPresent: terminalHasPresent },{ node: desktopGroup, hasPresent: desktopHasPresent },]diff --git a/packages/app/src/lib/acp/catalog.test.ts b/packages/app/src/lib/acp/catalog.test.tsindex ef874bf4c..4671137a3 100644--- a/packages/app/src/lib/acp/catalog.test.ts+++ b/packages/app/src/lib/acp/catalog.test.ts@@ -1,10 +1,21 @@import { describe, expect, test } from 'vitest';-import { type CatalogAgent, detectedHarnessAgents } from './catalog';+import { type CatalogAgent, detectedHarnessAgents, harnessPresenceRank } from './catalog';++type HarnessCli = NonNullable<CatalogAgent['harness']>['cli'];++/** Mirrors the server's agent-id → CLI mapping so fixtures name a real pair. */+const HARNESS_CLI: Record<string, HarnessCli> = {+ 'claude-acp': 'claude',+ 'codex-acp': 'codex',+ cursor: 'cursor',+ opencode: 'opencode',+};function agent(id: string,availability: 'present' | 'not-found' | 'unknown',supported = true,+ credentials: 'present' | 'unknown' = 'unknown',): CatalogAgent {return {id,@@ -13,7 +24,7 @@ function agent(source: 'registry',supported,featured: true,- harness: { cli: id === 'cursor' ? 'cursor' : 'claude', availability },+ harness: { cli: HARNESS_CLI[id] ?? 'claude', availability, credentials },};}@@ -28,4 +39,28 @@ describe('detectedHarnessAgents', () => {]).map((entry) => entry.id),).toEqual(['claude-acp', 'cursor']);});++ test('existing credentials detect an agent whose CLI is not on PATH', () => {+ // The Codex Desktop case: the adapter brings its own runtime and the login+ // is already in the shared store, so a missing `codex` binary must not hide+ // an agent that would start and authenticate on the first try.+ expect(+ detectedHarnessAgents([agent('codex-acp', 'not-found', true, 'present')]).map((e) => e.id),+ ).toEqual(['codex-acp']);+ });++ test('credentials do not rescue an agent with no launchable distribution', () => {+ expect(detectedHarnessAgents([agent('codex-acp', 'not-found', false, 'present')])).toEqual([]);+ });+});++describe('harnessPresenceRank', () => {+ test('credentials keep a PATH-absent agent out of the sunk tier', () => {+ expect(harnessPresenceRank(agent('codex-acp', 'not-found', true, 'present'))).toBe(0);+ expect(harnessPresenceRank(agent('codex-acp', 'not-found'))).toBe(1);+ });++ test('a pending probe still ranks with present', () => {+ expect(harnessPresenceRank(agent('claude-acp', 'unknown'))).toBe(0);+ });});diff --git a/packages/app/src/lib/acp/catalog.ts b/packages/app/src/lib/acp/catalog.tsindex acf33bd98..d20e7c783 100644--- a/packages/app/src/lib/acp/catalog.ts+++ b/packages/app/src/lib/acp/catalog.ts@@ -23,10 +23,32 @@ export interface CatalogAgent {harness?: {cli: 'claude' | 'codex' | 'cursor' | 'gemini' | 'opencode' | 'pi';availability: 'present' | 'not-found' | 'unknown';+ /** A sign-in already exists in the namespace the adapter reads. */+ credentials: 'present' | 'unknown';};}-/** Registry agents whose corresponding first-party CLI is on the server host. */+/**+ * Whether this host looks ready to run the agent — the single predicate behind+ * both the launcher menus and the Settings list, which must never disagree.+ *+ * Either signal alone is enough, and both are weak. The CLI on PATH means the+ * user works with this harness, not that they are signed in; a credential+ * record means they signed in here at some point, not that the token still+ * works. Neither is a launchability test either: adapters bring their own+ * runtime (npx, or a binary OK downloads itself), so a host with neither+ * signal can still run the agent perfectly well once the user turns it on.+ *+ * Being wrong in the offering direction costs a sign-in prompt; being wrong in+ * the hiding direction costs an agent the user never learns they can use. This+ * only decides what to offer unprompted, so it leans toward offering.+ */+export function isHarnessDetected(agent: CatalogAgent): boolean {+ if (!agent.supported) return false;+ return agent.harness?.availability === 'present' || agent.harness?.credentials === 'present';+}++/** Registry agents this host looks ready to run, best-known first. */export function detectedHarnessAgents(agents: readonly CatalogAgent[]): CatalogAgent[] {const priority = ['claude-acp', 'codex-acp', 'cursor', 'opencode'];// `indexOf` returns -1 for an id not in the priority list; map that to the end@@ -35,25 +57,24 @@ export function detectedHarnessAgents(agents: readonly CatalogAgent[]): CatalogAconst i = priority.indexOf(id);return i === -1 ? priority.length : i;};- return agents- .filter((agent) => agent.supported && agent.harness?.availability === 'present')- .sort((a, b) => rank(a.id) - rank(b.id));+ return agents.filter(isHarnessDetected).sort((a, b) => rank(a.id) - rank(b.id));}/**- * Sort rank by what the harness probe found: 0 for an agent whose CLI is on the- * host or whose probe has not landed yet, 1 for one the probe positively- * reported absent.+ * Sort rank by what the harness probes found: 0 for an agent whose CLI is on the+ * host, whose credentials are already there, or whose probe has not landed yet;+ * 1 for one the PATH probe positively reported absent with nothing else to go on.** `unknown` ranks WITH `present`, not with `not-found` — a probe that has not* answered is pending, not a negative result, and burying an agent the user* actually has behind a fold because a PATH check was slow is the worse failure.* Same three-valued discipline the Desktop rows already apply to their own probe.*- * Distinct from `detectedHarnessAgents`, which filters strictly to `present`- * because its callers need a positive answer; this one only orders.+ * Distinct from `isHarnessDetected`, which needs a positive answer; this one+ * only orders, so it keeps the pending case up top.*/export function harnessPresenceRank(agent: CatalogAgent): number {+ if (agent.harness?.credentials === 'present') return 0;return agent.harness?.availability === 'not-found' ? 1 : 0;}diff --git a/packages/server/src/acp/harness-availability.test.ts b/packages/server/src/acp/harness-availability.test.tsindex 4088d4bc2..7a325461e 100644--- a/packages/server/src/acp/harness-availability.test.ts+++ b/packages/server/src/acp/harness-availability.test.ts@@ -36,6 +36,22 @@ afterEach(() => {shims = [];});+/**+ * The real credential probe reads the host filesystem, so every availability+ * assertion below pins it — otherwise a dev machine with `~/.codex/auth.json`+ * and CI disagree about the same expected object.+ */+const noCredentials = () => 'unknown' as const;++/** Availability-only view, for the assertions that predate the second signal. */+function availabilityOf(+ result: Awaited<ReturnType<ReturnType<typeof createAcpHarnessAvailabilityProbe>>>,+): Record<string, HarnessAvailability> {+ return Object.fromEntries(+ Object.entries(result).map(([cli, signals]) => [cli, signals.availability]),+ );+}+describe('ACP harness availability', () => {test('maps the registry-backed harness agents to their real CLI ids', () => {expect(ACP_AGENT_HARNESS_CLIS).toEqual({@@ -64,13 +80,14 @@ describe('ACP harness availability', () => {calls.push(cli);return availability[cli] ?? 'unknown';},+ credentials: noCredentials,now: () => timestamp,ttlMs: 50,});const first = probe();expect(probe()).toBe(first);- expect(await first).toEqual(availability);+ expect(availabilityOf(await first)).toEqual(availability);expect(calls).toEqual(['claude', 'codex', 'cursor', 'gemini', 'opencode', 'pi']);timestamp = 151;@@ -91,8 +108,9 @@ describe('ACP harness availability', () => {}const probe = createAcpHarnessAvailabilityProbe({resolveLoginShellPath: async () => shimDir,+ credentials: noCredentials,});- expect(await probe()).toEqual({+ expect(availabilityOf(await probe())).toEqual({claude: 'present',codex: 'present',cursor: 'present',@@ -111,11 +129,12 @@ describe('ACP harness availability', () => {consulted += 1;return emptyDir;},+ credentials: noCredentials,});const result = await probe();// Whatever this machine happens to have installed, every CLI that missed// the base PATH must have been given the login-shell second chance.- const missing = Object.values(result).filter((v) => v === 'not-found').length;+ const missing = Object.values(result).filter((v) => v.availability === 'not-found').length;expect(consulted).toBe(missing);});@@ -125,9 +144,67 @@ describe('ACP harness availability', () => {if (cli === 'codex') throw new Error('probe failed');return 'not-found';},+ credentials: noCredentials,+ });++ expect((await probe()).codex?.availability).toBe('unknown');+ });+});++describe('harness credentials (a second positive signal, never a negative one)', () => {+ test('an existing sign-in is reported even when the PATH probe rejects', async () => {+ // The two signals are independent: a signed-in harness whose preflight blew+ // up is exactly the case the credential probe exists to rescue, so a+ // rejected availability probe must not also swallow the credential answer.+ const probe = createAcpHarnessAvailabilityProbe({+ probe: async () => {+ throw new Error('probe failed');+ },+ credentials: (cli) => (cli === 'codex' ? 'present' : 'unknown'),+ });++ expect((await probe()).codex).toEqual({ availability: 'unknown', credentials: 'present' });+ });++ test('a throwing credential probe degrades that harness without poisoning the cache', async () => {+ // The result promise is cached for the whole TTL and rejections are never+ // evicted, so an unguarded throw here would answer every catalog request+ // for the next minute with a 502 instead of a degraded row.+ const probe = createAcpHarnessAvailabilityProbe({+ probe: async () => 'not-found',+ credentials: (cli) => {+ if (cli === 'codex') throw new Error('credential probe exploded');+ return 'unknown';+ },});- expect((await probe()).codex).toBe('unknown');+ await expect(probe()).resolves.toMatchObject({+ codex: { availability: 'not-found', credentials: 'unknown' },+ });+ });++ test('reads the Codex sign-in from the CODEX_HOME the adapter would inherit', async () => {+ // Pins the shared-store contract the Codex Desktop case rests on: Desktop+ // and CLI both land on `$CODEX_HOME/auth.json`, and the probe has to read+ // the same env the launch chain passes through `mergedEnv`.+ const codexHome = mkdtempSync(join(tmpdir(), 'harness-creds-test-'));+ shims.push(codexHome);+ const previous = process.env.CODEX_HOME;+ process.env.CODEX_HOME = codexHome;+ try {+ const before = await createAcpHarnessAvailabilityProbe({ probe: async () => 'not-found' })();+ expect(before.codex?.credentials).toBe('unknown');++ writeFileSync(join(codexHome, 'auth.json'), '{}');+ const after = await createAcpHarnessAvailabilityProbe({ probe: async () => 'not-found' })();+ expect(after.codex?.credentials).toBe('present');+ // Only Codex is mapped — Claude Desktop keeps an app-owned session that+ // never reaches Claude Code's namespace, so no `~/.claude` inference.+ expect(after.claude?.credentials).toBe('unknown');+ } finally {+ if (previous === undefined) delete process.env.CODEX_HOME;+ else process.env.CODEX_HOME = previous;+ }});});@@ -150,10 +227,11 @@ describe('unverified verdicts (a probe failure is not absence, and must leave aconst probe = createAcpHarnessAvailabilityProbe({preflight: firstChanceAlwaysMisses,resolveLoginShellPath: async () => null,+ credentials: noCredentials,});const result = await probe();- for (const [cli, verdict] of Object.entries(result)) {- expect({ cli, verdict }).toEqual({ cli, verdict: 'unknown' });+ for (const [cli, signals] of Object.entries(result)) {+ expect({ cli, verdict: signals.availability }).toEqual({ cli, verdict: 'unknown' });}// Guard against a vacuous pass: every mapped harness got a verdict.expect(Object.keys(result)).toHaveLength(6);@@ -169,9 +247,10 @@ describe('unverified verdicts (a probe failure is not absence, and must leave aresolveLoginShellPath: async () => {throw captureFailure;},+ credentials: noCredentials,});const result = await probe();- for (const verdict of Object.values(result)) expect(verdict).toBe('unknown');+ for (const signals of Object.values(result)) expect(signals.availability).toBe('unknown');const records = [...acpLog.warn.mock.calls, ...acpLog.info.mock.calls];expect(records.length).toBeGreaterThan(0);expect(diff --git a/packages/server/src/acp/harness-availability.ts b/packages/server/src/acp/harness-availability.tsindex 5e0249dc4..f5ca48946 100644--- a/packages/server/src/acp/harness-availability.ts+++ b/packages/server/src/acp/harness-availability.ts@@ -5,8 +5,17 @@* things: a registry row may be runnable through npx while the corresponding* first-party CLI is absent. This probe is only a defaulting/presentation* signal. Launch resolution remains authoritative.+ *+ * Two independent signals per harness, deliberately kept apart rather than+ * collapsed into one verdict: whether the first-party CLI is on PATH, and+ * whether the credential namespace the adapter reads already holds a sign-in.+ * They answer different questions and a future logged-out card needs to tell+ * "no CLI here" apart from "CLI here but signed out".*/+import { existsSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';import type { TerminalCli } from '@inkeep/open-knowledge-core';import { getLogger } from '../logger.ts';import { AgentLaunchError, mergedEnv, preflightLaunch, withLoginShellPath } from './launch.ts';@@ -14,6 +23,33 @@ import { getSharedLoginShellPathProvider } from './login-shell-path.ts';export type HarnessAvailability = 'present' | 'not-found' | 'unknown';+/**+ * Whether the harness's credential namespace holds a sign-in RECORD. Not+ * whether that record still works.+ *+ * Weak evidence in both directions. Absence proves nothing: Codex supports+ * keyring and ephemeral stores where a signed-in user has no on-disk record at+ * all. Presence proves little more: `codex` deletes `auth.json` only on an+ * explicit user-invoked `codex logout`, so an expired, reused, or revoked+ * refresh token leaves the file sitting there, as does a CLI the user has+ * since uninstalled.+ *+ * The stale-record false positive is accepted knowingly. Parsing the file+ * would not buy much — the dominant lapse is an expired token, which no+ * on-disk check can see — and the two errors are not symmetric: a stale record+ * offers an agent that then asks the user to sign in, while the miss this+ * signal exists to fix hides a working agent entirely.+ *+ * Hence two-valued: the signal may only ever add an agent, never hide one. Do+ * not add an `'absent'` member and start gating on it.+ */+export type HarnessCredentials = 'present' | 'unknown';++interface HarnessSignals {+ readonly availability: HarnessAvailability;+ readonly credentials: HarnessCredentials;+}+/*** Harnesses this probe knows how to look for. A superset of `TerminalCli`:* Gemini has a first-party CLI and a registry ACP row but no docked-terminal@@ -44,8 +80,59 @@ const HARNESS_BINS: Readonly<Record<AcpHarnessCli, string>> = {hermes: 'hermes',};-export type AcpHarnessAvailability = Readonly<Partial<Record<AcpHarnessCli, HarnessAvailability>>>;+export type AcpHarnessAvailability = Readonly<Partial<Record<AcpHarnessCli, HarnessSignals>>>;++/**+ * Where each harness keeps the credential namespace its ACP adapter reads.+ *+ * Only Codex is mapped, and the asymmetry is the point. Codex Desktop and the+ * Codex CLI share `$CODEX_HOME/auth.json`, so someone who signed in through+ * Codex Desktop and never installed a `codex` binary has a working runtime+ * (the adapter brings its own) and, in the common case, a usable sign-in — and+ * the PATH probe alone would hide them. Claude Desktop holds an app-owned+ * session that never reaches Claude Code's namespace, so the same inference+ * does not hold there and adding a `~/.claude` entry here would assert+ * something we have no evidence for.+ *+ * Resolution reads `process.env` because `mergedEnv` hands the adapter this+ * same environment; probing a different `CODEX_HOME` than the adapter will use+ * would report on a namespace the agent cannot read.+ */+const HARNESS_CREDENTIAL_PATHS: Readonly<Partial<Record<AcpHarnessCli, () => string>>> = {+ codex: () => join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'auth.json'),+};+function detectHarnessCredentials(cli: AcpHarnessCli): HarnessCredentials {+ const resolvePath = HARNESS_CREDENTIAL_PATHS[cli];+ if (resolvePath === undefined) return 'unknown';+ let credentialPath: string | undefined;+ try {+ credentialPath = resolvePath();+ return existsSync(credentialPath) ? 'present' : 'unknown';+ } catch (err) {+ // `credentialPath` stays undefined when `resolvePath()` itself threw, so+ // logging it separates "CODEX_HOME pointed somewhere unreadable" from "we+ // never resolved a path at all" (a container with no resolvable home).+ getLogger('acp-harness').warn(+ { cli, credentialPath, err },+ 'harness credential probe failed; treating as unknown',+ );+ return 'unknown';+ }+}++/**+ * How long a probe result stays fresh. Sized for the PATH signal, which only+ * changes when someone installs or removes a binary.+ *+ * The credential signal is far more volatile — signing in to Codex Desktop is+ * a moment-to-moment act — and it inherits this TTL underneath a five-minute+ * React Query `staleTime` on `['acp-catalog']`, with no user-facing refresh+ * outside the error state. So someone can sign in, come straight back, and+ * still not be offered the agent for a few minutes. Accepted deliberately:+ * before this signal existed they were never offered it at all, and the row+ * appears on its own shortly after.+ */const DEFAULT_TTL_MS = 60_000;async function detectHarness(@@ -120,6 +207,8 @@ export function createAcpHarnessAvailabilityProbe(resolveLoginShellPath?: () => Promise<string | null>;/** Test seam: the launch preflight is otherwise environment-dependent. */preflight?: typeof preflightLaunch;+ /** Test seam: the credential probe is otherwise filesystem-dependent. */+ credentials?: (cli: AcpHarnessCli) => HarnessCredentials;} = {},): () => Promise<AcpHarnessAvailability> {const resolveLoginShellPath =@@ -127,6 +216,7 @@ export function createAcpHarnessAvailabilityProbe(const preflight = opts.preflight ?? preflightLaunch;const probe =opts.probe ?? ((cli: AcpHarnessCli) => detectHarness(cli, resolveLoginShellPath, preflight));+ const credentials = opts.credentials ?? detectHarnessCredentials;const now = opts.now ?? Date.now;const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;const harnesses = [...new Set(Object.values(ACP_AGENT_HARNESS_CLIS))].filter(@@ -139,14 +229,34 @@ export function createAcpHarnessAvailabilityProbe(if (cached !== null && cached.expiresAt > timestamp) return cached.value;const value = Promise.all(harnesses.map(async (cli) => {+ // Runs outside the try below because the two signals are independent:+ // a signed-in harness whose preflight blew up is exactly the case this+ // signal exists to rescue.+ //+ // The guard covers the injectable `opts.credentials` seam only —+ // `detectHarnessCredentials` is total, so in production this cannot+ // fire. It stays because the blast radius of a throwing test double is+ // out of proportion to the mistake: it would reject the whole+ // `Promise.all`, and a rejected result is cached for the full TTL+ // rather than evicted, so every catalog request for the next minute+ // fails too.+ let creds: HarnessCredentials = 'unknown';+ try {+ creds = credentials(cli);+ } catch (err) {+ getLogger('acp-harness').warn(+ { cli, err },+ 'harness credential probe threw; treating as unknown',+ );+ }try {- return [cli, await probe(cli)] as const;+ return [cli, { availability: await probe(cli), credentials: creds }] as const;} catch (err) {getLogger('acp-harness').warn({ cli, err },'harness availability probe rejected; availability unknown',);- return [cli, 'unknown'] as const;+ return [cli, { availability: 'unknown', credentials: creds }] as const;}}),).then((entries) => Object.fromEntries(entries) as AcpHarnessAvailability);diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 08c8f6fd1..71b252c4b 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -8437,6 +8437,8 @@ export function createApiExtension(.object({cli: z.enum(['claude', 'codex', 'cursor', 'gemini', 'opencode', 'pi']),availability: z.enum(['present', 'not-found', 'unknown']),+ /** No `absent` member — see `HarnessCredentials`. */+ credentials: z.enum(['present', 'unknown']),}).optional(),});@@ -8482,7 +8484,8 @@ export function createApiExtension(? {harness: {cli: harnessCli,- availability: harnessAvailability[harnessCli] ?? 'unknown',+ availability: harnessAvailability[harnessCli]?.availability ?? 'unknown',+ credentials: harnessAvailability[harnessCli]?.credentials ?? 'unknown',},}: {}),