The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-05 i1335: #3098 (#3109)
0xken15bb2e53510df4
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex fbd8b5fe1..4bbdf7a31 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -1,3 +1,4 @@+import { RELAY_REASONS } from './relayHealth.js'import { execFileSync } from 'node:child_process'import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'@@ -436,6 +437,68 @@ describe('contributed machine executor', () => {expect(readings(f)[0]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: null }])})+ // Task #3106: Kay's Mac read Claude as signed in for its Team account while the owner's relay refused every request, as+ // the readiness looked only for the relay's file. Routing kept sending work there, and each start lost its task.+ it('reads a Team account\'s relayed engine as signed out while the relay does not answer, says why, and ready again within a minute', async () => {+ const f = fixture({}, () => null, () => true)+ withEngines(f)+ let health: { ok: true } | { ok: false; reason: string } = { ok: false, reason: RELAY_REASONS.down }+ const relayHealth = vi.fn(async () => health)+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth } as never)+ await machine.tick()+ expect(readings(f)[0]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true, signedIn: null }])+ health = { ok: true }+ f.advance(); await machine.tick()+ // Within the minute the relay's answer is kept for: still read as it was.+ expect(readings(f)[1]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true, signedIn: null }])+ f.step(60_000); await machine.tick()+ expect(readings(f).at(-1)!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: true }, { engine: 'codex', installed: true, signedIn: null }])+ // The engines themselves were probed once: only the relay is asked again.+ expect(probes(f)).toHaveLength(1)+ expect(relayHealth).toHaveBeenCalledTimes(2)+ })++ // Security review 2 of #3098: the probe asks Claude's path, so an owner sign-in it cannot read is Claude's alone. A Mac+ // whose owner has only ChatGPT kept getting Codex work before, and must still.+ it('reads only Claude signed out when the owner\'s Claude sign-in cannot be read, Codex still on the relay', async () => {+ const f = fixture({}, () => null, () => true)+ const usage = f.request.getMockImplementation()!+ f.request.mockImplementation(async (type, ...rest) => type === 'engines_probe'+ ? { engines: [{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true, signedIn: false }] } : usage(type, ...rest as []))+ const relayHealth = vi.fn(async () => ({ ok: false as const, reason: RELAY_REASONS.ownerSignIn, claudeOnly: true as const }))+ await new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth } as never).tick()+ expect(readings(f)[0]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true, signedIn: true }])+ })++ // Each probe has the owner's daemon read the owner's Keychain item: while macOS refuses it, it may ask on the owner's screen.+ it('asks again only five minutes after the owner\'s Claude sign-in could not be read', async () => {+ const f = fixture({}, () => null, () => true)+ withEngines(f)+ const relayHealth = vi.fn(async () => ({ ok: false as const, reason: RELAY_REASONS.ownerSignIn, claudeOnly: true as const }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth } as never)+ await machine.tick()+ f.step(4 * 60_000); await machine.tick()+ expect(relayHealth).toHaveBeenCalledOnce()+ f.step(60_000); await machine.tick()+ expect(relayHealth).toHaveBeenCalledTimes(2)+ })++ it('reads a probe that failed outright as a relay that does not answer', async () => {+ const f = fixture({}, () => null, () => true)+ withEngines(f)+ const relayHealth = vi.fn(async () => { throw new Error('unexpected') })+ await new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth } as never).tick()+ expect(readings(f)[0]!.readiness?.engines).toEqual([{ engine: 'claude', installed: true, signedIn: false }, { engine: 'codex', installed: true, signedIn: null }])+ })++ it('never asks the relay on a machine without one', async () => {+ const f = fixture()+ withEngines(f)+ const relayHealth = vi.fn(async () => ({ ok: true as const }))+ await new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth } as never).tick()+ expect(relayHealth).not.toHaveBeenCalled()+ })+it('reads an engine the probe calls not installed as unknown, since a timed-out shell probe says the same (review of #1743)', async () => {const f = fixture()const usage = f.request.getMockImplementation()!@@ -2603,6 +2666,22 @@ describe('the allowance a machine reports', () => {expect(last(f).quotaReasons).toEqual({ codex: "This account runs on its owner's subscription; its allowance is read on the owner's machine." })})+ it("says why a Harness Team account cannot use its owner's subscription when the owner's relay does not answer", async () => {+ const f = fixture({}, () => null, () => true)+ f.request.mockImplementation(answer({ outcome: 'signedOut' }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth: async () => ({ ok: false, reason: RELAY_REASONS.refused }) } as never)+ await machine.tick()+ expect(last(f).quotaReasons).toEqual({ codex: RELAY_REASONS.refused })+ })++ it("keeps Codex's reason when only the owner's Claude sign-in cannot be read", async () => {+ const f = fixture({}, () => null, () => true)+ f.request.mockImplementation(answer({ outcome: 'signedOut' }))+ const machine = new ContributedMachines(f.core, 'host', { ...f.deps, relayHealth: async () => ({ ok: false, reason: RELAY_REASONS.ownerSignIn, claudeOnly: true }) } as never)+ await machine.tick()+ expect(last(f).quotaReasons).toEqual({ codex: "This account runs on its owner's subscription; its allowance is read on the owner's machine." })+ })+it('drops the reasons for a backend that refuses them, keeping the allowance, and offers them again ten minutes later', async () => {const f = fixture()f.request.mockImplementation(limited)diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex f6f591c76..3b8a2eb31 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -22,6 +22,7 @@ import { projectsRoot } from '../lib/projectFolder.js'import { worktreeFolderName } from '../lib/agentNames.js'import { teamPrivacyObserver } from '../team/observer.js'import { teamRelayed } from '../team/relay.js'+import { RELAY_REASONS, teamRelayHealth, type RelayHealth } from './relayHealth.js'import type { PrivacyObservation } from '../team/privacy.js'import { repositoryKey } from './route.js'import { cleanupClosed } from './cleanupCloses.js'@@ -152,6 +153,8 @@ export interface MachineDeps {/** In the Harness Team account: whether its engines can spend the owner's subscription through the owner's relay* (team/relay.ts), so one it has not signed in itself is ready all the same. */relayed?: () => boolean+ /** Whether that relay answers, and why not (relayHealth.ts); null when there is no grant to ask. */+ relayHealth?: () => Promise<RelayHealth | null>/** The Claude and Codex profile folders this machine offers ([listClaudeProfiles], [listCodexProfiles]). */claudeProfiles?: (machineId: string) => Array<{ id: string; path: string; reportLabel: string; offered: boolean; default?: true }>codexProfiles?: () => Array<{ path: string; offered?: boolean }>@@ -279,6 +282,8 @@ export class ContributedMachines {/** Whether each engine is installed and signed in, and until when that stands: one probe starts login shells and reads* the engines' accounts, so it runs every [READINESS_MS] (a failed one again after [READINESS_RETRY_MS]). */private engineRead: { value: ReadyEngine[] | null; until: number } | null = null+ /** The owner's relay's last answer, asked again once it is [RELAY_HEALTH_MS] old (task #3106). */+ private relayRead: { value: RelayHealth | null; until: number } | null = null/** The account reader's last answer, when it was read and until when it stands ([USAGE_FRESH_MS] and the rest). */private usageRead: { value: Record<string, unknown>; at: number; until: number } | null = null/** Per engine, its last readable allowance windows and when they were read, kept [USAGE_KEEP_MS] through failed reads. */@@ -296,7 +301,33 @@ export class ContributedMachines {private readonly checkoutReading = new Set<string>()private async engineReadiness(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }): Promise<ReadyEngine[] | null> {const now = this.deps.now()- if (this.engineRead && now < this.engineRead.until) return this.engineRead.value+ // Ready on the relay only while it answers (task #3106: Kay's Mac read signed in while the relay refused every request).+ // Asked on its own minute, apart from the engines' ten.+ const health = await this.relayHealthNow()+ const own = this.engineRead && now < this.engineRead.until ? this.engineRead.value : await this.ownEngines(local, now)+ return own && own.map(e => ({ ...e,+ signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn || this.relayServes(e.engine, health) : e.signedIn }))+ }+ /** Whether this Team account's [engine] may spend its owner's subscription now: the relay's grant is there, and the relay+ * answers it, or cannot be asked (no grant to ask with, as before). */+ private relayServes(engine: string, health: RelayHealth | null): boolean {+ if (!(this.deps.relayed ?? teamRelayed)()) return false+ return !health || health.ok || (health.claudeOnly === true && engine !== 'claude')+ }+ /** The relay's answer, at most [RELAY_HEALTH_MS] old; null on a machine without a relay grant. */+ private async relayHealthNow(): Promise<RelayHealth | null> {+ if (!(this.deps.relayed ?? teamRelayed)()) return null+ const now = this.deps.now()+ if (this.relayRead && now < this.relayRead.until) return this.relayRead.value+ // A probe that failed outright is a relay that does not answer (review 1 of #3098: it read as answering).+ const value = await (this.deps.relayHealth ?? teamRelayHealth)().catch((): RelayHealth => ({ ok: false, reason: RELAY_REASONS.down }))+ // An owner sign-in the owner's daemon could not read is asked about less often: each probe has it read the owner's+ // Keychain item, and while macOS refuses that it may ask on the owner's screen (security reviews of #3098).+ this.relayRead = { value, until: now + (value && !value.ok && value.claudeOnly ? RELAY_SIGN_IN_RETRY_MS : RELAY_HEALTH_MS) }+ return value+ }+ /** The engines' own installs and sign-ins, probed again once [READINESS_MS] old. */+ private async ownEngines(local: { request: (type: string, payload: Record<string, unknown>, timeoutMs: number) => Promise<unknown> }, now: number): Promise<ReadyEngine[] | null> {const answer = await local.request('engines_probe', { engines: ['claude', 'codex'], accounts: true }, 20_000).catch(() => null)const engines = object(answer).engines// An engine that says nothing of its sign-in (an older daemon, an engine not installed) is unknown, never signed out.@@ -304,10 +335,9 @@ export class ContributedMachines {// such a machine fails its first start loudly instead (review of #1743).// A Harness Team account that has not signed an engine in spends its owner's subscription through the owner's relay// (team/relay.ts): the Lead routed nothing to it while it read as signed out (routeCommand.ts `unreadyPool`).- const relayed = (this.deps.relayed ?? teamRelayed)()const value = Array.isArray(engines) ? list(engines).filter(e => e.engine === 'claude' || e.engine === 'codex').map((e): ReadyEngine => ({ engine: String(e.engine), installed: e.installed === true ? true : null,- signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn || relayed : null })) : null+ signedIn: e.installed === true && typeof e.signedIn === 'boolean' ? e.signedIn : null })) : nullthis.engineRead = { value, until: now + (value ? READINESS_MS : READINESS_RETRY_MS) }return value}@@ -372,6 +402,9 @@ export class ContributedMachines {if (list(read.value.providers).find(p => p.provider === engine)?.outcome === 'signedOut') this.goodQuota.delete(engine)const kept = this.goodQuota.get(engine)if (kept && this.deps.now() - kept.at <= USAGE_KEEP_MS) return { engine, known: true, windows: kept.windows }+ // A relay that does not answer says why, in place of where the allowance is read (task #3106).+ const relay = this.relayRead?.value ?? null+ if (relay && !relay.ok && !this.relayServes(engine, relay) && (this.deps.relayed ?? teamRelayed)()) return { engine, known: false, windows: [], reason: relay.reason }return { engine, known: false, windows: [], reason: quotaUnknownReason(read.value, engine, (this.deps.relayed ?? teamRelayed)()) ?? undefined }}/** The last readiness of [root]'s checkouts, reading them again beside the pass once it is [READINESS_MS] old. Null@@ -1265,6 +1298,10 @@ export class ContributedMachines {* probe that failed is tried again. */const READINESS_MS = 10 * 60_000const READINESS_RETRY_MS = 60_000+/** How long the owner's relay's answer stands: a relay back after its owner's restart reads ready again within this. */+const RELAY_HEALTH_MS = 60_000+/** How long an owner Claude sign-in the relay could not read stands before it is asked about again. */+const RELAY_SIGN_IN_RETRY_MS = 5 * 60_000/** How long an allowance reading stands. 2026-10-29: Anthropic answered 5 reads in a row, then refused them for 5 minutes* (HTTP 429, retry-after 300); read on every 15-second report, Claude's allowance showed as unknown. */const USAGE_FRESH_MS = 3 * 60_000diff --git a/cli/src/superTabs/relayHealth.spec.ts b/cli/src/superTabs/relayHealth.spec.tsnew file mode 100644index 000000000..36675c68b--- /dev/null+++ b/cli/src/superTabs/relayHealth.spec.ts@@ -0,0 +1,86 @@+/**+ * Whether the owner's relay answers a Harness Team account, and why not, in words its owner can act on (task #3106).+ */+import { createServer } from 'node:http'+import type { AddressInfo } from 'node:net'+import { describe, expect, it, onTestFinished } from 'vitest'+import { startSubscriptionRelay } from '../lib/subscriptionRelay.js'+import { TEAM_RELAY_GUEST } from '../team/relay.js'+import { probeRelay, RELAY_REASONS } from './relayHealth.js'++/** Anthropic's own error body for [status] (https://docs.anthropic.com/en/api/errors). */+const vendorError = (status: number) => JSON.stringify({ type: 'error', error: { type: ({ 401: 'authentication_error', 403: 'permission_error', 429: 'rate_limit_error', 529: 'overloaded_error' } as Record<number, string>)[status] ?? 'api_error', message: 'fixture' } })+async function relay(owner: { read: () => Promise<unknown>; refresh: () => Promise<null> }, status = 200) {+ const upstream = createServer((req, res) => { res.writeHead(req.url === '/v1/models' ? status : 404); res.end(status === 200 ? '{"data":[]}' : vendorError(status)) })+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve))+ onTestFinished(() => { upstream.closeAllConnections(); upstream.close() })+ const started = await startSubscriptionRelay({ owner: owner as never, upstream: { claude: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}` } })+ onTestFinished(() => started.close())+ return { url: started.url, token: started.mintToken(TEAM_RELAY_GUEST) }+}+const signedIn = { read: async () => ({ provider: 'claude', accessToken: 'owner-fixture', expiresAt: null, accountId: null }), refresh: async () => null }++describe('asking the owner\'s relay whether it answers', () => {+ it('answers with the owner signed in', async () => {+ expect(await probeRelay(await relay(signedIn))).toEqual({ ok: true })+ })++ it('says the owner\'s sign-in cannot be read, and what the owner does, when the relay finds none (Kay\'s Mac)', async () => {+ const grant = await relay({ read: async () => null, refresh: async () => null })+ // Claude's alone: the relay may still serve the owner's Codex.+ expect(await probeRelay(grant)).toEqual({ ok: false, reason: RELAY_REASONS.ownerSignIn, claudeOnly: true })+ expect(RELAY_REASONS.ownerSignIn).toMatch(/allow/)+ })++ it('reads Anthropic busy or failing as the relay answering, never as the owner\'s sign-in (security reviews of #3098)', async () => {+ for (const status of [503, 529, 429, 500]) expect(await probeRelay(await relay(signedIn, status)), String(status)).toEqual({ ok: true })+ })++ // Review 1 of #3098, second read: the relay answers its own 502 for anything that throws in it, such as an owner sign-in+ // it refreshed and could not save back to the Keychain: every Team request then fails while the reading said ready.+ it('reads the relay\'s own 502 as not answering, for both engines', async () => {+ const throwing = { read: async () => { throw new Error('keychain write refused') }, refresh: async () => null }+ expect(await probeRelay(await relay(throwing))).toEqual({ ok: false, reason: RELAY_REASONS.vendor })+ })++ it('reads at most a few kilobytes of an error body, however much a port\'s holder sends', async () => {+ const endless = createServer((_req, res) => {+ res.writeHead(500)+ const chunk = 'x'.repeat(64 * 1024)+ const pump = () => { while (res.write(chunk)) { /* fill */ } }+ res.on('drain', pump); pump()+ })+ await new Promise<void>(resolve => endless.listen(0, '127.0.0.1', resolve))+ onTestFinished(() => { endless.closeAllConnections(); endless.close() })+ const started = Date.now()+ expect(await probeRelay({ url: `http://127.0.0.1:${(endless.address() as AddressInfo).port}`, token: 'any-token-aaaaaaaaaaaaaaaa' })).toEqual({ ok: false, reason: RELAY_REASONS.down })+ expect(Date.now() - started).toBeLessThan(5_000)+ })++ // Review 2 of #3098, second read: once the owner's Harness has gone, whatever else listens on its port must not read ready.+ it('reads anything but a 2xx or Anthropic\'s own error as not answering: a redirect, a 404, an empty body', async () => {+ for (const [status, body] of [[302, ''], [404, ''], [500, 'oops'], [401, ''], [503, '{"type":"error"}']] as const) {+ const other = createServer((_req, res) => { res.writeHead(status, status === 302 ? { location: 'http://example.com/' } : {}); res.end(body) })+ await new Promise<void>(resolve => other.listen(0, '127.0.0.1', resolve))+ onTestFinished(() => { other.closeAllConnections(); other.close() })+ expect(await probeRelay({ url: `http://127.0.0.1:${(other.address() as AddressInfo).port}`, token: 'any-token-aaaaaaaaaaaaaaaa' }), String(status))+ .toEqual({ ok: false, reason: RELAY_REASONS.down })+ }+ })++ it('says Anthropic refused the owner\'s Claude sign-in, as Claude\'s alone, apart from the relay refusing this account', async () => {+ expect(await probeRelay(await relay(signedIn, 401))).toEqual({ ok: false, reason: RELAY_REASONS.claudeRefused, claudeOnly: true })+ })++ it('says the token was refused, and that nothing listens, without the token in either', async () => {+ const grant = await relay(signedIn)+ const refused = await probeRelay({ url: grant.url, token: 'not-the-token-aaaaaaaaaaaa' })+ expect(refused).toEqual({ ok: false, reason: RELAY_REASONS.refused })+ const free = createServer()+ await new Promise<void>(resolve => free.listen(0, '127.0.0.1', resolve))+ const port = (free.address() as AddressInfo).port+ await new Promise<void>(resolve => free.close(() => resolve()))+ expect(await probeRelay({ url: `http://127.0.0.1:${port}`, token: grant.token })).toEqual({ ok: false, reason: RELAY_REASONS.down })+ for (const reason of Object.values(RELAY_REASONS)) expect(reason).not.toContain(grant.token)+ })+})diff --git a/cli/src/superTabs/relayHealth.ts b/cli/src/superTabs/relayHealth.tsnew file mode 100644index 000000000..78243954f--- /dev/null+++ b/cli/src/superTabs/relayHealth.ts@@ -0,0 +1,112 @@+/**+ * Whether the owner's relay answers this Harness Team account, and why not (task #3106).+ *+ * A Team account's Claude and Codex read as signed in when the owner's daemon has left its relay grant (team/relay.ts+ * `teamRelayed`): the file alone was looked at. On Kay's Mac, 2026-11-05, the relay refused every request, as the owner's+ * daemon could not read the owner's Claude sign-in, while the reading still said signed in. Routing kept sending work+ * there and each start lost its task. So the reading asks the relay itself: a GET of Claude's model list with the grant,+ * which spends nothing, and which the relay forwards with the owner's sign-in. A relay that is gone, a token it refuses and+ * an owner sign-in it cannot read each read as not answering, with a reason the owner can act on.+ *+ * ⚠️ The token goes only to the address the owner's daemon published, which every launch already uses, and is never logged.+ */+import { readAuthSession } from '../lib/authSession.js'+import { readTeamConfig } from '../team/config.js'+import { readTeamRelay, type TeamRelayGrant } from '../team/relay.js'++/** Whether the relay answers. [claudeOnly]: what failed is the owner's Claude sign-in, which the relay may still serve Codex+ * without (security review 2 of #3098: a Mac whose owner has only ChatGPT kept getting Codex work before, and must still). */+export type RelayHealth = { ok: true } | { ok: false; reason: string; claudeOnly?: true }++/** What a Team account's reading says when its owner's relay does not answer: the quota reason, read by people. */+export const RELAY_REASONS = {+ /** The relay's own 503: the owner's daemon found no Claude sign-in it can read (lib/subscriptionRelay.ts). macOS may+ * refuse the Keychain item to Harness after an update, and the owner's own Claude Code keeps working. */+ ownerSignIn: "This account runs on its owner's subscription, and the owner's Harness can't read the owner's Claude sign-in: the owner needs to allow sign-in access (open Claude Code once, and choose Always Allow if macOS asks).",+ /** Anthropic's 401 or 403 through the relay, after the relay's own refresh: the owner's sign-in itself was refused. */+ claudeRefused: "This account runs on its owner's subscription, and Anthropic refused the owner's Claude sign-in: the owner signs in to Claude Code again.",+ refused: "This account runs on its owner's subscription, and the owner's relay did not accept its key: the owner's Harness hands out a new one when it next publishes its relay.",+ down: "This account runs on its owner's subscription, and the owner's Harness relay on this Mac does not answer: the owner's Harness is restarting or stopped.",+ /** The relay's own 502: anything that threw in it, Anthropic out of reach or an owner sign-in it refreshed and could not+ * save back (lib/ownerSubscriptions.ts). */+ vendor: "This account runs on its owner's subscription, and the owner's Harness can't reach Anthropic or save the owner's refreshed Claude sign-in.",+} as const++const PROBE_TIMEOUT_MS = 10_000+/** As much of an error body as is read: the relay's own fit in a few hundred bytes, and whatever holds the port may send+ * without end (review 1 of #3098). */+const BODY_BYTES = 4096++/** The first [BODY_BYTES] of [answer]'s body, the rest left unread. */+async function headOf(answer: Response): Promise<string> {+ const reader = answer.body?.getReader()+ if (!reader) return ''+ const chunks: Uint8Array[] = []+ let size = 0+ try {+ while (size < BODY_BYTES) {+ const { done, value } = await reader.read()+ if (done) break+ chunks.push(value)+ size += value.byteLength+ }+ } finally { await reader.cancel().catch(() => {}) }+ return Buffer.concat(chunks).subarray(0, BODY_BYTES).toString('utf8')+}+/** The relay's own refusals carry this; anything else came from the vendor through it (lib/subscriptionRelay.ts `fail`). */+const RELAY_OWN = '"harness_relay_error"'++/**+ * Asks the relay at [grant] for Claude's model list with its token. It answers on a 2xx, and on Anthropic's own error for+ * Anthropic busy, limiting or failing (a 503, 529 or 429 passed through), which is no fault of this account's: read as the+ * owner's sign-in, it told the owner to allow access that was there (security reviews of #3098). Everything else reads as+ * not answering, with why.+ */+export async function probeRelay(grant: TeamRelayGrant, fetchImpl: typeof fetch = fetch): Promise<RelayHealth> {+ let status: number, body = ''+ try {+ const answer = await fetchImpl(`${grant.url.replace(/\/$/, '')}/claude/v1/models`, {+ headers: { authorization: `Bearer ${grant.token}`, 'anthropic-version': '2023-06-01', accept: 'application/json' },+ redirect: 'manual', signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ })+ status = answer.status+ if (status >= 200 && status < 300) await answer.body?.cancel().catch(() => {})+ else body = await headOf(answer)+ } catch {+ return { ok: false, reason: RELAY_REASONS.down }+ }+ if (status >= 200 && status < 300) return { ok: true }+ if (body.includes(RELAY_OWN)) {+ if (status === 503) return { ok: false, reason: RELAY_REASONS.ownerSignIn, claudeOnly: true }+ if (status === 401) return { ok: false, reason: RELAY_REASONS.refused }+ // 502: anything that threw in the relay, for every request while it lasts (review 1 of #3098, second read).+ if (status === 502) return { ok: false, reason: RELAY_REASONS.vendor }+ return { ok: false, reason: `This account runs on its owner's subscription, and the owner's relay answered with an error (HTTP ${status}).` }+ }+ // Anthropic's own answer, passed through: its sign-in refused is Claude's alone; busy, limiting or failing is no fault of+ // this account's. Anything else (a redirect, a 404, an empty body) is not the owner's relay: whatever holds its port once+ // the owner's Harness has gone (review 2 of #3098, second read).+ const vendor = vendorErrorType(body)+ if (vendor === 'authentication_error' || vendor === 'permission_error') return { ok: false, reason: RELAY_REASONS.claudeRefused, claudeOnly: true }+ if (vendor) return { ok: true }+ return { ok: false, reason: RELAY_REASONS.down }+}++/** The error type in Anthropic's own error body (`{"type":"error","error":{"type":"overloaded_error",…}}`), or null. */+function vendorErrorType(body: string): string | null {+ try {+ const value = JSON.parse(body) as { type?: unknown; error?: { type?: unknown } }+ const type = value?.type === 'error' ? value.error?.type : undefined+ return typeof type === 'string' && /^[a-z_]{1,40}_error$/.test(type) ? type : null+ } catch { return null }+}++/** This Team account's: the grant read as each launch reads it (team/relay.ts `realTeamRelayLaunch`), then asked. Null with+ * no grant to ask, or on any other daemon. */+export async function teamRelayHealth(): Promise<RelayHealth | null> {+ // A spec never asks this Mac's own relay with its own Team sign-in. Production never has VITEST set.+ if (process.env.VITEST || readAuthSession()?.kind !== 'team') return null+ const config = readTeamConfig()+ const grant = config ? readTeamRelay(config) : null+ return grant ? probeRelay(grant) : null+}