The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(free-tier): browser challenge primitive for the anonymous token exchange
Robin Fernandes90ff655c81fe
diff --git a/apps/desktop/electron/challenge-window.test.ts b/apps/desktop/electron/challenge-window.test.tsnew file mode 100644index 00000000000..68858f61cd0--- /dev/null+++ b/apps/desktop/electron/challenge-window.test.ts@@ -0,0 +1,358 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'++import { test, vi } from 'vitest'++import {+ challengePhase,+ challengeUrlAllowed,+ challengeWindowOptions,+ createChallengeWindows,+ parseChallengeRequest+} from './challenge-window'++const PORTAL = 'https://portal.nousresearch.com'+const URL_OK = `${PORTAL}/challenge?code=abc`++function makeSession() {+ return Object.assign(new EventEmitter(), {+ setPermissionRequestHandler: vi.fn(),+ setPermissionCheckHandler: vi.fn()+ })+}++function makeHarness() {+ const windows: any[] = []+ const logs: string[] = []+ // Errors the next loadURL calls reject with, in order.+ const loadErrors: Error[] = []+ const session = makeSession()++ const createWindow = (options: any) => {+ const contents = Object.assign(new EventEmitter(), {+ setAudioMuted: vi.fn(),+ setWindowOpenHandler: vi.fn()+ })++ const win = Object.assign(new EventEmitter(), {+ options,+ webContents: contents,+ shown: false,+ destroyed: false,+ loaded: '' as string,+ show() {+ this.shown = true+ },+ focus() {},+ isDestroyed() {+ return this.destroyed+ },+ destroy() {+ this.destroyed = true+ },+ loadURL(url: string) {+ this.loaded = url+ const failure = loadErrors.shift()++ return failure ? Promise.reject(failure) : Promise.resolve()+ }+ })++ windows.push(win)++ return win as any+ }++ const clock = { now: 1_000_000 }++ const challenges = createChallengeWindows({+ isReady: () => true,+ getSession: () => session as any,+ resolvePortalBaseUrl: () => PORTAL,+ createWindow,+ rememberLog: message => logs.push(message),+ now: () => clock.now+ })++ const phase = (win: any, fragment: string) =>+ win.webContents.emit('did-navigate-in-page', {}, `${URL_OK}#${fragment}`)++ return { challenges, windows, logs, session, phase, clock, loadErrors }+}++test('only <portal>/challenge URLs are ever loadable', () => {+ assert.equal(challengeUrlAllowed(URL_OK, PORTAL), true)+ assert.equal(challengeUrlAllowed(`${PORTAL}/challenge/lab`, PORTAL), true)++ for (const url of [+ 'https://evil.example/challenge?code=abc',+ `${PORTAL}.evil.example/challenge`,+ `${PORTAL}/login`,+ `${PORTAL}/challenges`,+ 'http://portal.nousresearch.com/challenge',+ 'javascript:alert(1)',+ 'file:///etc/passwd',+ ''+ ]) {+ assert.equal(challengeUrlAllowed(url, PORTAL), false, url)+ }+})++test('the phase is the URL fragment, and nothing else is a phase', () => {+ assert.equal(challengePhase(`${URL_OK}#interactive`), 'interactive')+ assert.equal(challengePhase(`${URL_OK}#done`), 'done')+ assert.equal(challengePhase(URL_OK), null)+ assert.equal(challengePhase(`${URL_OK}#constructor`), null)+})++test('the window is hidden, hardened, isolated, and not throttled', () => {+ const session = { id: 'challenge' } as any+ const options = challengeWindowOptions(session)++ assert.equal(options.show, false)+ assert.equal(options.webPreferences?.session, session)+ assert.equal(options.webPreferences?.sandbox, true)+ assert.equal(options.webPreferences?.contextIsolation, true)+ assert.equal(options.webPreferences?.nodeIntegration, false)+ assert.equal(options.webPreferences?.backgroundThrottling, false)+})++test('a pass while hidden closes the window without ever showing it', async () => {+ const { challenges, windows, phase, session } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true })+ const [win] = windows++ assert.equal(win.loaded, URL_OK)+ assert.equal(win.options.show, false)+ phase(win, 'working')+ phase(win, 'done')++ assert.equal(await outcome, 'done')+ assert.equal(win.shown, false)+ assert.equal(win.destroyed, true)+ // Remote content gets no permissions and no popups.+ assert.equal(session.setPermissionRequestHandler.mock.calls.length, 1)+ assert.deepEqual(win.webContents.setWindowOpenHandler.mock.calls[0][0]({ url: 'https://x.test' }), {+ action: 'deny'+ })+})++test('the page asking for the human reveals the window, and a pass lingers briefly', async () => {+ vi.useFakeTimers()++ try {+ const { challenges, windows, phase } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true, expiresIn: 600 })+ const [win] = windows++ phase(win, 'interactive')+ assert.equal(win.shown, true)+ // The hidden deadline no longer applies: the human has the ticket's life.+ vi.advanceTimersByTime(120_000)+ assert.equal(win.destroyed, false)++ phase(win, 'done')+ assert.equal(win.destroyed, false)+ vi.advanceTimersByTime(2_000)+ assert.equal(await outcome, 'done')+ assert.equal(win.destroyed, true)+ } finally {+ vi.useRealTimers()+ }+})++test('an optional challenge is never revealed', async () => {+ const { challenges, windows, phase } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: false })++ phase(windows[0], 'interactive')+ assert.equal(await outcome, 'failed')+ assert.equal(windows[0].shown, false)+})++test('a hidden window that never finishes times out instead of living forever', async () => {+ vi.useFakeTimers()++ try {+ const { challenges, windows } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true })++ vi.advanceTimersByTime(91_000)+ assert.equal(await outcome, 'timeout')+ assert.equal(windows[0].destroyed, true)+ } finally {+ vi.useRealTimers()+ }+})++test('the page cannot take the window off the portal', () => {+ const { challenges, windows } = makeHarness()++ void challenges.run({ url: URL_OK, required: true })++ const navigate = (url: string) => {+ const event = { preventDefault: vi.fn() }++ windows[0].webContents.emit('will-navigate', event, url)++ return event.preventDefault.mock.calls.length+ }++ assert.equal(navigate(`${PORTAL}/challenge?code=abc#done`), 0)+ assert.equal(navigate('https://evil.example/'), 1)+ assert.equal(navigate('not a url'), 1)+})++test('a URL that is not a portal challenge opens nothing', async () => {+ const { challenges, windows } = makeHarness()++ assert.equal(await challenges.run({ url: 'https://evil.example/challenge', required: true }), 'refused')+ assert.equal(windows.length, 0)+})++test('two asks for the same challenge share one window', async () => {+ const { challenges, windows, phase } = makeHarness()+ const first = challenges.run({ url: URL_OK, required: true })+ const second = challenges.run({ url: URL_OK, required: true })++ assert.equal(windows.length, 1)+ phase(windows[0], 'done')+ assert.deepEqual(await Promise.all([first, second]), ['done', 'done'])+})++test('a settled challenge does not come back for the same ticket, until the memory lapses', async () => {+ const { challenges, windows, phase, clock } = makeHarness()+ const first = challenges.run({ url: URL_OK, required: true })++ phase(windows[0], 'interactive')+ windows[0].emit('closed')+ assert.equal(await first, 'closed')++ // The backend is still announcing the ticket; the window the user closed stays closed.+ assert.equal(await challenges.run({ url: URL_OK, required: true }), 'closed')+ assert.equal(windows.length, 1)++ clock.now += 11 * 60_000+ void challenges.run({ url: URL_OK, required: true })+ assert.equal(windows.length, 2)+})++test('a timed-out window may be tried again for the same ticket', async () => {+ vi.useFakeTimers()++ try {+ const { challenges, windows } = makeHarness()+ const first = challenges.run({ url: URL_OK, required: true })++ vi.advanceTimersByTime(91_000)+ assert.equal(await first, 'timeout')+ void challenges.run({ url: URL_OK, required: true })+ assert.equal(windows.length, 2)+ } finally {+ vi.useRealTimers()+ }+})++test('a server redirect off the portal is cancelled, and a foreign page cannot signal a phase', async () => {+ const { challenges, windows } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true })+ const [win] = windows+ const redirect = { preventDefault: vi.fn() }++ win.webContents.emit('will-redirect', redirect, 'https://evil.example/landing')+ assert.equal(redirect.preventDefault.mock.calls.length, 1)++ // A fragment on a foreign URL is not a phase: the window is not revealed.+ win.webContents.emit('did-navigate-in-page', {}, 'https://evil.example/x#interactive', true)+ assert.equal(win.shown, false)++ // A subframe cannot signal either.+ win.webContents.emit('did-navigate-in-page', {}, `${URL_OK}#interactive`, false)+ assert.equal(win.shown, false)++ // And a main-frame commit off the portal ends the run.+ win.webContents.emit('did-navigate', {}, 'https://evil.example/landing', 200)+ assert.equal(await outcome, 'failed')+ assert.equal(win.destroyed, true)+})++test('an HTTP error page ends the run instead of waiting out the deadline, and may be tried again', async () => {+ const { challenges, windows, phase } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true })++ windows[0].webContents.emit('did-navigate', {}, URL_OK, 503)+ assert.equal(await outcome, 'error')++ const retry = challenges.run({ url: URL_OK, required: true })+ assert.equal(windows.length, 2)+ phase(windows[1], 'done')+ assert.equal(await retry, 'done')+})++test('a superseded load is not a failed one, but a real load failure is', async () => {+ const { challenges, windows, phase, loadErrors } = makeHarness()++ loadErrors.push(Object.assign(new Error('ERR_ABORTED'), { errno: -3 }))+ const superseded = challenges.run({ url: `${URL_OK}&n=1`, required: true })++ await new Promise(resolve => setImmediate(resolve))+ assert.equal(windows[0].destroyed, false)+ phase(windows[0], 'done')+ assert.equal(await superseded, 'done')++ loadErrors.push(Object.assign(new Error('ERR_NAME_NOT_RESOLVED'), { errno: -105 }))+ assert.equal(await challenges.run({ url: `${URL_OK}&n=2`, required: true }), 'error')+})++test('an absurd ticket life cannot overflow the reveal timer', async () => {+ vi.useFakeTimers()++ try {+ const { challenges, windows, phase } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true, expiresIn: 1e12 })++ phase(windows[0], 'interactive')+ vi.advanceTimersByTime(60_000)+ // Still open a minute later: a 2^31 overflow would have closed it at once.+ assert.equal(windows[0].destroyed, false)+ vi.advanceTimersByTime(15 * 60_000)+ assert.equal(await outcome, 'timeout')+ } finally {+ vi.useRealTimers()+ }+})++test('the user closing a revealed window settles the run', async () => {+ const { challenges, windows, phase } = makeHarness()+ const outcome = challenges.run({ url: URL_OK, required: true })++ phase(windows[0], 'interactive')+ windows[0].emit('closed')+ assert.equal(await outcome, 'closed')+})++test('IPC payloads are parsed, not trusted', () => {+ assert.deepEqual(parseChallengeRequest({ url: URL_OK, required: false, expiresIn: 600 }), {+ url: URL_OK,+ required: false,+ expiresIn: 600+ })+ assert.deepEqual(parseChallengeRequest({ url: URL_OK }), { url: URL_OK, required: true, expiresIn: undefined })+ assert.equal(parseChallengeRequest({ url: 42 }), null)+ assert.equal(parseChallengeRequest(null), null)+ assert.equal(parseChallengeRequest({ url: 'x'.repeat(3000) }), null)+})++test('a fresh foreground attempt can reopen a closed window while status replay cannot', async () => {+ const { challenges, windows, phase } = makeHarness()+ const first = challenges.run({ url: URL_OK, required: true, attempt: 0 })++ windows[0].emit('closed')+ assert.equal(await first, 'closed')+ assert.equal(await challenges.run({ url: URL_OK, required: true, attempt: 0 }), 'closed')+ const retry = challenges.run({ url: URL_OK, required: true, attempt: 1 })++ assert.equal(windows.length, 2)+ phase(windows[1], 'done')+ assert.equal(await retry, 'done')+})diff --git a/apps/desktop/electron/challenge-window.ts b/apps/desktop/electron/challenge-window.tsnew file mode 100644index 00000000000..13116d8c806--- /dev/null+++ b/apps/desktop/electron/challenge-window.ts@@ -0,0 +1,367 @@+import type { BrowserWindow, BrowserWindowConstructorOptions, Session } from 'electron'++/**+ * The free tier's browser challenge, desktop half.+ *+ * The Nous account service can ask an anonymous install to clear a challenge+ * before it mints a token (`hermes_cli/anon_challenge.py`). The challenge is a+ * portal page; everything it does (bot detection, an in-browser proof of work,+ * an interactive fallback) belongs to the portal and changes without a Desktop+ * release. Desktop's whole job is this file: load that page in a HIDDEN+ * window, reveal the window only if the page asks for the human, and close it+ * when the page says it is finished. The backend polls the account service on+ * its own and re-mints; nothing here holds a credential.+ *+ * The page talks to us through its URL fragment, which we can read with no+ * bridge into the page:+ *+ * #working nothing to show; stay hidden+ * #interactive needs the human: reveal+ * #done passed: close+ * #failed ended without a pass: close (the backend's next mint says why)+ *+ * The page is remote content, so the window is hardened the way the link-title+ * window is: sandboxed, isolated, its own partition, no popups, no downloads,+ * no permissions. It is pinned to the portal origin three ways: navigations+ * and SERVER REDIRECTS off-origin are cancelled, a main-frame commit anywhere+ * else ends the run, and a phase is only ever read from a portal URL — a+ * foreign page must never be able to get this window revealed under a Hermes+ * title. Only `<portal>/challenge…` URLs are ever loaded — the URL arrives from the+ * network by way of the backend and the renderer, and "open this URL" must not+ * become "open any URL".+ */++export type ChallengePhase = 'working' | 'interactive' | 'done' | 'failed'++export type ChallengeOutcome = 'done' | 'failed' | 'closed' | 'timeout' | 'refused' | 'error'++export interface ChallengeRequest {+ url: string+ /** False for a challenge the service is only measuring with: never revealed. */+ required: boolean+ /** Seconds the ticket has left, as the service reported it. */+ expiresIn?: number+ /** A new foreground attempt may reopen a window the user closed. */+ attempt?: number+}++interface ChallengeWindowDependencies {+ isReady: () => boolean+ getSession: () => Session | null+ resolvePortalBaseUrl: () => string+ createWindow: (options: BrowserWindowConstructorOptions) => BrowserWindow+ rememberLog: (message: string) => void+ now?: () => number+}++export const CHALLENGE_PARTITION = 'persist:hermes-challenge'+export const CHALLENGE_PATH = '/challenge'++// While hidden nobody can see it hang: BotID plus a CPU-fallback proof of work+// fits well inside this. Once revealed, the human has the ticket's own life.+const HIDDEN_DEADLINE_MS = 90_000+const DEFAULT_TICKET_LIFE_MS = 10 * 60_000+// Long enough to read "You're all set" when the window was revealed.+const REVEALED_DONE_LINGER_MS = 1_500+const REVEALED_FAILED_LINGER_MS = 20_000+// `expiresIn` is network input that becomes a timer: a delay past 2^31 ms+// overflows setTimeout and fires at once.+const MIN_TICKET_LIFE_MS = 30_000+const MAX_TICKET_LIFE_MS = 15 * 60_000+// Chromium's ERR_ABORTED: the load was superseded (the page navigated while+// loading), not failed.+const ERR_ABORTED = -3++// How long a settled challenge URL is remembered. A window the user closed,+// or a page that already ruled, must not come back for the same ticket just+// because the backend is still announcing it (tickets live ten minutes).+const SETTLED_MEMORY_MS = 10 * 60_000+/** Outcomes after which the same URL is worth another window. */+const RETRYABLE_OUTCOMES: readonly ChallengeOutcome[] = ['timeout', 'error']++const PHASES: readonly ChallengePhase[] = ['working', 'interactive', 'done', 'failed']++export function challengeUrlAllowed(url: string, portalBaseUrl: string): boolean {+ try {+ const target = new URL(url)+ const portal = new URL(portalBaseUrl)++ return (+ (target.protocol === 'https:' || target.protocol === 'http:') &&+ target.origin === portal.origin &&+ (target.pathname === CHALLENGE_PATH || target.pathname.startsWith(`${CHALLENGE_PATH}/`))+ )+ } catch {+ return false+ }+}++export function challengePhase(url: string): ChallengePhase | null {+ try {+ const fragment = new URL(url).hash.replace(/^#/, '')++ return PHASES.find(phase => phase === fragment) ?? null+ } catch {+ return null+ }+}++export function challengeWindowOptions(session: Session): BrowserWindowConstructorOptions {+ return {+ width: 520,+ height: 720,+ show: false,+ title: 'Hermes — quick check',+ autoHideMenuBar: true,+ webPreferences: {+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ webSecurity: true,+ session,+ // An unshown window is not composited; without this its timers are+ // clamped and the page's work can stall while nobody is watching it.+ backgroundThrottling: false+ }+ }+}++/** Remote content in its own jar: no permissions, no downloads. Idempotent per session. */+const guardedSessions = new WeakSet<Session>()++export function guardChallengeSession(session: Session): void {+ if (guardedSessions.has(session)) {+ return+ }++ guardedSessions.add(session)+ session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false))+ session.setPermissionCheckHandler(() => false)+ session.on('will-download', event => event.preventDefault())+}++export function createChallengeWindows({+ isReady,+ getSession,+ resolvePortalBaseUrl,+ createWindow,+ rememberLog,+ now+}: ChallengeWindowDependencies) {+ // One window per challenge URL: the backend's event and the renderer's+ // status read can both ask for the same one.+ const running = new Map<string, Promise<ChallengeOutcome>>()+ const settledAt = new Map<string, { outcome: ChallengeOutcome; at: number }>()+ const clock = now ?? Date.now++ function drive(request: ChallengeRequest, session: Session): Promise<ChallengeOutcome> {+ const portalOrigin = new URL(resolvePortalBaseUrl()).origin++ return new Promise<ChallengeOutcome>(resolve => {+ let settled = false+ let revealed = false+ let win: BrowserWindow | null = null+ let deadline: ReturnType<typeof setTimeout> | null = null+ let linger: ReturnType<typeof setTimeout> | null = null++ const finish = (outcome: ChallengeOutcome) => {+ if (settled) {+ return+ }++ settled = true++ for (const timer of [deadline, linger]) {+ if (timer) {+ clearTimeout(timer)+ }+ }++ rememberLog(`[free-tier] challenge window ${outcome}${revealed ? ' (revealed)' : ''}`)+ // Settle first: a destroy() that throws must not leave the caller hanging.+ resolve(outcome)++ if (win && !win.isDestroyed()) {+ win.destroy()+ }+ }++ const armDeadline = (ms: number) => {+ if (deadline) {+ clearTimeout(deadline)+ }++ deadline = setTimeout(() => finish('timeout'), ms)+ }++ const finishAfter = (outcome: ChallengeOutcome, ms: number) => {+ if (!settled && !linger) {+ linger = setTimeout(() => finish(outcome), ms)+ }+ }++ const onPortal = (url: string) => {+ try {+ return new URL(url).origin === portalOrigin+ } catch {+ return false+ }+ }++ const onPhase = (url: string) => {+ // Only the portal speaks for the challenge.+ const phase = onPortal(url) ? challengePhase(url) : null++ if (settled || phase === null || phase === 'working') {+ return+ }++ if (phase === 'interactive') {+ // An optional challenge runs where nobody is looking; it has nothing+ // to ask a person for.+ if (!request.required) {+ finish('failed')++ return+ }++ if (!revealed && win && !win.isDestroyed()) {+ revealed = true+ armDeadline(ticketLifeMs(request.expiresIn))+ win.show()+ win.focus()+ }++ return+ }++ if (revealed) {+ finishAfter(phase, phase === 'done' ? REVEALED_DONE_LINGER_MS : REVEALED_FAILED_LINGER_MS)+ } else {+ finish(phase)+ }+ }++ try {+ guardChallengeSession(session)+ win = createWindow(challengeWindowOptions(session))+ } catch (error) {+ rememberLog(`[free-tier] challenge window could not be created: ${String(error)}`)+ finish('error')++ return+ }++ const contents = win.webContents++ contents.setAudioMuted(true)+ contents.setWindowOpenHandler(() => ({ action: 'deny' }))++ // The page may move within the portal (a fragment, a reload); it may not+ // take this window anywhere else — by script (`will-navigate`) or by a+ // server redirect (`will-redirect`, which `will-navigate` never sees).+ const stayOnPortal = (event: { preventDefault: () => void }, url: string) => {+ if (!onPortal(url)) {+ event.preventDefault()+ }+ }++ contents.on('will-navigate', stayOnPortal)+ contents.on('will-redirect', stayOnPortal)+ contents.on('did-navigate-in-page', (_event, url, isMainFrame) => {+ if (isMainFrame !== false) {+ onPhase(url)+ }+ })+ contents.on('did-navigate', (_event, url, httpResponseCode) => {+ // Belt and braces: a main-frame commit off the portal ends the run; an+ // HTTP error page is not going to signal anything, but is worth a retry.+ if (!onPortal(url)) {+ finish('failed')+ } else if (typeof httpResponseCode === 'number' && httpResponseCode >= 400) {+ finish('error')+ } else {+ onPhase(url)+ }+ })+ contents.on('render-process-gone', () => finish('error'))+ win.on('closed', () => finish('closed'))++ armDeadline(HIDDEN_DEADLINE_MS)+ win.loadURL(request.url).catch((error: { errno?: number }) => {+ if (error?.errno !== ERR_ABORTED) {+ finish('error')+ }+ })+ })+ }++ function run(request: ChallengeRequest): Promise<ChallengeOutcome> {+ const session = isReady() ? getSession() : null++ if (!session || !challengeUrlAllowed(request.url, resolvePortalBaseUrl())) {+ rememberLog('[free-tier] challenge window refused (not ready, or URL is not a portal challenge)')++ return Promise.resolve('refused')+ }++ const existing = running.get(request.url)++ if (existing) {+ return existing+ }++ const attemptKey = `${request.url}:${request.attempt ?? 0}`+ const before = settledAt.get(attemptKey)++ if (before && clock() - before.at < SETTLED_MEMORY_MS && !RETRYABLE_OUTCOMES.includes(before.outcome)) {+ return Promise.resolve(before.outcome)+ }++ const outcome = drive(request, session)+ .then(result => {+ settledAt.set(attemptKey, { outcome: result, at: clock() })++ for (const [key, entry] of settledAt) {+ if (clock() - entry.at >= SETTLED_MEMORY_MS) {+ settledAt.delete(key)+ }+ }++ return result+ })+ .finally(() => running.delete(request.url))++ running.set(request.url, outcome)++ return outcome+ }++ return { run }+}++function ticketLifeMs(expiresInSeconds: number | undefined): number {+ const asked = (expiresInSeconds ?? 0) * 1000 || DEFAULT_TICKET_LIFE_MS++ return Math.min(MAX_TICKET_LIFE_MS, Math.max(MIN_TICKET_LIFE_MS, asked))+}++/** IPC payloads are untrusted: accept only the documented shape. */+export function parseChallengeRequest(value: unknown): ChallengeRequest | null {+ if (typeof value !== 'object' || value === null) {+ return null+ }++ const { url, required, expiresIn, attempt } = value as Record<string, unknown>++ if (typeof url !== 'string' || url.length === 0 || url.length > 2048) {+ return null+ }++ return {+ url,+ required: required !== false,+ expiresIn: typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined,+ ...(typeof attempt === 'number' && Number.isSafeInteger(attempt) && attempt >= 0 ? { attempt } : {})+ }+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex d5f85952349..1cf7cf14489 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -448,6 +448,7 @@ import {} from './pool-spawn-coordinator'import { createPoolStopper } from './pool-stop'import { poolTouchKeys } from './pool-touch-scope'+import { CHALLENGE_PARTITION, createChallengeWindows, parseChallengeRequest } from './challenge-window'import { createPortalSession } from './portal-session'import {createKeepAwake,@@ -8168,6 +8169,17 @@ const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, orememberLog})+// The free tier's browser challenge (hermes_cli/anon_challenge.py): the portal+// page runs in a hidden window of its own partition, revealed only if it asks+// for the human. See electron/challenge-window.ts.+const freeTierChallengeWindows = createChallengeWindows({+ isReady: () => app.isReady(),+ getSession: () => session.fromPartition(CHALLENGE_PARTITION),+ resolvePortalBaseUrl,+ createWindow: options => new BrowserWindow(options),+ rememberLog+})+// Discover the hosted (Hermes Cloud) agents the signed-in user can see. Calls// the NAS trimmed-summary endpoint over the partition-bound net, so the portal// session cookie is attached automatically (no bearer needed — NAS accepts the@@ -18478,6 +18490,12 @@ ipcMain.on('hermes:devtools:disable-f12', (_event, on) => {}})+ipcMain.handle('hermes:freeTierChallenge:run', (_event, payload) => {+ const request = parseChallengeRequest(payload)++ return request ? freeTierChallengeWindows.run(request) : 'refused'+})+ipcMain.handle('hermes:openExternal', async (_event, url) => {const result = await openExternalUrl(url)diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 543ba6e353c..7ab1fbf1beb 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -410,6 +410,11 @@ contextBridge.exposeInMainWorld('hermesDesktop', {setPreviewGuestHidden: (webContentsId, hidden) =>ipcRenderer.send('hermes:preview-guest-hidden', { webContentsId, hidden: Boolean(hidden) }),openExternal: url => ipcRenderer.invoke('hermes:openExternal', url),+ freeTierChallenge: {+ // Load the account service's challenge page in a hidden window (revealed+ // only if the page asks for the human). Resolves with how it ended.+ run: request => ipcRenderer.invoke('hermes:freeTierChallenge:run', request)+ },mcpOauth: {// One-shot loopback listener for MCP OAuth against remote backends: bind// on this machine, hand redirectUri to mcp.servers.oauth.start, then waitdiff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.tsindex 06641ecb48f..5074f371a55 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts@@ -3,6 +3,8 @@ import type { HermesSkin } from '@hermes/shared/skin'import { invalidateContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'import { clearClarifyRequest } from '@/store/clarify'+import { runFreeTierChallenge } from '@/store/free-tier-challenge'+import { activeGatewayConnectionId, requestGatewayForAgent } from '@/store/gateway'import {notifyCronChanged,notifyPairingChanged,@@ -53,6 +55,21 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {return true}+ if (event.type === 'free_tier.challenge') {+ // The account service wants a browser challenge cleared before it mints+ // the free-tier token. The backend polls for the result on its own; this+ // only gets the page loaded (hidden). Any source's challenge is worth+ // running: it is the install's identity, not the focused session's.+ const connectionId = event.connectionId ?? activeGatewayConnectionId()+ const profile = event.profile ?? deps.activeGatewayProfile++ void runFreeTierChallenge(payload, result =>+ requestGatewayForAgent(connectionId, profile, 'free_tier.challenge_result', result)+ )++ return true+ }+if (event.type === 'skin.changed') {// A runtime skin switch (Hermes activating an authored skin, or `/skin`// on another surface). Only the active source+profile's change repaints.diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 6d56e770331..811c15fa1c5 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -413,6 +413,17 @@ declare global {setPreviewGuestHidden?: (webContentsId: number, hidden: boolean) => voidopenExternal: (url: string) => Promise<void>onExternalOpenFailed?: (callback: (payload: ExternalOpenFailedPayload) => void) => () => void+ /** The free tier's browser challenge (electron/challenge-window.ts): load+ * the account service's page in a hidden window, revealed only if the+ * page asks for the human. Resolves with how the window ended. */+ freeTierChallenge?: {+ run: (request: {+ url: string+ required: boolean+ expiresIn?: number+ attempt?: number+ }) => Promise<'done' | 'failed' | 'closed' | 'timeout' | 'refused' | 'error'>+ }/** One-shot loopback callback listener for MCP OAuth against remote* backends (electron/mcp-oauth-callback-ipc.ts): bind on THIS machine,* pass redirectUri as client_redirect_uri to mcp.servers.oauth.start,diff --git a/apps/desktop/src/store/free-tier-challenge.test.ts b/apps/desktop/src/store/free-tier-challenge.test.tsnew file mode 100644index 00000000000..296cc5caf29--- /dev/null+++ b/apps/desktop/src/store/free-tier-challenge.test.ts@@ -0,0 +1,89 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { runFreeTierChallenge } from './free-tier-challenge'++const challenge = {+ type: 'browser',+ url: 'https://portal.nousresearch.com/challenge?code=abc',+ required: true,+ expires_in: 600,+ message: 'A quick check first.'+}++function installBridge(run: (request: unknown) => Promise<string>) {+ ;(window as unknown as { hermesDesktop?: unknown }).hermesDesktop = { freeTierChallenge: { run } }+}++afterEach(() => {+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++describe('runFreeTierChallenge', () => {+ it('reports the matching attempt outcome without treating the host as an auth authority', async () => {+ const report = vi.fn().mockResolvedValue({ accepted: true })+ const run = vi.fn().mockResolvedValue('error')++ installBridge(run)+ await expect(runFreeTierChallenge({ ...challenge, attempt: 3 }, report)).resolves.toBe('error')+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ attempt: 3 }))+ expect(report).toHaveBeenCalledWith({ url: challenge.url, attempt: 3, outcome: 'error' })+ })+ it('hands a browser challenge to the main process', async () => {+ const run = vi.fn().mockResolvedValue('done')++ installBridge(run)++ await expect(runFreeTierChallenge(challenge)).resolves.toBe('done')+ expect(run).toHaveBeenCalledWith({ url: challenge.url, required: true, expiresIn: 600, attempt: 0 })+ })++ it('runs one window per URL while it is in flight, reports it once, then allows it again', async () => {+ let settle: (outcome: string) => void = () => {}+ const run = vi.fn().mockImplementation(() => new Promise<string>(resolve => (settle = resolve)))+ const report = vi.fn().mockResolvedValue({ accepted: true })++ installBridge(run)++ const first = runFreeTierChallenge(challenge, report)+ const second = runFreeTierChallenge(challenge, report)++ expect(run).toHaveBeenCalledTimes(1)+ settle('done')+ await expect(Promise.all([first, second])).resolves.toEqual(['done', 'done'])+ // The event and the status read both asked; the backend hears about it once.+ expect(report).toHaveBeenCalledTimes(1)++ void runFreeTierChallenge(challenge)+ expect(run).toHaveBeenCalledTimes(2)+ })++ it('a backend that rejects the report (older gateway, dropped socket) does not change the outcome', async () => {+ installBridge(vi.fn().mockResolvedValue('done'))+ const report = vi.fn().mockRejectedValue(new Error('Method not found'))++ await expect(runFreeTierChallenge({ ...challenge, url: `${challenge.url}5` }, report)).resolves.toBe('done')+ })++ it('passes an optional challenge through as not-required', async () => {+ const run = vi.fn().mockResolvedValue('failed')++ installBridge(run)+ await runFreeTierChallenge({ ...challenge, url: `${challenge.url}2`, required: false })+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ required: false }))+ })++ it('ignores anything that is not a browser challenge', () => {+ installBridge(vi.fn())+ expect(runFreeTierChallenge(undefined)).toBeNull()+ expect(runFreeTierChallenge(null)).toBeNull()+ expect(runFreeTierChallenge({ type: 'attestation', url: 'https://x.test' })).toBeNull()+ expect(runFreeTierChallenge({ type: 'browser' })).toBeNull()+ })++ it('reports unsupported when no shell can host the page, and an IPC failure as an error', async () => {+ await expect(runFreeTierChallenge({ ...challenge, url: `${challenge.url}3` })).resolves.toBe('unsupported')++ installBridge(vi.fn().mockRejectedValue(new Error('ipc down')))+ await expect(runFreeTierChallenge({ ...challenge, url: `${challenge.url}4` })).resolves.toBe('error')+ })+})diff --git a/apps/desktop/src/store/free-tier-challenge.ts b/apps/desktop/src/store/free-tier-challenge.tsnew file mode 100644index 00000000000..26fc6619cf2--- /dev/null+++ b/apps/desktop/src/store/free-tier-challenge.ts@@ -0,0 +1,80 @@+import type { FreeTierChallengePayload } from '@hermes/shared'++/**+ * The free tier's browser challenge, renderer half: a relay. The backend+ * (`hermes_cli/anon_challenge.py`) announces a challenge and polls the account+ * service for the result itself; the Electron main process+ * (`electron/challenge-window.ts`) loads the page hidden and decides when to+ * reveal it. This relays each presentation attempt and reports how the window+ * ended, once, so the backend can re-mint promptly instead of polling out.+ * The event and a status read can both name the same attempt.+ */++export type FreeTierChallengeOutcome = 'done' | 'failed' | 'closed' | 'timeout' | 'refused' | 'error' | 'unsupported'++const inFlight = new Map<string, Promise<FreeTierChallengeOutcome>>()+type ChallengeReporter = (result: {+ url: string+ attempt: number+ outcome: FreeTierChallengeOutcome+}) => Promise<unknown>++function isBrowserChallenge(value: unknown): value is FreeTierChallengePayload {+ if (typeof value !== 'object' || value === null) {+ return false+ }++ const candidate = value as Partial<FreeTierChallengePayload>++ return candidate.type === 'browser' && typeof candidate.url === 'string' && candidate.url.length > 0+}++export function runFreeTierChallenge(+ challenge: unknown,+ report?: ChallengeReporter+): Promise<FreeTierChallengeOutcome> | null {+ if (!isBrowserChallenge(challenge)) {+ return null+ }++ const attempt = challenge.attempt ?? 0+ const key = `${challenge.url}:${attempt}`+ const existing = inFlight.get(key)++ if (existing) {+ // The first asker's report covers this attempt; a second report would+ // only repeat it.+ return existing+ }++ // A hint, not a verdict: an older backend without the RPC, or a dropped+ // socket, loses it and falls back to its bounded status poll. The result+ // never grants a credential, so a failed report is not worth surfacing.+ const reported = async (outcome: FreeTierChallengeOutcome) => {+ try {+ await report?.({ url: challenge.url, attempt, outcome })+ } catch {+ // see above+ }++ return outcome+ }++ const bridge = window.hermesDesktop?.freeTierChallenge++ if (!bridge) {+ // A web build, or a desktop shell older than this renderer: nothing can+ // host the page. Say so, so the backend can end its wait promptly.+ return reported('unsupported')+ }++ const run = bridge+ .run({ url: challenge.url, required: challenge.required !== false, expiresIn: challenge.expires_in, attempt })+ .catch((): FreeTierChallengeOutcome => 'error')+ .then(reported)+ .finally(() => inFlight.delete(key))++ inFlight.set(key, run)++ return run+}diff --git a/apps/desktop/src/store/free-tier.ts b/apps/desktop/src/store/free-tier.tsindex 6c95b29d65f..b528141ec3d 100644--- a/apps/desktop/src/store/free-tier.ts+++ b/apps/desktop/src/store/free-tier.ts@@ -1,5 +1,6 @@import { atom } from 'nanostores'+import { runFreeTierChallenge } from '@/store/free-tier-challenge'import { onboardingSurfaceActive } from '@/store/onboarding-presence'import type { FreeTierStatus } from '@/types/hermes'@@ -44,6 +45,9 @@ export async function refreshFreeTierStatus(requestGateway: FreeTierRequester):}$freeTierStatus.set(status)+ // A client that connected after the `free_tier.challenge` event still has+ // a window to open; the run is de-duplicated per URL.+ void runFreeTierChallenge(status.challenge, result => requestGateway('free_tier.challenge_result', result))return status} catch {diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 8e7f81ca492..164c806dfcd 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1,4 +1,4 @@-import type { ConnectionRequestPayload, ToolLabel } from '@hermes/shared'+import type { ConnectionRequestPayload, FreeTierChallengePayload, ToolLabel } from '@hermes/shared'import type { ToolResultMetadata } from '@/lib/tool-result-metadata'@@ -181,6 +181,8 @@ export interface FreeTierStatus {error_code?: stringretryable?: booleanretry_after?: number+ /** Present while the backend is waiting on a browser challenge. */+ challenge?: FreeTierChallengePayload | null}export interface MemoryProviderOAuthStatus {diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 8b4693197f2..ba3e2d22b79 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -642,6 +642,26 @@ export interface FreeTierStatusResult {error_code?: string | nullretryable?: boolean | nullretry_after?: number | null+ challenge?: FreeTierChallengePayload | null+}+/** ``hermes_cli/anon_challenge.py::BrowserChallenge.as_payload``: the ``free_tier.challenge`` event, and ``free_tier.status``'s ``challenge`` field for a client that connected after it. */+export interface FreeTierChallengePayload {+ type: 'browser'+ url: string+ required: boolean+ expires_in: number+ message: string+ attempt?: number+ [key: string]: unknown+}+export interface FreeTierChallengeResultParams {+ profile?: string | null+ url: string+ attempt?: number+ outcome: 'done' | 'failed' | 'closed' | 'timeout' | 'refused' | 'error' | 'unsupported'+}+export interface FreeTierChallengeResult {+ accepted: boolean}export interface FreeTierProvisionResult {has_guest: boolean@@ -5022,6 +5042,8 @@ export interface RpcMethods {'file.attach': { params: FileAttachParams; result: FileAttachResult }/** Mark the one-time availability notice as shown on the free-tier identity. */'free_tier.ack_notice': { params: ProfileParams; result: FreeTierAckNoticeResult }+ /** Report a browser window outcome for the matching pending attempt; mint remains authoritative. */+ 'free_tier.challenge_result': { params: FreeTierChallengeResultParams; result: FreeTierChallengeResult }/** Explicit retry of the free-tier identity mint when the boot bootstrap could not create it. */'free_tier.provision': { params: ProfileParams; result: FreeTierProvisionResult }/** Pure read of the focused profile's free-tier identity state (no network, no side effects). */@@ -5471,6 +5493,7 @@ export const RPC_METHODS = ['display.thumbnail','file.attach','free_tier.ack_notice',+ 'free_tier.challenge_result','free_tier.provision','free_tier.status','gateway.capabilities',@@ -5750,6 +5773,8 @@ export interface BackendGatewayEventMap {'display.status': DisplayStatusPayload/** A session-level failure outside a turn (agent init, model switch, compression, resume). */error: ErrorPayload+ /** The account service wants a browser challenge cleared before the free-tier token exchange (broadcast); the desktop loads ``url`` in a hidden window. */+ 'free_tier.challenge': FreeTierChallengePayload/** First frame of a connection: the resolved skin, the change-event capability and the replay epoch. */'gateway.ready': GatewayReadyPayload/** Apply a named desktop layout preset. */@@ -5886,6 +5911,7 @@ export const GATEWAY_EVENT_TYPES = ['display.lease','display.status','error',+ 'free_tier.challenge','gateway.ready','layout.apply','message.complete',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex edd3f051da4..92946d483d2 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -1014,6 +1014,24 @@}}},+ {+ "name": "free_tier.challenge_result",+ "summary": "Report a browser window outcome for the matching pending attempt; mint remains authoritative.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/FreeTierChallengeResultParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/FreeTierChallengeResult"+ }+ }+ },{"name": "free_tier.provision","summary": "Explicit retry of the free-tier identity mint when the boot bootstrap could not create it.",@@ -13944,6 +13962,106 @@"title": "FreeTierAckNoticeResult","type": "object"},+ "FreeTierChallengePayload": {+ "additionalProperties": true,+ "description": "``hermes_cli/anon_challenge.py::BrowserChallenge.as_payload``: the ``free_tier.challenge``\nevent, and ``free_tier.status``'s ``challenge`` field for a client that connected after it.",+ "properties": {+ "type": {+ "const": "browser",+ "title": "Type",+ "type": "string"+ },+ "url": {+ "title": "Url",+ "type": "string"+ },+ "required": {+ "title": "Required",+ "type": "boolean"+ },+ "expires_in": {+ "title": "Expires In",+ "type": "integer"+ },+ "message": {+ "title": "Message",+ "type": "string"+ },+ "attempt": {+ "default": 0,+ "title": "Attempt",+ "type": "integer"+ }+ },+ "required": [+ "type",+ "url",+ "required",+ "expires_in",+ "message"+ ],+ "title": "FreeTierChallengePayload",+ "type": "object"+ },+ "FreeTierChallengeResult": {+ "additionalProperties": false,+ "properties": {+ "accepted": {+ "title": "Accepted",+ "type": "boolean"+ }+ },+ "required": [+ "accepted"+ ],+ "title": "FreeTierChallengeResult",+ "type": "object"+ },+ "FreeTierChallengeResultParams": {+ "additionalProperties": false,+ "properties": {+ "profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Profile"+ },+ "url": {+ "title": "Url",+ "type": "string"+ },+ "attempt": {+ "default": 0,+ "title": "Attempt",+ "type": "integer"+ },+ "outcome": {+ "enum": [+ "done",+ "failed",+ "closed",+ "timeout",+ "refused",+ "error",+ "unsupported"+ ],+ "title": "Outcome",+ "type": "string"+ }+ },+ "required": [+ "url",+ "outcome"+ ],+ "title": "FreeTierChallengeResultParams",+ "type": "object"+ },"FreeTierProvisionResult": {"additionalProperties": false,"properties": {@@ -14086,6 +14204,17 @@],"default": null,"title": "Retry After"+ },+ "challenge": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/FreeTierChallengePayload"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"required": [@@ -39773,6 +39902,18 @@}]},+ {+ "name": "free_tier.challenge",+ "summary": "The account service wants a browser challenge cleared before the free-tier token exchange (broadcast); the desktop loads ``url`` in a hidden window.",+ "params": [+ {+ "name": "payload",+ "schema": {+ "$ref": "#/components/schemas/FreeTierChallengePayload"+ }+ }+ ]+ },{"name": "gateway.ready","summary": "First frame of a connection: the resolved skin, the change-event capability and the replay epoch.",diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.pyindex 3161c21229f..c8df250d574 100644--- a/hermes_cli/anon_auth.py+++ b/hermes_cli/anon_auth.py@@ -32,6 +32,8 @@ from datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Dict, Optionalfrom agent.retry_utils import parse_retry_after_seconds+from hermes_cli import anon_challenge+from hermes_cli.anon_challenge import ANON_CHALLENGE_REQUIRED, ANON_SIGNIN_REQUIREDfrom hermes_cli.auth_constants import (AuthError, DEFAULT_NOUS_PORTAL_URL, DEFAULT_NOUS_WELCOME_URL, _decode_jwt_claims, httpx)@@ -83,6 +85,8 @@ def _anon_err(message: str, code: str, *, retry_after: Optional[float] = None) -# 503 ``temporarily_disabled`` the ops breaker is tripped (transient, no hint)# 429 ``temporarily_unavailable`` + Retry-After per-address / per-credential limits# 428 ``pow_required`` / ``pow_invalid`` / ``pow_replayed`` proof-of-work enforced (not implemented here)+# 428 ``challenge_required`` + ``challenges[]`` a browser challenge first (``anon_challenge``)+# 403 ``signin_required`` / ``access_denied`` this client is refused without an account# 404 ``unknown_token`` the credential was reaped or claimed (re-mint)# 403 ``account_locked`` the account is locked (dead; never re-mint from it)# 401 an outstanding JWT whose account is gone (re-mint)@@ -94,8 +98,12 @@ ANON_ACCOUNT_LOCKED = "anon_account_locked" # dead, and no replacement is minANON_CREDENTIAL_DEAD = "anon_credential_dead" # reaped or claimed: replaced silently, onceANON_UNREACHABLE = "anon_unreachable" # timeout, DNS, refused connectionANON_SERVER_ERROR = "anon_server_error" # 5xx, non-JSON, malformed success body+# ANON_CHALLENGE_REQUIRED / ANON_SIGNIN_REQUIRED live in ``anon_challenge`` (imported above): a+# browser challenge is still pending (retryable), or the service refuses this client without an+# account, which includes any 428 this version does not understand.# Codes a later attempt cannot fix (for this process / this version).-ANON_TERMINAL_CODES = frozenset({ANON_GATE_CLOSED, ANON_POW_REQUIRED, ANON_ACCOUNT_LOCKED})+ANON_TERMINAL_CODES = frozenset({+ ANON_GATE_CLOSED, ANON_POW_REQUIRED, ANON_ACCOUNT_LOCKED, ANON_SIGNIN_REQUIRED})# Codes that mean the account service itself is not answering: a sign-in (which goes through the# same service) cannot help either, so surfaces offer "try again" / "another provider" only.ANON_UNREACHABLE_CODES = frozenset({ANON_UNREACHABLE, ANON_SERVER_ERROR})@@ -110,6 +118,8 @@ ANON_FAILURE_COPY = {"Signing in is free and skips the wait.",ANON_POW_REQUIRED: "The Nous server asked for a proof of work, but that isn't implemented in your ""Agent yet. Sign in with a Nous account to continue.",+ ANON_CHALLENGE_REQUIRED: anon_challenge.CHALLENGE_PENDING_COPY,+ ANON_SIGNIN_REQUIRED: anon_challenge.SIGNIN_REQUIRED_COPY,ANON_ACCOUNT_LOCKED: f"This session can't continue without signing in. {_SIGNIN_IS_FREE}",ANON_CREDENTIAL_DEAD: "Your session ended. A new one starts on its own.",ANON_UNREACHABLE: "The Nous service couldn't be reached. Check your internet connection and try again.",@@ -260,7 +270,7 @@ def anon_secret() -> str:def _anon_headers() -> Dict[str, str]:- headers = {"content-type": "application/json"}+ headers = {"content-type": "application/json", "user-agent": anon_challenge.user_agent()}if secret := anon_secret():headers[ANON_SECRET_HEADER] = secretreturn headers@@ -282,7 +292,9 @@ _NAS_REFUSALS: Dict[tuple, tuple] = {}-def _raise_for_anon_status(response: httpx.Response, *, action: str) -> Dict[str, Any]:+def _raise_for_anon_status(+ response: httpx.Response, *, action: str, portal_base_url: str = "",+) -> Dict[str, Any]:try:payload = response.json()except ValueError:@@ -295,8 +307,18 @@ def _raise_for_anon_status(response: httpx.Response, *, action: str) -> Dict[strreturn payloadif error.startswith("pow_"):error = "pow_" # pow_required / pow_invalid / pow_replayed are one verdict+ # The challenge gate sits on the token exchange only (``portal_base_url`` is passed by it and+ # nothing else); every other endpoint keeps the table below, unchanged.+ if portal_base_url:+ if status == 428 and error == "challenge_required":+ raise anon_challenge.challenge_error(payload, portal_base_url)+ if (status == 403 and error in ("signin_required", "access_denied")) or (+ status == 428 and error != "pow_"):+ # Refused without an account, or a 428 this version has no primitive for: either way+ # the honest way forward is a sign-in, in the service's own words when it sent some.+ raise anon_challenge.signin_required_error(payload.get("message"))cls, code = (_NAS_REFUSALS.get((status, error)) or _NAS_REFUSALS.get((status, None))- or ((AuthError, ANON_POW_REQUIRED) if error == "pow_" else (AuthError, ANON_SERVER_ERROR)))+ or (AuthError, ANON_SERVER_ERROR))if code == ANON_SERVER_ERROR:logger.info("Nous free tier %s failed (%s%s)", action, status, f": {error}" if error else "")retry_after = parse_retry_after_seconds(response.headers)@@ -321,11 +343,18 @@ def exchange_anon_jwt(client: httpx.Client, portal_base_url: str, anon_token: stRaises :class:`AnonCredentialDead` on 404 ``unknown_token`` / 401 (reaped or claimed)."""response = client.post(- f"{portal_base_url.rstrip('/')}/api/anonymous/token", headers=_anon_headers(), json={"token": anon_token})- payload = _raise_for_anon_status(response, action="token exchange")+ f"{portal_base_url.rstrip('/')}/api/anonymous/token", headers=_anon_headers(),+ json={"token": anon_token, "client": anon_challenge.client_info()})+ try:+ payload = _raise_for_anon_status(response, action="token exchange", portal_base_url=portal_base_url)+ except anon_challenge.AnonChallengeRequired as challenge:+ # What ``run_with_challenge`` polls with, once the caller's locks have unwound.+ challenge.portal_base_url, challenge.anon_token = portal_base_url, anon_token+ raiseif not isinstance(payload.get("access_token"), str) or not payload["access_token"]:logger.info("Nous free tier token exchange returned no token")raise _anon_err(ANON_FAILURE_COPY[ANON_SERVER_ERROR], ANON_SERVER_ERROR)+ anon_challenge.note_optional_challenges(payload, portal_base_url)return payload@@ -581,7 +610,12 @@ def refresh_guest_state(state: Dict[str, Any], client: httpx.Client) -> None:if not isinstance(anon_token, str) or not anon_token:raise AnonCredentialDead(ANON_FAILURE_COPY[ANON_CREDENTIAL_DEAD], code=ANON_CREDENTIAL_DEAD)from hermes_cli.auth import _nous_portal_base_url- apply_exchange_to_state(state, exchange_anon_jwt(client, _nous_portal_base_url(state), anon_token))+ try:+ payload = exchange_anon_jwt(client, _nous_portal_base_url(state), anon_token)+ except anon_challenge.AnonChallengeRequired as challenge:+ challenge.auth_state = state # the ``tls`` block the status poll inherits+ raise+ apply_exchange_to_state(state, payload)def clear_dead_guest(reason: str, *, dead_token: Optional[str] = None) -> None:diff --git a/hermes_cli/anon_challenge.py b/hermes_cli/anon_challenge.pynew file mode 100644index 00000000000..967cd7708b9--- /dev/null+++ b/hermes_cli/anon_challenge.py@@ -0,0 +1,470 @@+"""Nous free tier: the browser challenge the account service may put in front of a token exchange.++NAS can answer ``POST /api/anonymous/token`` with **428** ``challenge_required`` and a list of+challenges. Hermes implements exactly one primitive, ``browser-v1``: *open this portal URL, poll+until it clears, exchange again*. Everything the page does (bot detection, an in-browser proof of+work, an interactive fallback, its copy) belongs to the portal and changes without a Hermes release.++Who opens the URL depends on the surface:++* **desktop** (``HERMES_DESKTOP=1``): this process never opens anything. It publishes the challenge+ (``free_tier.challenge`` global event, and ``free_tier.status``'s ``challenge`` field for a client+ that connects later); the renderer hands it to the Electron main process, which loads it in a+ HIDDEN window and reveals that window only if the page asks for the human.+* **terminal**: print the URL, and open the system browser when there is a graphical one to open.++The wait runs OUTSIDE the auth-store and shared-store locks: the exchange that hit the 428 has+already unwound (the exception left the ``with`` blocks), so a slow page never stalls a sibling+profile or process. One challenge is worked at a time per process; a second thread that hits the+same 428 waits for the first and then simply exchanges again (NAS hands a retried mint the same+ticket, and a cleared credential a token).++Only a caller someone is waiting on waits for a challenge. A background reader (the keepalive tick,+a status paint) runs inside :func:`background_caller`: it still gets the challenge in front of a+desktop client (so the hidden window can clear it before anyone needs a token) but never blocks,+prints, or opens a browser.++An *optional* challenge (``required: false`` on a successful exchange: the service is measuring, not+enforcing) is only ever announced to a desktop client, never opened in a user's browser, and+nothing waits on it.+"""++from __future__ import annotations++import contextlib+import contextvars+import logging+import math+import os+import platform+import sys+import threading+import time+from dataclasses import dataclass, replace+from typing import Any, Callable, Dict, Optional, TypeVar+from urllib.parse import urlparse++from hermes_cli.auth_constants import AuthError, httpx++logger = logging.getLogger("hermes_cli.auth")++BROWSER_CAPABILITY = "browser-v1"+CHALLENGE_EVENT = "free_tier.challenge"+ANON_CHALLENGE_REQUIRED = "anon_challenge_required"+ANON_SIGNIN_REQUIRED = "anon_signin_required"++# How long one exchange attempt waits for its challenge. The page normally clears in seconds; this+# bounds the interactive case (a human solving a check) without parking a request for the ticket's+# whole ten minutes. A later attempt resumes the same ticket.+CHALLENGE_WAIT_SECONDS = 120.0+_POLL_MIN_SECONDS, _POLL_MAX_SECONDS = 1.0, 5.0+# ``expires_in`` is network input that ends up in timers on two runtimes: keep it finite and sane.+_EXPIRES_MIN_SECONDS, _EXPIRES_MAX_SECONDS, _EXPIRES_DEFAULT_SECONDS = 30.0, 900.0, 600.0+_MESSAGE_MAX_CHARS = 300++CHALLENGE_COPY = "Nous needs to run a quick check before starting your free session."+CHALLENGE_PENDING_COPY = "Finish the quick check in your browser, then try again."+SIGNIN_REQUIRED_COPY = "Free guest access isn't available here. Sign in with a Nous account to continue."++T = TypeVar("T")+++@dataclass(frozen=True)+class BrowserChallenge:+ url: str+ required: bool+ expires_in: float+ interval: float+ message: str+ attempt: int = 0++ def as_payload(self) -> Dict[str, Any]:+ return {"type": "browser", "url": self.url, "required": self.required,+ "expires_in": int(self.expires_in), "message": self.message, "attempt": self.attempt}+++class AnonChallengeRequired(AuthError):+ """The exchange needs a browser challenge first. Carries what :func:`run_with_challenge` needs+ to work it: the challenge, and the portal, credential and trust to poll with (set by the exchange)."""++ def __init__(self, challenge: BrowserChallenge) -> None:+ super().__init__(challenge.message, provider="nous", code=ANON_CHALLENGE_REQUIRED, retryable=True)+ self.challenge = challenge+ self.portal_base_url = ""+ self.anon_token = ""+ self.auth_state: Optional[Dict[str, Any]] = None+++def signin_required_error(message: Any = None) -> AuthError:+ """The service will not serve this client without an account (or asked for something this+ version cannot do). Terminal for the process, like a closed gate."""+ return AuthError(server_message(message) or SIGNIN_REQUIRED_COPY, provider="nous",+ code=ANON_SIGNIN_REQUIRED, retryable=False)+++def server_message(value: Any) -> str:+ """User-facing copy the service sent, if it is plausibly that: a short single paragraph."""+ if not isinstance(value, str):+ return ""+ # Printable text only: this reaches a terminal, and a control character there is an escape+ # sequence the service (or whoever answered as it) gets to run.+ text = " ".join("".join(ch if ch.isprintable() else " " for ch in value).split())+ return text if 0 < len(text) <= _MESSAGE_MAX_CHARS else ""+++# --- What this client tells the service about itself -------------------------------------------------+++def client_surface() -> str:+ """``gateway`` in the process that holds the messaging gateway's runtime lock (nobody is at its+ console), ``desktop`` for the backend the desktop app spawned, else ``cli``."""+ status = sys.modules.get("gateway.status")+ if status is not None and status.owns_gateway_runtime_lock():+ return "gateway"+ return "desktop" if (os.environ.get("HERMES_DESKTOP") or "").strip() == "1" else "cli"+++def client_info() -> Dict[str, Any]:+ """The self-reported ``client`` block on a token exchange. It sorts honest clients (which+ surface, which challenge primitives) for the service's rules; it proves nothing, by design."""+ from hermes_cli import __version__+ return {"name": "hermes-agent", "version": __version__, "surface": client_surface(),+ "platform": sys.platform, "capabilities": [BROWSER_CAPABILITY]}+++def user_agent() -> str:+ from hermes_cli import __version__+ return f"hermes-agent/{__version__} ({client_surface()}; {sys.platform}; {platform.machine() or 'unknown'})"+++# --- Parsing ------------------------------------------------------------------------------------------+++def _same_origin(url: str, portal_base_url: str) -> bool:+ """A challenge URL is only ever opened on the portal the exchange itself went to: the response+ is network input, and "open this URL" must not become "open any URL"."""+ try:+ target, portal = urlparse(url), urlparse(portal_base_url)+ except ValueError:+ return False+ return (target.scheme in ("https", "http") and target.scheme == portal.scheme+ and bool(target.netloc) and target.netloc.lower() == portal.netloc.lower())+++def _number(value: Any, default: float) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ return default+ return float(value)+++def parse_browser_challenge(payload: Dict[str, Any], portal_base_url: str) -> Optional[BrowserChallenge]:+ """The first challenge in ``payload["challenges"]`` this client can run, or None."""+ entries = payload.get("challenges")+ if not isinstance(entries, list):+ return None+ message = server_message(payload.get("message")) or CHALLENGE_COPY+ for entry in entries:+ if not isinstance(entry, dict) or entry.get("type") != "browser":+ continue+ url = entry.get("url")+ if not isinstance(url, str) or not url.isprintable() or not _same_origin(url, portal_base_url):+ logger.info("Nous free tier: ignoring a challenge URL outside the portal origin")+ continue+ return BrowserChallenge(+ url=url, required=entry.get("required") is not False,+ expires_in=min(_EXPIRES_MAX_SECONDS, max(+ _EXPIRES_MIN_SECONDS, _number(entry.get("expires_in"), _EXPIRES_DEFAULT_SECONDS))),+ interval=min(_POLL_MAX_SECONDS, max(_POLL_MIN_SECONDS, _number(entry.get("interval"), 2.0))),+ message=message)+ return None+++def challenge_error(payload: Dict[str, Any], portal_base_url: str) -> AuthError:+ """The error for a 428 ``challenge_required``: a challenge to work, or (nothing offered that+ this version can run) the sign-in fallback."""+ challenge = parse_browser_challenge(payload, portal_base_url)+ # The payload's ``message`` describes the challenge, so it is not reused for the fallback.+ return AnonChallengeRequired(challenge) if challenge else signin_required_error()+++# --- Pending challenge: what a status read shows --------------------------------------------------------++_pending_lock = threading.Lock()+_pending: Dict[str, Dict[str, Any]] = {}+# One challenge worked at a time PER PROFILE: a sibling profile's wait must not queue behind it.+_work_locks: Dict[str, threading.Lock] = {}++# Set by :func:`background_caller`: this caller has nobody waiting on it.+_background: contextvars.ContextVar[bool] = contextvars.ContextVar("anon_challenge_background", default=False)+++def background_caller():+ """Mark the enclosed token reads as background work (a keepalive tick, a status paint): a+ challenge is announced to a desktop client but never waited on, printed, or opened."""+ token = _background.set(True)+ try:+ yield+ finally:+ _background.reset(token)+++def _work_lock() -> threading.Lock:+ with _pending_lock:+ return _work_locks.setdefault(_profile_key(), threading.Lock())+++def _profile_key() -> str:+ from hermes_cli.anon_auth import _mint_memo_key+ return _mint_memo_key()+++def pending_challenge() -> Optional[Dict[str, Any]]:+ """The challenge this profile is waiting on, for ``free_tier.status`` (a client that connected+ after the event fired still learns it has a window to open). None once cleared or expired, or+ once the host said how its window ended (a window the user closed must not come back)."""+ with _pending_lock:+ entry = _pending.get(_profile_key())+ if entry and entry["deadline"] <= time.monotonic():+ _pending.pop(_profile_key(), None)+ entry = None+ if not entry or entry["outcome"] not in (None, "timeout", "error"):+ return None+ return {**entry["payload"], "expires_in": math.ceil(entry["deadline"] - time.monotonic())}+++def _clear_pending() -> None:+ with _pending_lock:+ _pending.pop(_profile_key(), None)+++def _set_pending(challenge: BrowserChallenge, *, new_attempt: bool = False) -> BrowserChallenge:+ """Record *challenge* as the profile's pending one. A replay of the same ticket keeps the+ original deadline and (unless *new_attempt*) its host outcome; the attempt number is what+ lets a fresh foreground attempt reopen a window the user closed."""+ with _pending_lock:+ key = _profile_key()+ previous = _pending.get(key)+ if previous and previous["payload"]["url"] != challenge.url:+ previous = None+ attempt = previous["payload"]["attempt"] + new_attempt if previous else 0+ deadline = time.monotonic() + challenge.expires_in+ if previous:+ deadline = min(deadline, previous["deadline"])+ challenge = replace(challenge, attempt=attempt)+ _pending[key] = {"payload": challenge.as_payload(), "deadline": deadline,+ "outcome": previous["outcome"] if previous and not new_attempt else None}+ return challenge+++def _matching_entry(url: str, attempt: int) -> Optional[Dict[str, Any]]:+ entry = _pending.get(_profile_key())+ if entry and entry["payload"]["url"] == url and entry["payload"]["attempt"] == attempt:+ return entry+ return None+++def record_host_outcome(url: str, attempt: int, outcome: str) -> bool:+ """A presentation hint: wakes a waiter to re-mint, never grants clearance locally. A late+ reply belongs to the attempt that opened the window, not to a newer retry."""+ with _pending_lock:+ entry = _matching_entry(url, attempt)+ if not entry or entry["deadline"] <= time.monotonic():+ return False+ entry["outcome"] = outcome+ return True+++def _host_outcome(challenge: BrowserChallenge) -> Optional[str]:+ with _pending_lock:+ entry = _matching_entry(challenge.url, challenge.attempt)+ return entry["outcome"] if entry else None+++def reset_for_tests() -> None:+ with _pending_lock:+ _pending.clear()+ _work_locks.clear()+ _gave_up_until.clear()+ _opened_urls.clear()+++# --- Presenting ---------------------------------------------------------------------------------------+++def _announce(challenge: BrowserChallenge) -> bool:+ """Broadcast to connected desktop clients. False when this process is not a gateway at all+ (``HERMES_DESKTOP`` is an env var, and a CLI the desktop spawned inherits it): importing the+ gateway here just to find nobody listening would also write an event frame to stdout."""+ server = sys.modules.get("tui_gateway.server")+ if server is None:+ return False+ try:+ server._broadcast_global_event(CHALLENGE_EVENT, challenge.as_payload())+ return True+ except Exception as exc:+ logger.debug("%s not broadcast: %s", CHALLENGE_EVENT, exc)+ return False+++_opened_urls: set = set() # challenge URLs whose browser tab was opened+++def _present_in_terminal(challenge: BrowserChallenge) -> None:+ from hermes_cli.auth_device_flow import _can_open_graphical_browser, _is_remote_session+ opened = False+ # One tab per ticket, however many attempts resume it: a user who has not got to it yet is+ # not helped by a second copy. A gateway has no console of its own: it logs the link only.+ already_open = challenge.url in _opened_urls+ if (not already_open and client_surface() != "gateway"+ and not _is_remote_session() and _can_open_graphical_browser()):+ try:+ import webbrowser+ opened = bool(webbrowser.open(challenge.url))+ if opened:+ _opened_urls.add(challenge.url)+ except Exception as exc:+ logger.debug("could not open the challenge in a browser: %s", exc)+ print(f"\n{challenge.message}", file=sys.stderr)+ print(f" Open: {challenge.url}", file=sys.stderr)+ print(" (Opened in your browser.)\n" if opened or already_open+ else " (Open that link in any browser; this continues on its own.)\n", file=sys.stderr)+++def present(challenge: BrowserChallenge) -> None:+ """Get the URL in front of something that can load it. Seam for tests (``_presenter``)."""+ if client_surface() == "desktop" and _announce(challenge):+ return+ if challenge.required and not _background.get():+ _present_in_terminal(challenge)+++_presenter: Callable[[BrowserChallenge], None] = present+_sleep = time.sleep # seam for tests+++# --- Working a challenge ----------------------------------------------------------------------------+++def _poll_status(client: httpx.Client, portal_base_url: str, anon_token: str) -> str:+ """One status read. Anything that is not a clear ``pending`` / ``needs_interaction`` ends the+ wait: the exchange that follows is the authority on whether the credential is cleared. (A+ passed challenge reads ``none``: passing detaches the ticket.)"""+ from hermes_cli.anon_auth import _anon_headers+ try:+ response = client.post(f"{portal_base_url.rstrip('/')}/api/anonymous/challenge/status",+ headers=_anon_headers(), json={"token": anon_token})+ if 400 <= response.status_code < 500 and response.status_code != 429:+ # The service will not answer this poll (credential reaped, surface off): waiting cannot+ # change that. End the wait; the exchange's own verdict says what happened.+ return "none"+ body = response.json() if response.status_code == 200 else None+ except (httpx.HTTPError, ValueError) as exc:+ logger.debug("challenge status poll failed: %s", exc)+ body = None+ status = body.get("status") if isinstance(body, dict) else None+ # Only a 200 that names a status is a verdict. A 429, a 5xx or a dropped connection is a+ # blip: keep waiting (the deadline bounds it) rather than abandon a check the user is on.+ return status if isinstance(status, str) else "pending"+++_WAITING = ("pending", "needs_interaction")+# After one attempt ran out of patience, the callers queued behind it fail fast for this long+# instead of each parking for another full wait (boot fires a burst of token reads).+_GAVE_UP_COOLDOWN_SECONDS = 30.0+_gave_up_until: Dict[str, float] = {}+++def _give_up(key: str) -> None:+ _gave_up_until[key] = time.monotonic() + _GAVE_UP_COOLDOWN_SECONDS+++def wait_for_challenge(exc: AnonChallengeRequired) -> bool:+ """Present *exc*'s challenge and poll until status or a host hint ends the wait.+ True = a result arrived; False = patience ran out. Re-mint is authoritative in either case.++ Called under the profile's work lock. A caller that queued behind another finds the ticket+ already settled on its first status read and returns without presenting anything."""+ from hermes_cli.auth import _resolve_verify+ from hermes_cli.auth_nous import _nous_http_client+ key = _profile_key()+ if time.monotonic() < _gave_up_until.get(key, 0.0):+ return False+ challenge = exc.challenge+ deadline = time.monotonic() + min(CHALLENGE_WAIT_SECONDS, challenge.expires_in)+ # Poll under the trust the credential was minted with: a guest's ``tls`` block is written from+ # the mint's own verify, so this is the context the 428 exchange just used, not a narrowing.+ verify = _resolve_verify(auth_state=exc.auth_state)+ told_interactive = False+ with _nous_http_client(10.0, verify) as client:+ if _poll_status(client, exc.portal_base_url, exc.anon_token) not in _WAITING:+ return True+ challenge = exc.challenge = _set_pending(challenge, new_attempt=True)+ _presenter(challenge)+ while time.monotonic() < deadline:+ if _host_outcome(challenge) is not None:+ return True+ _sleep(challenge.interval)+ status = _poll_status(client, exc.portal_base_url, exc.anon_token)+ if status not in _WAITING:+ return True+ if status == "needs_interaction" and not told_interactive:+ told_interactive = True+ if client_surface() != "desktop":+ print(" Finish the quick check in your browser to continue.", file=sys.stderr)+ _give_up(key)+ return False+++def _still_pending(cause: AnonChallengeRequired) -> AuthError:+ message = ("The quick check couldn't finish. Try again." if _host_outcome(cause.challenge)+ else CHALLENGE_PENDING_COPY)+ error = AuthError(message, provider="nous", code=ANON_CHALLENGE_REQUIRED, retryable=True)+ error.__cause__ = cause+ return error+++def run_with_challenge(exchange: Callable[[], T]) -> T:+ """Run *exchange*; if the service asks for a browser challenge, work it (outside every lock:+ the exception has already unwound them) and run *exchange* once more.++ A background caller (:func:`background_caller`) never waits: the challenge is announced so a+ desktop client can start clearing it, and the retryable error goes straight back.++ A second ``challenge_required`` is not looped on: it surfaces as a retryable error whose copy+ says what the user can do, the callers queued behind it fail fast for a while, and the next+ attempt resumes the same ticket."""+ try:+ return exchange()+ except AnonChallengeRequired as exc:+ first = exc+ if _background.get():+ _presenter(_set_pending(first.challenge))+ raise _still_pending(first)+ with _work_lock():+ wait_for_challenge(first)+ # Even a timed-out status poll can lag a committed clearance. Mint is+ # authoritative and gets one final attempt before we report a pending check.+ try:+ return exchange()+ except AnonChallengeRequired as again:+ # Whatever ended the wait (status, a host hint, patience), a second 428 starts the fail-fast+ # cooldown; the attempt after it opens a fresh window (``new_attempt``).+ again.challenge = _set_pending(again.challenge)+ _give_up(_profile_key())+ raise _still_pending(again)+ except AuthError as error:+ if not error.retryable:+ _clear_pending()+ raise+++def note_optional_challenges(payload: Dict[str, Any], portal_base_url: str) -> None:+ """A successful exchange may advertise a challenge nobody has to pass (the service is measuring+ before it enforces). Only a desktop client runs it, hidden; a terminal never opens a browser+ for something optional. Fire and forget."""+ challenge = parse_browser_challenge(payload, portal_base_url)+ if challenge is None:+ _clear_pending()+ elif not challenge.required and client_surface() == "desktop":+ _announce(_set_pending(challenge))diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex e50c29a50dd..35362e832ad 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -1830,7 +1830,22 @@ def resolve_nous_access_token(insecure: Optional[bool] = None,ca_bundle: Optional[str] = None,refresh_skew_seconds: int = ACCESS_TOKEN_REFRESH_SKEW_SECONDS) -> str:- """Resolve a refresh-aware Nous Portal access token for managed tool gateways."""+ """Resolve a refresh-aware Nous Portal access token for managed tool gateways.++ A free-tier exchange may be answered with a browser challenge (``anon_challenge``); it is worked+ here, after the exchange's locks have unwound, and the exchange is then run once more."""+ from hermes_cli.anon_challenge import run_with_challenge+ return run_with_challenge(lambda: _resolve_nous_access_token(+ timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle,+ refresh_skew_seconds=refresh_skew_seconds))+++def _resolve_nous_access_token(+ *,+ timeout_seconds: float,+ insecure: Optional[bool],+ ca_bundle: Optional[str],+ refresh_skew_seconds: int) -> str:# Only a default-TLS resolution is memoised; error paths never populate the memo.memoable = not insecure and ca_bundle is Nonecache_key = hermes_home_key()diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.pyindex bca4a7e3d61..c1a6168cdb7 100644--- a/hermes_cli/auth_nous.py+++ b/hermes_cli/auth_nous.py@@ -1054,10 +1054,13 @@ def resolve_nous_runtime_credentials(identity is set up once, transparently -- the one client rule covering both reap and claim."""from hermes_cli.anon_auth import AnonCredentialDead, clear_dead_guest, ensure_portal_identity+ from hermes_cli.anon_challenge import run_with_challengetry:- return _resolve_nous_runtime_credentials(+ # A free-tier exchange may be answered with a browser challenge; it is worked here, after+ # the exchange's locks have unwound, and the exchange is then run once more.+ return run_with_challenge(lambda: _resolve_nous_runtime_credentials(timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle,- force_refresh=force_refresh, stale_access_token=stale_access_token)+ force_refresh=force_refresh, stale_access_token=stale_access_token))except AnonCredentialDead as dead_exc:from hermes_cli.auth import get_provider_auth_statefrom hermes_cli.anon_auth import ANON_ACCOUNT_LOCKED@@ -1068,8 +1071,8 @@ def resolve_nous_runtime_credentials(raiseif ensure_portal_identity(explicit=True, timeout_seconds=timeout_seconds) is None:raise- return _resolve_nous_runtime_credentials(- timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle)+ return run_with_challenge(lambda: _resolve_nous_runtime_credentials(+ timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle))def _resolve_nous_runtime_credentials(@@ -1201,7 +1204,10 @@ def _compute_nous_auth_status() -> Dict[str, Any]:base_status = _nous_status_from_state(state, logged_in=bool(state.get("access_token")), source="auth_store")try:- creds = resolve_nous_runtime_credentials()+ # A status paint must not park on (or open a browser for) a free-tier challenge.+ from hermes_cli.anon_challenge import background_caller+ with background_caller():+ creds = resolve_nous_runtime_credentials()refreshed_state = get_provider_auth_state("nous") or statebase_status.update({"logged_in": True,diff --git a/hermes_cli/nous_auth_keepalive.py b/hermes_cli/nous_auth_keepalive.pyindex f25d819a560..24eaa00eefb 100644--- a/hermes_cli/nous_auth_keepalive.py+++ b/hermes_cli/nous_auth_keepalive.py@@ -165,7 +165,11 @@ def refresh_nous_auth_keepalive_once(if not get_provider_auth_state("nous"):return Falsetry:- resolve_nous_runtime_credentials(timeout_seconds=_timeout_seconds(timeout_seconds))+ # Nobody is waiting on a keepalive tick: a free-tier browser challenge is announced to the+ # desktop (so it can clear before a token is needed) but never waited on here.+ from hermes_cli.anon_challenge import background_caller+ with background_caller():+ resolve_nous_runtime_credentials(timeout_seconds=_timeout_seconds(timeout_seconds))logger.debug("Nous auth keepalive: refreshed singleton auth state")return Trueexcept Exception as exc:diff --git a/tests/hermes_cli/anon_portal.py b/tests/hermes_cli/anon_portal.pyindex 52bf84c2066..e6696c87622 100644--- a/tests/hermes_cli/anon_portal.py+++ b/tests/hermes_cli/anon_portal.py@@ -40,6 +40,18 @@ class FakePortal:self.create_response: httpx.Response | None = Noneself.token_response: httpx.Response | None = Noneself.raise_transport: Exception | None = None+ # Browser challenge (``hermes_cli.anon_challenge``). ``challenge_required`` makes the exchange+ # answer 428 until the ticket settles; each status poll consumes one entry of+ # ``challenge_statuses`` (then "none": a passed challenge detaches its ticket), and the+ # exchange goes through once the list is drained unless ``challenge_never_clears``.+ self.challenge_required = False+ self.challenge_never_clears = False+ self.challenge_statuses: list[str] = []+ # Status polls answered with this HTTP error first (a 429 / 5xx blip), one per entry.+ self.challenge_status_errors: list[int] = []+ self.challenge_url = f"{PORTAL}/challenge?code=ticket"+ self.optional_challenge = False+ self.token_requests: list[dict] = []def creates(self) -> int:return [p for _, p in self.calls].count("/api/anonymous/create")@@ -59,9 +71,26 @@ class FakePortal:self.minted += 1return httpx.Response(201, json={"user_id": f"nas_user:{self.minted}", "org_id": "nas_org:1","token": f"anon_{self.minted:04d}", "idle_ttl_days": 14})+ if path == "/api/anonymous/challenge/status":+ if self.challenge_status_errors:+ return httpx.Response(self.challenge_status_errors.pop(0), json={"error": "blip"})+ if self.challenge_statuses:+ return httpx.Response(200, json={"status": self.challenge_statuses.pop(0)})+ if self.challenge_never_clears:+ return httpx.Response(200, json={"status": "pending"})+ self.challenge_required = False+ return httpx.Response(200, json={"status": "none"})if path == "/api/anonymous/token":+ self.token_requests.append(+ {"body": json.loads(request.content), "user_agent": request.headers.get("user-agent")})if self.token_response is not None:return self.token_response+ if self.challenge_required:+ return httpx.Response(428, json={+ "error": "challenge_required", "message": "A quick check first.",+ "challenges": [{"type": "browser", "url": self.challenge_url, "state": "pending",+ "required": True, "expires_in": 600, "interval": 2}],+ "fallback_url": f"{PORTAL}/login"})token = json.loads(request.content)["token"]if token in self.dead_tokens:return httpx.Response(404, json={"error": "unknown_token"})@@ -69,6 +98,9 @@ class FakePortal:"user_id": "nas_user:1", "org_id": "nas_org:1"}if self.inference_base_url:body["inference_base_url"] = self.inference_base_url+ if self.optional_challenge:+ body["challenges"] = [{"type": "browser", "url": self.challenge_url, "state": "pending",+ "required": False, "expires_in": 600, "interval": 2}]return httpx.Response(200, json=body)return httpx.Response(500, json={"error": f"unexpected {path}"})@@ -99,6 +131,10 @@ def install_portal(monkeypatch, tmp_path, fake: FakePortal | None = None) -> Fakmonkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)anon_auth.reset_mint_memo_for_tests()free_tier_bootstrap.reset_for_tests()+ from hermes_cli import anon_challenge+ anon_challenge.reset_for_tests()+ monkeypatch.setattr(anon_challenge, "_sleep", lambda _seconds: None)+ monkeypatch.delenv("HERMES_DESKTOP", raising=False)# resolve_nous_access_token memoises the last token for 5 s per profile home (dict); a token minted# by an earlier test must not be served to this one.monkeypatch.setattr(auth_mod, "_RESOLVE_TOKEN_CACHE", {})diff --git a/tests/hermes_cli/test_anon_challenge.py b/tests/hermes_cli/test_anon_challenge.pynew file mode 100644index 00000000000..f293df4680e--- /dev/null+++ b/tests/hermes_cli/test_anon_challenge.py@@ -0,0 +1,398 @@+"""Nous free tier: the browser challenge in front of a token exchange (``hermes_cli.anon_challenge``).++Driven through the fake NAS with Hermes' real client code: the exchange hits a 428, the challenge is+presented and polled OUTSIDE the auth locks, and the exchange runs once more.+"""++from __future__ import annotations++import httpx+import pytest++from hermes_cli import anon_auth, anon_challenge++from tests.hermes_cli.anon_portal import PORTAL, install_portal # noqa: F401+++def nas(monkeypatch, tmp_path):+ return install_portal(monkeypatch, tmp_path)+++def presented(monkeypatch):+ seen: list[anon_challenge.BrowserChallenge] = []+ monkeypatch.setattr(anon_challenge, "_presenter", seen.append)+ return seen+++def _resolve():+ from hermes_cli.auth_nous import resolve_nous_runtime_credentials+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ return resolve_nous_runtime_credentials()+++class TestWhatTheClientSends:+ def test_the_exchange_reports_surface_version_and_the_browser_capability(self, nas):+ _resolve()+ sent = nas.token_requests[-1]+ assert sent["body"]["client"]["capabilities"] == ["browser-v1"]+ assert sent["body"]["client"]["surface"] == "cli"+ assert sent["body"]["client"]["name"] == "hermes-agent"+ assert sent["user_agent"].startswith("hermes-agent/") and "(cli;" in sent["user_agent"]++ def test_the_desktop_backend_reports_the_desktop_surface(self, nas, monkeypatch):+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ _resolve()+ assert nas.token_requests[-1]["body"]["client"]["surface"] == "desktop"+ assert "(desktop;" in nas.token_requests[-1]["user_agent"]++ def test_the_messaging_gateway_reports_the_gateway_surface(self, nas, monkeypatch):+ """The gateway process has no console and no desktop; it must not read as ``cli`` (whose+ rules may expect a human at a terminal) or print challenge links into its logs."""+ import gateway.status as status+ monkeypatch.setattr(status, "owns_gateway_runtime_lock", lambda: True)+ _resolve()+ assert nas.token_requests[-1]["body"]["client"]["surface"] == "gateway"+++class TestRequiredChallenge:+ def test_a_host_failure_wakes_the_waiter_but_still_requires_an_authoritative_mint(self, nas, monkeypatch):+ nas.challenge_required = True+ nas.challenge_never_clears = True++ def failed(challenge):+ assert anon_challenge.record_host_outcome(challenge.url, challenge.attempt, "error")+ monkeypatch.setattr(anon_challenge, "_presenter", failed)+ with pytest.raises(anon_auth.AuthError, match="couldn't finish"):+ _resolve()+ assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2+ assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 1+ # A window that crashed is not a reason to let a boot burst of callers each re-mint and+ # reopen a window: the second 428 starts the same fail-fast cooldown as a timeout.+ from hermes_cli.auth_nous import resolve_nous_runtime_credentials+ with pytest.raises(anon_auth.AuthError):+ resolve_nous_runtime_credentials()+ assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 1++ def test_a_poll_the_service_refuses_ends_the_wait_instead_of_running_out_the_clock(self, nas, presented):+ """404 ``unknown_token`` / 400 on the status poll: the credential is gone (or the surface is+ off), so no amount of waiting clears it. The wait ends and the re-mint says what happened."""+ nas.challenge_required = True+ nas.challenge_never_clears = True+ nas.challenge_statuses = ["pending"] # the "is it already settled?" read+ original = nas.handler++ def refuse_once_pending_is_spent(request):+ if request.url.path.endswith("/challenge/status") and not nas.challenge_statuses:+ nas.calls.append((request.method, request.url.path))+ return httpx.Response(404, json={"error": "unknown_token"})+ return original(request)+ nas.handler = refuse_once_pending_is_spent+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED+ assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") == 2++ def test_the_status_poll_trusts_what_the_credential_was_minted_with(self, nas, presented, monkeypatch):+ """A guest whose ``auth.json`` carries a ``tls`` block polls under it (a private CA, say),+ not under a fresh default context that would fail every read and run out the clock."""+ from hermes_cli import auth_nous+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ with _auth_store_lock():+ store = _load_auth_store()+ store["providers"]["nous"]["tls"] = {"insecure": True}+ _save_auth_store(store)+ polled_with = []+ real = auth_nous._nous_http_client+ monkeypatch.setattr(auth_nous, "_nous_http_client",+ lambda timeout, verify: polled_with.append(verify) or real(timeout, verify))+ nas.challenge_required = True+ from hermes_cli.auth_nous import resolve_nous_runtime_credentials+ resolve_nous_runtime_credentials()+ assert [p for _, p in nas.calls].count("/api/anonymous/challenge/status") >= 1+ assert polled_with and all(verify is False for verify in polled_with)++ def test_a_stale_status_cannot_hide_a_clearance_from_the_final_mint(self, nas, presented, monkeypatch):+ nas.challenge_required = True+ nas.challenge_never_clears = True+ monkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0)+ original = nas.handler++ def cleared_after_status(request):+ response = original(request)+ if request.url.path.endswith("/challenge/status"):+ nas.challenge_required = False+ return response+ nas.handler = cleared_after_status+ assert _resolve()["api_key"]+ assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2+ assert anon_challenge.pending_challenge() is None+ def test_a_challenge_is_presented_polled_and_the_exchange_retried(self, nas, presented):+ nas.challenge_required = True+ nas.challenge_statuses = ["pending", "pending", "needs_interaction"]+ creds = _resolve()+ assert creds["api_key"]+ assert [c.url for c in presented] == [nas.challenge_url]+ assert presented[0].required and presented[0].message == "A quick check first."+ paths = [p for _, p in nas.calls]+ assert paths.count("/api/anonymous/token") == 2+ # the three scripted states (the first answers "is it already settled?") + the settling "none"+ assert paths.count("/api/anonymous/challenge/status") == 4+ assert anon_challenge.pending_challenge() is None++ def test_the_wait_happens_outside_the_auth_locks(self, nas, monkeypatch):+ """A sibling process must be able to take the shared-store lock while the page runs."""+ from hermes_cli.auth_nous import _nous_shared_store_lock+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]++ def present(_challenge):+ with _nous_shared_store_lock(timeout_seconds=0.5):+ pass+ monkeypatch.setattr(anon_challenge, "_presenter", present)+ assert _resolve()["api_key"]++ def test_status_shows_the_pending_challenge_while_it_is_worked(self, nas, monkeypatch):+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]+ seen = []+ monkeypatch.setattr(anon_challenge, "_presenter", lambda _c: seen.append(anon_challenge.pending_challenge()))+ _resolve()+ assert seen == [{"type": "browser", "url": nas.challenge_url, "required": True,+ "expires_in": 600, "message": "A quick check first.", "attempt": 0}]++ def test_a_challenge_that_never_clears_is_a_retryable_error_not_a_hang(self, nas, presented, monkeypatch):+ nas.challenge_required = True+ nas.challenge_never_clears = True+ monkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0.05)+ monkeypatch.setattr(anon_challenge, "_sleep", lambda _seconds: __import__("time").sleep(0.02))+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED and exc.value.retryable is True+ assert "browser" in str(exc.value)+ # The callers queued behind it fail fast instead of each parking for a full wait.+ from hermes_cli.auth_nous import resolve_nous_runtime_credentials+ with pytest.raises(anon_auth.AuthError):+ resolve_nous_runtime_credentials()+ assert len(presented) == 1++ def test_a_second_challenge_after_the_retry_is_not_looped_on(self, nas, presented):+ nas.challenge_required = True+ nas.challenge_statuses = ["failed"] # the page ruled; the ticket left the waiting states++ original = nas.handler++ def still_challenged(request):+ response = original(request)+ nas.challenge_required = True # NAS keeps answering 428+ return response+ nas.handler = still_challenged+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED+ assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2++ def test_the_managed_tool_token_path_works_a_challenge_too(self, nas, presented):+ from hermes_cli.auth import resolve_nous_access_token+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]+ assert resolve_nous_access_token()+ assert len(presented) == 1+++class TestWhoWaits:+ def test_a_background_caller_announces_and_returns_at_once(self, nas, presented):+ """A keepalive tick or a status paint has nobody waiting on it: no poll, no parked thread."""+ from hermes_cli.auth_nous import resolve_nous_runtime_credentials+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ nas.challenge_required = True+ nas.challenge_never_clears = True+ with anon_challenge.background_caller():+ with pytest.raises(anon_auth.AuthError) as exc:+ resolve_nous_runtime_credentials()+ assert exc.value.code == anon_auth.ANON_CHALLENGE_REQUIRED and exc.value.retryable is True+ assert len(presented) == 1+ assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]+ assert anon_challenge.pending_challenge()["url"] == nas.challenge_url++ def test_a_background_caller_never_prints_or_opens_a_browser(self, monkeypatch, capsys):+ import webbrowser+ monkeypatch.setattr(webbrowser, "open", lambda _url: pytest.fail("opened a browser in the background"))+ challenge = anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=t", True, 600, 2, "A quick check.")+ with anon_challenge.background_caller():+ anon_challenge.present(challenge)+ assert capsys.readouterr().err == ""++ def test_the_keepalive_and_the_status_paint_are_background_callers(self, nas, presented):+ from hermes_cli.auth_nous import _compute_nous_auth_status+ from hermes_cli.nous_auth_keepalive import refresh_nous_auth_keepalive_once+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ nas.challenge_required = True+ nas.challenge_never_clears = True+ assert refresh_nous_auth_keepalive_once() is False+ _compute_nous_auth_status()+ assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]++ def test_a_poll_error_is_a_blip_not_a_verdict(self, nas, presented):+ nas.challenge_required = True+ nas.challenge_status_errors = [429] # the "is it already settled?" read+ nas.challenge_statuses = ["pending"]+ nas.challenge_status_errors += [500]+ assert _resolve()["api_key"]+ assert len(presented) == 1 # the 429 did not skip presenting++ def test_a_desktop_flag_without_a_gateway_falls_back_to_the_terminal(self, monkeypatch, capsys):+ """HERMES_DESKTOP is inherited by CLIs the desktop spawns; with no gateway in this process+ there is nobody to announce to, so the link is printed instead of silently waiting."""+ import sys+ import webbrowser+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ monkeypatch.setenv("SSH_TTY", "/dev/pts/0")+ monkeypatch.delitem(sys.modules, "tui_gateway.server", raising=False)+ monkeypatch.setattr(webbrowser, "open", lambda _url: False)+ anon_challenge.present(anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=t", True, 600, 2, "m"))+ assert f"{PORTAL}/challenge?code=t" in capsys.readouterr().err+++class TestOtherEndpointsAreUnchanged:+ def test_a_428_on_sign_up_is_still_the_proof_of_work_verdict(self, nas):+ nas.create_response = httpx.Response(428, json={"error": "challenge_required", "challenges": []})+ with pytest.raises(anon_auth.AuthError) as exc:+ anon_auth.ensure_portal_identity(explicit=True)+ assert exc.value.code == anon_auth.ANON_POW_REQUIRED++ def test_a_403_on_sign_up_stays_retryable(self, nas):+ nas.create_response = httpx.Response(403, json={"error": "access_denied"})+ with pytest.raises(anon_auth.AuthError) as exc:+ anon_auth.ensure_portal_identity(explicit=True)+ assert exc.value.code == anon_auth.ANON_SERVER_ERROR and exc.value.retryable is True+++class TestWhatIsNeverOpened:+ def test_a_challenge_url_off_the_portal_origin_is_refused(self, nas, presented):+ nas.challenge_required = True+ nas.challenge_url = "https://evil.example/challenge?code=x"+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED and exc.value.retryable is False+ assert presented == []++ @pytest.mark.parametrize("url", [+ "javascript:alert(1)", "file:///etc/passwd", f"{PORTAL}.evil.example/challenge",+ PORTAL.replace("https://", "http://") + "/challenge", "", None])+ def test_same_origin_means_scheme_and_host(self, url):+ payload = {"challenges": [{"type": "browser", "url": url}]}+ assert anon_challenge.parse_browser_challenge(payload, PORTAL) is None++ def test_an_unknown_challenge_type_falls_back_to_sign_in(self, nas, presented):+ nas.token_response = httpx.Response(428, json={+ "error": "challenge_required", "message": "Attest your device.",+ "challenges": [{"type": "attestation-v9", "url": f"{PORTAL}/x"}]})+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED+ assert "Sign in" in str(exc.value) and "Attest" not in str(exc.value)++ def test_an_unknown_428_is_a_sign_in_not_the_proof_of_work_sentence(self, nas):+ nas.token_response = httpx.Response(428, json={"error": "something_new"})+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED+ assert "proof of work" not in str(exc.value)++ @pytest.mark.parametrize("error", ["signin_required", "access_denied"])+ def test_a_refusal_uses_the_services_own_words(self, nas, error):+ nas.token_response = httpx.Response(403, json={"error": error, "message": "Not from here, sorry."})+ with pytest.raises(anon_auth.AuthError) as exc:+ _resolve()+ assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED and str(exc.value) == "Not from here, sorry."++ def test_network_numbers_are_kept_finite_and_sane(self):+ def parsed(expires_in):+ return anon_challenge.parse_browser_challenge(+ {"challenges": [{"type": "browser", "url": f"{PORTAL}/challenge?code=t",+ "expires_in": expires_in}]}, PORTAL)+ assert parsed(float("inf")).expires_in == 600+ assert parsed(10 ** 12).expires_in == 900+ assert parsed(0).expires_in == 30+ assert parsed(True).expires_in == 600+ assert parsed(float("inf")).as_payload()["expires_in"] == 600++ def test_control_characters_never_reach_the_terminal(self):+ assert anon_challenge.server_message("Check\x1b[2J this") == "Check [2J this"+ payload = {"challenges": [{"type": "browser", "url": f"{PORTAL}/challenge?code=\x1b]0;x"}]}+ assert anon_challenge.parse_browser_challenge(payload, PORTAL) is None++ def test_server_copy_is_only_used_when_it_looks_like_copy(self):+ assert anon_challenge.server_message(" Two\n lines ") == "Two lines"+ assert anon_challenge.server_message("x" * 301) == ""+ assert anon_challenge.server_message({"not": "text"}) == ""+++class TestOptionalChallenge:+ def test_a_terminal_never_opens_anything_for_an_optional_challenge(self, nas, presented, monkeypatch):+ announced = []+ monkeypatch.setattr(anon_challenge, "_announce", announced.append)+ nas.optional_challenge = True+ assert _resolve()["api_key"]+ assert presented == [] and announced == []++ def test_the_desktop_backend_announces_it_and_waits_on_nothing(self, nas, presented, monkeypatch):+ announced = []+ monkeypatch.setattr(anon_challenge, "_announce", announced.append)+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ nas.optional_challenge = True+ assert _resolve()["api_key"]+ assert [c.required for c in announced] == [False]+ assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]+ assert anon_challenge.pending_challenge()["url"] == nas.challenge_url++ def test_replayed_offers_keep_the_original_expiry_and_old_results_cannot_end_a_retry(self, nas, monkeypatch):+ clock = [100.0]+ monkeypatch.setattr(anon_challenge.time, "monotonic", lambda: clock[0])+ challenge = anon_challenge.BrowserChallenge(nas.challenge_url, False, 60, 2, "check")+ anon_challenge._set_pending(challenge)+ clock[0] += 20+ anon_challenge._set_pending(challenge)+ assert anon_challenge.pending_challenge()["expires_in"] == 40+ retry = anon_challenge._set_pending(challenge, new_attempt=True)+ assert not anon_challenge.record_host_outcome(challenge.url, 0, "done")+ assert anon_challenge.pending_challenge()["attempt"] == retry.attempt+ clock[0] += 41+ assert anon_challenge.pending_challenge() is None+++class TestPresenting:+ def test_the_desktop_backend_announces_and_never_opens_a_browser(self, monkeypatch):+ announced, opened = [], []+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ monkeypatch.setattr(anon_challenge, "_announce", lambda c: announced.append(c) or True)+ monkeypatch.setattr(anon_challenge, "_present_in_terminal", opened.append)+ challenge = anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=t", True, 600, 2, "m")+ anon_challenge.present(challenge)+ assert announced == [challenge] and opened == []++ def test_a_terminal_opens_one_tab_per_ticket_however_many_attempts_resume_it(self, monkeypatch, capsys):+ import webbrowser+ from hermes_cli import auth_device_flow+ opened = []+ monkeypatch.setattr(auth_device_flow, "_is_remote_session", lambda: False)+ monkeypatch.setattr(auth_device_flow, "_can_open_graphical_browser", lambda: True)+ monkeypatch.setattr(webbrowser, "open", lambda url: opened.append(url) or True)+ challenge = anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=once", True, 600, 2, "m")+ anon_challenge.present(challenge)+ anon_challenge.present(challenge)+ assert opened == [challenge.url]+ assert capsys.readouterr().err.count(challenge.url) == 2 # the link is always shown++ def test_a_terminal_prints_the_link_and_skips_the_browser_over_ssh(self, monkeypatch, capsys):+ import webbrowser+ monkeypatch.setenv("SSH_TTY", "/dev/pts/0")+ monkeypatch.setattr(webbrowser, "open", lambda _url: pytest.fail("opened a browser over SSH"))+ challenge = anon_challenge.BrowserChallenge(f"{PORTAL}/challenge?code=t", True, 600, 2, "A quick check.")+ anon_challenge.present(challenge)+ err = capsys.readouterr().err+ assert "A quick check." in err and f"{PORTAL}/challenge?code=t" in errdiff --git a/tests/tui_gateway/contracts/test_generated.py b/tests/tui_gateway/contracts/test_generated.pyindex b74d813960a..b971ab87ee6 100644--- a/tests/tui_gateway/contracts/test_generated.py+++ b/tests/tui_gateway/contracts/test_generated.py@@ -45,6 +45,7 @@ _SUBAGENT_RELAY = re.compile(r"\"(subagent\.[a-z_]+)\"")_DESKTOP_UI_EMIT = re.compile(r"desktop_ui\.(?:emit|emit_or_error)\(\s*\"([a-z_][a-z0-9_.]*)\"")_BROKER_FRAME = re.compile(r"^FRAME_[A-Z_]+ = \"(browser\.controller\.[a-z_]+)\"", re.M)_SETUP_READY = re.compile(r"^SETUP_READY_EVENT = \"([a-z_.]+)\"", re.M)+_FREE_TIER_CHALLENGE = re.compile(r"^CHALLENGE_EVENT = \"([a-z_.]+)\"", re.M)def _read(path: Path) -> str:@@ -72,6 +73,7 @@ def emitted_event_names() -> set[str]:names.update(_DESKTOP_UI_EMIT.findall(_read(src)))names.update(_BROKER_FRAME.findall(_read(REPO / "gateway" / "browser_control_broker.py")))names.update(_SETUP_READY.findall(_read(REPO / "hermes_cli" / "free_tier_bootstrap.py")))+ names.update(_FREE_TIER_CHALLENGE.findall(_read(REPO / "hermes_cli" / "anon_challenge.py")))return namesdiff --git a/tests/tui_gateway/test_free_tier_rpc.py b/tests/tui_gateway/test_free_tier_rpc.pyindex 9f3d5ddad65..770ba1c5ca1 100644--- a/tests/tui_gateway/test_free_tier_rpc.py+++ b/tests/tui_gateway/test_free_tier_rpc.py@@ -77,6 +77,40 @@ def test_status_is_pull_from_local_state_and_ack_persists_on_the_identity(guest,assert status["available"] is False and status["notice_pending"] is False+def test_status_carries_the_pending_browser_challenge_and_drops_it_once_cleared(guest):+ """A client that connects after the ``free_tier.challenge`` event still learns there is a+ window to open; once the challenge is worked, the field is gone."""+ from hermes_cli import anon_challenge+ assert "challenge" not in _call("free_tier.status")++ challenge = anon_challenge.BrowserChallenge(+ "https://portal.example.test/challenge?code=t", True, 600, 2, "A quick check first.")+ anon_challenge._set_pending(challenge)+ try:+ assert _call("free_tier.status")["challenge"] == challenge.as_payload()+ finally:+ anon_challenge._clear_pending()+ assert "challenge" not in _call("free_tier.status")+++def test_window_outcomes_are_scoped_and_do_not_grant_auth(guest, tmp_path):+ from hermes_cli import anon_challenge+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override+ a = anon_challenge.BrowserChallenge("https://portal.example.test/challenge?code=a", True, 600, 2, "check")+ b = anon_challenge.BrowserChallenge("https://portal.example.test/challenge?code=b", False, 600, 2, "check")+ anon_challenge._set_pending(a)+ scope = set_hermes_home_override(tmp_path / "secondary")+ try:+ anon_challenge._set_pending(b)+ assert not anon_challenge.record_host_outcome(a.url, 0, "done")+ assert anon_challenge.pending_challenge()["url"] == b.url+ finally:+ reset_hermes_home_override(scope)+ assert _call("free_tier.status")["challenge"]["url"] == a.url+ assert _call("free_tier.challenge_result", {"url": a.url, "outcome": "error"}) == {"accepted": True}+ assert _call("free_tier.status")["challenge"]["url"] == a.url++def test_billing_state_answers_the_free_tier_locally(guest, monkeypatch):import agent.billing_view as bvmonkeypatch.setattr(bv, "build_billing_state", lambda *a, **kw: pytest.fail("free tier must not call the portal"))diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.pyindex cbcec20a82a..30f81c2a098 100644--- a/tui_gateway/contracts/config_free_tier_control.py+++ b/tui_gateway/contracts/config_free_tier_control.py@@ -181,6 +181,19 @@ method("diagnostics.share_nous", params=DiagnosticsShareNousParams, result=Diagn# ── free tier ─────────────────────────────────────────────────────────────────────────────────+class FreeTierChallengePayload(OpenModel):+ """``hermes_cli/anon_challenge.py::BrowserChallenge.as_payload``: the ``free_tier.challenge``+ event, and ``free_tier.status``'s ``challenge`` field for a client that connected after it."""++ type: Literal["browser"]+ url: str+ # False = the account service is measuring, not enforcing: run it hidden, never reveal it.+ required: bool+ expires_in: int+ message: str+ attempt: int = 0++class FreeTierStatusResult(Result):"""``available`` = an identity exists AND the tier is on; whether inference runs on it is``setup.runtime_check.free_tier_route``'s question."""@@ -195,12 +208,28 @@ class FreeTierStatusResult(Result):error_code: str | None = Noneretryable: bool | None = Noneretry_after: int | None = None+ # A browser challenge the account service is waiting on (``hermes_cli/anon_challenge.py``).+ challenge: FreeTierChallengePayload | None = Nonemethod("free_tier.status", params=ProfileParams, result=FreeTierStatusResult,doc="Pure read of the focused profile's free-tier identity state (no network, no side effects).")+class FreeTierChallengeResultParams(ProfileParams):+ url: str+ attempt: int = 0+ outcome: Literal["done", "failed", "closed", "timeout", "refused", "error", "unsupported"]+++class FreeTierChallengeResult(Result):+ accepted: bool+++method("free_tier.challenge_result", params=FreeTierChallengeResultParams, result=FreeTierChallengeResult,+ doc="Report a browser window outcome for the matching pending attempt; mint remains authoritative.")++class FreeTierProvisionResult(Result):has_guest: boolenabled: booldiff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 7751a1f6189..f6307647e3a 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -19,7 +19,7 @@ from pydantic import Fieldfrom .base import JsonValue, Payload, WireEnumfrom .common import MessageReaction, SessionLiveInfo, SubagentStatus, ToolLabel, ToolLabelKind, Usage-from .config_free_tier_control import SessionControlSnapshot+from .config_free_tier_control import FreeTierChallengePayload, SessionControlSnapshotfrom .registry import event@@ -84,6 +84,11 @@ event("setup.ready", SetupReadyPayload,doc="The free-tier bootstrap finished (broadcast); the desktop's setup gate reads the record.")+event("free_tier.challenge", FreeTierChallengePayload,+ doc="The account service wants a browser challenge cleared before the free-tier token exchange "+ "(broadcast); the desktop loads ``url`` in a hidden window.")++class ErrorPayload(Payload):"""Every ``_emit("error", …)`` site sets exactly ``message``."""@@ -738,7 +743,7 @@ __all__ = ["BillingBlock", "BillingStepUpVerificationPayload", "BrowserControllerCancelPayload","BrowserControllerCommandPayload", "BrowserProgressPayload", "ChangeSignalPayload", "ErrorPayload","ErrorSurface", "GatewayReadyPayload", "LayoutApplyPayload", "MessageCompletePayload",- "MessageInterimPayload", "MessageReaction", "MessageReactionPayload", "MoaAggregatingPayload",+ "FreeTierChallengePayload", "MessageInterimPayload", "MessageReaction", "MessageReactionPayload", "MoaAggregatingPayload","MoaPhasePayload", "MoaProgressPayload", "MoaReferencePayload", "NoticePayload","NotificationClearPayload", "NotificationShowPayload", "OpenPayload", "PaneRevealPayload","PetChangedPayload", "PetGenerateProgressPayload", "PetHatchProgressPayload", "PreviewClosePayload",diff --git a/tui_gateway/methods_free_tier.py b/tui_gateway/methods_free_tier.pyindex a461d1face7..8dcab19070c 100644--- a/tui_gateway/methods_free_tier.py+++ b/tui_gateway/methods_free_tier.py@@ -1,8 +1,9 @@-"""Nous free-tier JSON-RPC handlers: a renderer reads the profile's local auth state (pull); nothing-is pushed except the boot bootstrap's one ``setup.ready`` event. ``free_tier.status`` answers from the+"""Nous free-tier JSON-RPC handlers. ``free_tier.status`` answers from theauth store with zero network and zero side effects; ``free_tier.provision`` is the explicit retry whenthe boot bootstrap could not create the identity (desktop-only entry); ``free_tier.ack_notice``persists the one-time notice flag on the free-tier identity itself, so it dies with that identity.+``free_tier.challenge_result`` records a presentation hint for the pending attempt; the+backend still exchanges with the portal to determine whether the credential is cleared.Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare."""@@ -39,6 +40,12 @@ def _(rid, params: dict) -> dict:# Why there is no identity, when the last attempt to make one failed:# ``{error, error_code, retryable, retry_after}`` (the mint memo's verdict).payload.update(anon_auth.last_mint_failure() or {})+ # A browser challenge the account service is waiting on (``anon_challenge``): the same+ # payload the ``free_tier.challenge`` event carried, for a client that connected after it.+ from hermes_cli import anon_challenge+ challenge = anon_challenge.pending_challenge()+ if challenge:+ payload["challenge"] = challengereturn _ok(rid, payload)except Exception as e:return _err(rid, 5090, str(e))@@ -88,5 +95,12 @@ def _(rid, params: dict) -> dict:return _err(rid, 5091, str(e))+@method("free_tier.challenge_result")+@_profile_scoped+def _(rid, params: dict) -> dict:+ from hermes_cli.anon_challenge import record_host_outcome+ return _ok(rid, {"accepted": record_host_outcome(params["url"], params.get("attempt", 0), params["outcome"])})++def register(server) -> None:bind_module(globals(), server, skip=("_",))