mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
fix(claude): stop locking Claude sessions to three hard-coded model aliases (#1948)
* feat(shared): derive Claude model choices from the CLI catalog The choices are the rows of the claude CLI's own /model picker, in its order and with its display names. The stored value is what claude --model receives: an alias is resolved again each time the session's claude process starts, a full id stays on its model, so following and staying need no new field. Effort support is read per model so a model switch can drop an effort level the next model does not offer. * feat(cli): discover Claude models from the CLI's initialize response A machine RPC starts claude in stream-json mode, sends only an initialize control request and reads the models it reports, so no turn runs and no transcript is written. claude --print runs a directory's project hooks and .mcp.json servers without a trust prompt, so the probe starts from the home directory with user settings only, no MCP servers and hooks disabled. Successful catalogs are cached per claude executable for five minutes and concurrent requests share one probe; failures are not cached. * feat(hub): expose the Claude model catalog per machine GET /machines/:id/claude-models forwards to the runner's listClaudeModels RPC. A runner that predates the handler answers with the stable rpc_target_missing code so clients can keep their built-in list. * feat(web): offer the machine's Claude models in the model pickers The composer and the create-session form list the rows the machine's claude CLI shows in its own /model picker, as it shows them. Built-in presets the catalog does not list remain selectable after it. Until the catalog arrives, or on a runner without discovery, the built-in presets are shown as before. A saved Claude model is no longer reset to Default when the built-in list lacks it; the create-session form keeps it and marks it as no longer listed when the catalog dropped it. * feat(hub,web): keep Claude effort within what the selected model offers For Claude sessions the model endpoint accepts an optional effort, so a model switch and the effort it keeps reach the session as one config change. Other flavors are refused: Pi, for one, commits the model before its thinking level. When the machine's catalog says the next Claude model does not offer the current effort, the composer clears it in that same request. The create-session form drops such an effort however the model was set, including a restored preference or draft. Effort choices in both places narrow to the selected model's levels; without a catalog every level stays available as before. * fix(web): retry Claude model discovery after a failed probe The machine answers a failed probe with success:false over HTTP 200. The query cached that as an answer for its stale time, so a user who signed in and reopened a picker within a minute still saw only the built-in models. A failed probe is now a query error, which is not kept, and the next picker to mount asks the machine again. * fix(web): list only the Claude CLI's models once its catalog is known The built-in presets were kept after the catalog so that a partial list could not hide Opus. The catalog is the CLI's own /model list, though, not a partial one, and the presets added entries the CLI does not show (Sonnet 1M, Opus 1M, Fable 1M). With a catalog the list is now exactly its rows; a saved model it does not list stays as the current model, and New Session marks it as no longer listed. Without a catalog the built-in presets are shown as before. * fix(shared,web): list earlier Claude versions under Other models Claude Code's model sheet shows each family's newest model first and every earlier version under an "Other models" heading. The CLI's catalog lists models in that order but does not say where the split is, so the first row of each family is taken as its newest and later rows of the same family as earlier versions. The composer's model list and New Session's model select now show the same two groups, keeping the CLI order within each. Nothing is folded: every row stays one click away, as it does in Claude Code. * test(web): pin that Claude 1M variants come from the CLI catalog Claude Code 2.1.105, 2.1.200, 2.1.240 and 2.1.274 list a 1M choice as its own catalog row (opus[1m], claude-fable-5[1m]); 2.1.303 and 2.1.310 list none, and on 2.1.310 opus and sonnet run with a 1M context window. The catalog-only list therefore offers a 1M variant exactly when the CLI does. Pin that and record why the built-in [1m] presets are not appended.
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { homedir } from 'node:os'
|
||||
import type { ClaudeModelSummary, ClaudeModelsResponse } from '@hapi/protocol/apiTypes'
|
||||
import { getDefaultClaudeCodePath } from '@/claude/sdk/utils'
|
||||
import { withBunRuntimeEnv } from '@/utils/bunRuntime'
|
||||
import { killProcessByChildProcess } from '../../utils/process'
|
||||
import { getErrorMessage } from './rpcResponses'
|
||||
|
||||
export type ListClaudeModelsRequest = Record<string, never>
|
||||
|
||||
export type ListClaudeModelsResponse = ClaudeModelsResponse
|
||||
|
||||
interface CacheEntry {
|
||||
expiresAt: number
|
||||
response: ListClaudeModelsResponse
|
||||
}
|
||||
|
||||
// The catalog changes rarely (a CLI update, a different login, an alias the
|
||||
// service moves to a newer model) and each probe starts a full claude process
|
||||
// (~0.75s), so a successful answer is kept for a few minutes. Failures are not
|
||||
// cached: a user who just logged in should not wait out the TTL.
|
||||
const CACHE_TTL_MS = 5 * 60_000
|
||||
const PROBE_TIMEOUT_MS = 15_000
|
||||
const PROBE_REQUEST_ID = 'hapi-claude-models-probe'
|
||||
const cache = new Map<string, CacheEntry>()
|
||||
const inflight = new Map<string, Promise<ListClaudeModelsResponse>>()
|
||||
|
||||
/**
|
||||
* Machine-level discovery of the models the `claude` CLI offers, read from the
|
||||
* `models` field of its `initialize` control response. No prompt is sent, so
|
||||
* the probe starts no turn and writes no transcript.
|
||||
*
|
||||
* `claude --print` loads the working directory's `.claude/settings*.json` and
|
||||
* `.mcp.json` without a workspace trust prompt, so any project hook or MCP
|
||||
* server there would run. The probe therefore runs from the home directory
|
||||
* and loads only user settings, no MCP servers, and no hooks at all (the
|
||||
* user's own hooks would otherwise fire on every catalog refresh).
|
||||
*
|
||||
* User settings stay loaded so the probe sees the same `env` a session does
|
||||
* (e.g. `ANTHROPIC_DEFAULT_OPUS_MODEL` changes what `opus` resolves to).
|
||||
* Project settings that redefine model aliases are ignored here, so in such
|
||||
* a directory the catalog can differ from what the session resolves.
|
||||
*/
|
||||
const CLAUDE_MODELS_PROBE_ARGS = [
|
||||
'--print',
|
||||
'--input-format', 'stream-json',
|
||||
'--output-format', 'stream-json',
|
||||
'--verbose',
|
||||
'--setting-sources', 'user',
|
||||
'--strict-mcp-config',
|
||||
'--settings', JSON.stringify({ disableAllHooks: true }),
|
||||
] as const
|
||||
|
||||
export type ClaudeModelsProbeLineResult =
|
||||
| { kind: 'models'; models: ClaudeModelSummary[] }
|
||||
| { kind: 'error'; error: string }
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value.trim() ? value : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* A row without `supportsEffort` (or with `null`) has no effort control, but
|
||||
* only when the CLI reports effort support at all: a CLI that predates the
|
||||
* field would otherwise hide effort for every model. A model that supports
|
||||
* effort without listing levels keeps them unknown.
|
||||
*/
|
||||
function parseClaudeCatalog(rawModels: unknown): ClaudeModelSummary[] {
|
||||
if (!Array.isArray(rawModels)) {
|
||||
return []
|
||||
}
|
||||
const rows = rawModels.map(asRecord).filter((row): row is Record<string, unknown> => row !== null)
|
||||
const reportsEffortSupport = rows.some((row) => 'supportsEffort' in row)
|
||||
const models: ClaudeModelSummary[] = []
|
||||
for (const row of rows) {
|
||||
const value = optionalString(row.value)
|
||||
if (!value) {
|
||||
continue
|
||||
}
|
||||
const model: ClaudeModelSummary = { value }
|
||||
const displayName = optionalString(row.displayName)
|
||||
if (displayName) model.displayName = displayName
|
||||
if (reportsEffortSupport && row.supportsEffort !== true) {
|
||||
model.effortLevels = []
|
||||
} else if (Array.isArray(row.supportedEffortLevels)) {
|
||||
model.effortLevels = row.supportedEffortLevels.filter((level): level is string => typeof level === 'string')
|
||||
}
|
||||
models.push(model)
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
/** Scans one stdout line for the answer to the probe's initialize request. */
|
||||
export function parseClaudeModelsProbeLine(line: string): ClaudeModelsProbeLineResult | null {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed.startsWith('{')) return null
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(trimmed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const message = asRecord(parsed)
|
||||
if (message?.type !== 'control_response') return null
|
||||
const response = asRecord(message.response)
|
||||
if (response?.request_id !== PROBE_REQUEST_ID) return null
|
||||
if (response.subtype !== 'success') {
|
||||
return { kind: 'error', error: optionalString(response.error) ?? 'Claude rejected the model probe request' }
|
||||
}
|
||||
return { kind: 'models', models: parseClaudeCatalog(asRecord(response.response)?.models) }
|
||||
}
|
||||
|
||||
function runClaudeModelsProbe(executable: string): Promise<ListClaudeModelsResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(executable, [...CLAUDE_MODELS_PROBE_ARGS], {
|
||||
cwd: homedir(),
|
||||
env: withBunRuntimeEnv(process.env, { allowBunBeBun: false }),
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
// getDefaultClaudeCodePath resolves an absolute path (claude.exe on
|
||||
// Windows), matching how sessions spawn it.
|
||||
shell: false,
|
||||
windowsHide: process.platform === 'win32',
|
||||
})
|
||||
let stdoutBuffer = ''
|
||||
let stderr = ''
|
||||
let settled = false
|
||||
|
||||
// The claude process stays up waiting for input, so every outcome
|
||||
// stops it before the caller sees a result.
|
||||
const finish = (settle: () => void) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
void (async () => {
|
||||
if (!child.pid) {
|
||||
settle()
|
||||
return
|
||||
}
|
||||
let stopped = false
|
||||
try {
|
||||
stopped = await killProcessByChildProcess(child, false)
|
||||
|| await killProcessByChildProcess(child, true)
|
||||
} catch {
|
||||
stopped = false
|
||||
}
|
||||
if (!stopped) {
|
||||
reject(new Error(`Claude model probe could not be stopped (pid ${child.pid})`))
|
||||
return
|
||||
}
|
||||
settle()
|
||||
})()
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
finish(() => reject(new Error('Claude model discovery timed out')))
|
||||
}, PROBE_TIMEOUT_MS)
|
||||
|
||||
child.stdout?.on('data', (chunk) => {
|
||||
stdoutBuffer += chunk.toString()
|
||||
let newlineIndex = stdoutBuffer.indexOf('\n')
|
||||
while (newlineIndex !== -1 && !settled) {
|
||||
const line = stdoutBuffer.slice(0, newlineIndex)
|
||||
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1)
|
||||
newlineIndex = stdoutBuffer.indexOf('\n')
|
||||
const result = parseClaudeModelsProbeLine(line)
|
||||
if (result === null) continue
|
||||
if (result.kind === 'error') {
|
||||
finish(() => reject(new Error(result.error)))
|
||||
return
|
||||
}
|
||||
if (result.models.length === 0) {
|
||||
finish(() => reject(new Error('Claude reported no models')))
|
||||
return
|
||||
}
|
||||
finish(() => resolve({ success: true, availableModels: result.models }))
|
||||
return
|
||||
}
|
||||
})
|
||||
child.stderr?.on('data', (chunk) => {
|
||||
stderr += chunk.toString()
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
finish(() => reject(error))
|
||||
})
|
||||
child.on('close', (code) => {
|
||||
finish(() => reject(new Error(
|
||||
stderr.trim() || `claude exited with code ${code ?? 'unknown'} before answering the model probe`
|
||||
)))
|
||||
})
|
||||
// An early exit surfaces through 'close', not as an unhandled EPIPE.
|
||||
child.stdin?.on('error', () => { /* handled via close */ })
|
||||
child.stdin?.write(`${JSON.stringify({
|
||||
type: 'control_request',
|
||||
request_id: PROBE_REQUEST_ID,
|
||||
request: { subtype: 'initialize' },
|
||||
})}\n`)
|
||||
})
|
||||
}
|
||||
|
||||
/** Clear the module-level probe cache and in-flight map between tests. */
|
||||
export function _resetClaudeModelsCacheForTests(): void {
|
||||
cache.clear()
|
||||
inflight.clear()
|
||||
}
|
||||
|
||||
/** Throws on failure; the RPC handler turns that into an error response. */
|
||||
export async function listClaudeModels(): Promise<ListClaudeModelsResponse> {
|
||||
// Keyed by executable: HAPI_CLAUDE_PATH can point a runner at a different
|
||||
// claude install, whose catalog is its own.
|
||||
const executable = getDefaultClaudeCodePath()
|
||||
const now = Date.now()
|
||||
const cached = cache.get(executable)
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.response
|
||||
}
|
||||
|
||||
const existing = inflight.get(executable)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
const pending = runClaudeModelsProbe(executable)
|
||||
.then((response) => {
|
||||
cache.set(executable, { expiresAt: Date.now() + CACHE_TTL_MS, response })
|
||||
return response
|
||||
})
|
||||
.catch((error) => {
|
||||
throw new Error(getErrorMessage(error, 'Failed to list Claude models'))
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(executable)
|
||||
})
|
||||
inflight.set(executable, pending)
|
||||
return pending
|
||||
}
|
||||
Reference in New Issue
Block a user