Skip to content

Model discovery: live /v1/models lookup + cache + onboarding picker - #171

Merged
FMXExpress merged 2 commits into
mainfrom
claude/model-discovery
Jun 7, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/model-discovery

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Lifts the "use the provider's /models endpoint" idea from UltraCode-Shim's Auto Router (and the carry-over question from PR #163) into a complete loop: discover, cache, surface in onboarding.

Before:

$ pasclaw onboard
Default model [claude-opus-4-7]: _

After (when the live fetch succeeds):

$ pasclaw onboard
Fetching available models from Anthropic ...
Available models (showing 12 of 47, newest first):
  1) claude-opus-4-7   (Claude Opus 4.7)
  2) claude-sonnet-4-6  (Claude Sonnet 4.6)
  3) claude-haiku-4-5   (Claude Haiku 4.5)
  ...
  (+ 35 more — see `pasclaw model list anthropic`)
Pick a number, type a name, or Enter for default [claude-opus-4-7]: _

New unit: src/pkg/providers/PasClaw.Providers.Models.pas

Three family parsers driven off TProviderSpec.Family:

Family Endpoint Auth Catalog rows covered
pfOpenAI GET <base>/v1/models Bearer (or asNone for Ollama/vLLM/LM Studio) openai, openrouter, groq, deepseek, mistral, xai, qwen, zhipu, cerebras, moonshot, ollama, vllm, lmstudio, litellm — 14 rows share one parser
pfAnthropic GET <base>/v1/models x-api-key + anthropic-version anthropic
pfGemini GET <base>/v1beta/models x-goog-api-key gemini (strips models/ prefix; filters out non-generateContent rows so embedders / counters don't pollute the picker)

Cache lives at $PASCLAW_HOME/cache/models/<provider>.json with a fetched_at timestamp. JoinPath built up segment-by-segment so the Windows PathDelim insertion stays consistent (PR #169 trap).

Discovery never raises. Failure modes return Ok=False with a human-readable ErrMsg the caller surfaces verbatim. Empty result is Ok=True with Length=0 (caller's call whether to retry).

New subcommands

pasclaw model refresh <provider>     hit /v1/models, save cache
pasclaw model refresh --all          refresh every configured row
pasclaw model list <provider>        show cached roster + age

pasclaw model show now adds a cache-freshness annotation:

default provider: anthropic
default model:    claude-opus-4-7
models cached:    47 (refreshed 3 days ago)

or the gentle nudge when no cache exists yet:

models cached:    (none — run `pasclaw model refresh anthropic` to populate)

Onboarding picker

Flipped prompt order: API key first, model second. The fetched key feeds the /v1/models call; the 8-second timeout means a slow provider status page can't make the user wait 30s. On success: numbered picker over the top 12 newest models (sorted created_at desc), with the option to type a free-form id or hit Enter for the catalog default. On failure: falls back to the existing text prompt verbatim so a broken /v1/models never blocks first-time setup.

Both the full result AND the sort-truncated view get cached, so pasclaw model list <provider> later shows the whole roster even though the onboarding picker only displayed the top 12.

Tests

New src/tests/model_discovery_tests.pas covers:

  • Cache schema contract — Save → Load preserves every field
  • Missing-cache fallback — LoadCachedModels returns False (not True with empty array)
  • HumanAge bucket boundaries (minutes / hours / days / over-a-year cap)
  • ModelCachePath case-insensitive canonicalisation

Wired into make test as test-model-discovery. All 11 test suites green.

Verified

$ pasclaw model show
  default provider: anthropic
  default model:    claude-opus-4-7
  models cached:    (none — run `pasclaw model refresh anthropic` to populate)

$ pasclaw model refresh anthropic        # no key
    · fetching /models from Anthropic ...
    ✗ anthropic: API key required for Anthropic /models endpoint

$ # synthesised cache file → list works:
$ pasclaw model list openai
  openai (3 cached, refreshed over a year ago)
    · gpt-4o   (GPT-4o)
    · gpt-4o-mini   (GPT-4o Mini)
    · gpt-5   (GPT-5)
  • FPC build clean on Linux.
  • Full test suite green: smoke + hashline + toolview + anthropic-server-tools + openai-server-tools + println-helper + utf8-codepage-tag + gemini-schema-strip + markdown-render + json-utf8-roundtrip + model-discovery.
  • PasClaw.Providers.Models registered in PasClaw.dproj so the Delphi build resolves it too (PR Register PasClaw.Markdown.Render in PasClaw.dproj (dcc64 F2613 fix) #156 / Delphi dproj + PR #166 review fix (status checks ONNX Runtime) #167 pattern).
  • README maintenance section updated with the new subcommand surface.
  • Live /v1/models fetch against real Anthropic / OpenAI / Gemini / xAI keys — not available in this CI environment. The parser tests cover the JSON shapes documented in each provider's current API reference.

Generated by Claude Code

Lifts the "use the provider's /models endpoint" idea from
UltraCode-Shim's Auto Router (and the carry-over from PR #163's
followup question) into a complete loop: discover, cache, surface
in onboarding.

New unit: src/pkg/providers/PasClaw.Providers.Models.pas

  Three family parsers driven off TProviderSpec.Family:

    pfOpenAI     GET <base>/v1/models, Bearer auth (or asNone for
                 Ollama / vLLM / LM Studio). Parses `data[].id` +
                 `data[].created`. Used by 14 catalog rows that share
                 the OpenAI-compatible /v1/models shape — openrouter,
                 groq, deepseek, mistral, xai, qwen, zhipu, cerebras,
                 moonshot, ollama, vllm, lmstudio, litellm, openai.

    pfAnthropic  GET <base>/v1/models, x-api-key + anthropic-version
                 headers. Parses `data[].id` + `display_name` + ISO
                 `created_at`.

    pfGemini     GET <base>/v1beta/models, x-goog-api-key header.
                 Strips the "models/" namespace prefix from each
                 `name`, filters out rows that don't list
                 "generateContent" in supportedGenerationMethods
                 (embedders and counters live there too and would
                 404 the chat path).

  Cache at $PASCLAW_HOME/cache/models/<provider>.json with a
  fetched_at unix timestamp. JoinPath built up segment-by-segment
  so PathDelim insertion stays consistent on Windows (PR #169 trap).

  Discovery never raises; failure modes return Ok=False with a
  human-readable ErrMsg the caller surfaces verbatim. Empty result
  is Ok=True with Length=0 (the operator's call whether to retry).

New subcommands: src/cmd/PasClaw.Cmd.Model.pas

    pasclaw model refresh <provider>     hit /v1/models, save cache
    pasclaw model refresh --all          refresh every configured row
    pasclaw model list <provider>        show cached roster + age

  `pasclaw model show` now adds a cache-freshness annotation for the
  default provider — "models cached: 47 (refreshed 3 days ago)" or
  the gentle nudge "(none — run `pasclaw model refresh anthropic`
  to populate)" when no cache exists yet.

Onboarding picker: src/cmd/PasClaw.Cmd.Onboard.pas

  Flipped the order: now prompts for the API key BEFORE the model,
  so the key is available for the /v1/models fetch. Live fetch is
  bounded at 8s — onboarding is interactive, a slow provider status
  page shouldn't make the user wait 30s. On success: numbered
  picker over the top 12 newest models (sorted by created_at desc),
  with the option to type a free-form id or hit Enter for the
  catalog default. On failure: falls back to the existing text
  prompt verbatim so a broken /v1/models never blocks first-time
  setup.

  Both the full result AND a sort-truncated view get cached, so
  `pasclaw model list <provider>` later shows the whole roster
  even though the onboarding picker only displayed the top 12.

New test: src/tests/model_discovery_tests.pas

  Covers the cache schema contract (Save → Load round-trip preserves
  every field), missing-cache fallback (LoadCachedModels returns
  False, NOT True-with-empty-array), HumanAge bucket boundaries
  (minutes / hours / days / over-a-year cap), and case-insensitive
  ModelCachePath canonicalisation. Wired into `make test` as
  test-model-discovery.

Updated:
  - src/pasclaw/PasClaw.dproj: registers PasClaw.Providers.Models
    so the Delphi build resolves it too (PR #156 / #167 pattern).
  - README.md: maintenance section adds `model refresh` / `model list`
    examples + explains the onboarding picker behaviour.
  - Makefile: adds test-model-discovery target and rolls it into the
    composite `test:` target.

Verified end-to-end on Linux/FPC:

  $ pasclaw model show
    default provider: anthropic
    default model:    claude-opus-4-7
    models cached:    (none — run `pasclaw model refresh anthropic` to populate)

  $ pasclaw model refresh anthropic        # without a real key
      · fetching /models from Anthropic ...
      ✗ anthropic: API key required for Anthropic /models endpoint

  $ # synthesised cache file → list works:
  $ pasclaw model list openai
    openai (3 cached, refreshed over a year ago)
      · gpt-4o   (GPT-4o)
      · gpt-4o-mini   (GPT-4o Mini)
      · gpt-5   (GPT-5)

  $ make test
    ... all 11 test suites green including model_discovery_tests: OK

Live-HTTP verification against real Anthropic / OpenAI / Gemini /
xAI keys hasn't run in this environment (no real keys), but the
parser tests cover the JSON shapes documented in each provider's
current API reference.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cd0c095dc8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cmd/PasClaw.Cmd.Model.pas Outdated
'" — run `pasclaw auth login ' + Name + '` first';
Exit;
end;
if not LookupProvider(Cfg.Providers[Idx].Kind, Spec) then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize provider kind before lookup

For configured providers whose Kind is the legacy openai-compat alias, or whose Kind is blank and only Name is set, the runtime factory still works because it normalizes/falls back before catalog lookup, but this new refresh path looks up the raw Kind and reports it as unknown. In that context pasclaw model refresh <provider> cannot populate discovery cache for providers that can otherwise chat normally; mirror the factory's normalization/name fallback here.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Model.pas Outdated
PrintLn(' ' + Ansi.Red + '✗ ' + Ansi.Reset + Name + ': ' + R.ErrMsg);
Exit;
end;
SaveCachedModels(Spec.Kind, R);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Key model caches by provider name

When a config has two named provider entries with the same catalog Kind but different APIBase/keys, this writes both refreshes to the same <kind>.json cache. The factory resolves providers by Name, so this is a supported configuration; refreshing one provider can overwrite the other's roster and model list/show can then surface models from the wrong backend. Use the requested provider name (or another effective-provider cache key) rather than Spec.Kind for named entries.

Useful? React with 👍 / 👎.

Two distinct findings from Codex on PR #171, both real:

P2 #1 — Normalize provider kind before lookup.
  ResolveSpecForName in PasClaw.Cmd.Model passed the raw
  Cfg.Providers[Idx].Kind to LookupProvider. But NewProviderFromConfig
  in PasClaw.Providers.Factory routes through NormalizeProviderKind
  (lowercase + trim + collapse "openai-compat" → "openai") and falls
  back to Cfg.Providers[Idx].Name when Kind is blank. Configs that
  the runtime factory resolves cleanly were rejected here as "unknown
  kind", so `pasclaw model refresh openai-compat-thing` couldn't
  populate the cache for providers that chat normally.

  Fix part 1: export NormalizeProviderKind from PasClaw.Providers.Factory
  (it was internal — IsGenuineOpenAI is already exported alongside).
  Fix part 2: mirror the factory's pattern verbatim in
  ResolveSpecForName — normalise the Kind, fall back to the normalised
  Name when Kind is empty, then look up.

P2 #2 — Key model caches by Provider Name, not Spec.Kind.
  PR #171's cache file path was $PASCLAW_HOME/cache/models/<Kind>.json.
  But NewProviderFromConfig resolves Cfg.Providers[] entries by Name,
  and two named entries (e.g. "openai-primary", "openai-backup") may
  legitimately share a Kind while pointing at different APIBase/keys.
  With the old key, refreshing "openai-primary" would silently
  overwrite "openai-backup"'s roster (and vice versa), making
  `model list` / `model show` surface models from the wrong backend.

  Fix: cache keyed on the operator-facing Provider Name throughout
  the refresh / list / show paths:
    - RefreshOne          → SaveCachedModels(Name, R)
    - DoList              → LoadCachedModels(Argv[1], R)
    - DoShow              → LoadCachedModels(Cfg.DefaultProvider, R)
                            (Cfg.DefaultProvider is a Name reference,
                            not a Kind)
  Onboarding's PickModelInteractive keeps SaveCachedModels(Spec.Kind, R)
  because UpsertProvider sets Name := Spec.Kind for both the upsert
  and insert paths in that file — the invariant holds at onboarding
  time, just documented now so the next reader doesn't undo it.

  Header doc in PasClaw.Providers.Models updated to spell out the
  cache-key contract.

Test coverage (model_discovery_tests):
  - TestCacheKeysDontCollideAcrossNames pins the P2 #2 fix: writing
    different rosters to two Names that share a Kind preserves both.
  - TestKindNormalisationMatchesFactory pins the P2 #1 contract:
    'openai-compat' → 'openai', case + whitespace normalisation,
    empty stays empty so the caller can fall back to Name.

All 11 test suites green: smoke + hashline + toolview +
anthropic-server-tools + openai-server-tools + println-helper +
utf8-codepage-tag + gemini-schema-strip + markdown-render +
json-utf8-roundtrip + model-discovery (now 6 cases).
@FMXExpress
FMXExpress merged commit 3fa08bf into main Jun 7, 2026
FMXExpress added a commit that referenced this pull request Jun 9, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
…w in `model show`

First-user feedback: `pasclaw onboard` was supposed to show a numbered
picker of available models, but only the old "Default model
[gemini-3.5-flash]:" prompt appeared. Two root causes; both fixed.

Cause 1 — re-onboard with existing key.
  The most common onboard flow is the SECOND run, when the user
  already has an API key saved in config.json and just wants to
  tweak something else. The API key prompt says "leave blank to
  skip" so they hit Enter — and PickModelInteractive saw an empty
  key, treated the auth-required provider as unreachable, and
  silently fell through to the text-input prompt without ever
  attempting discovery.

  Fix in Cmd.Onboard.RunOnboard: when the operator's key entry is
  blank, look up the existing key from Cfg.Providers[<Spec.Kind>]
  and pass it to PickModelInteractive as the effective key.
  UpsertProvider already treats Key='' as "preserve existing key"
  so this only affects the discovery path — the saved config is
  unchanged. Prompt copy also flipped from "leave blank to skip"
  to "leave blank to keep existing" so the existing-key path
  reads correctly.

Cause 2 — silent skip when no key available.
  Even when no existing key was present, the picker fell through
  to the text prompt with zero explanation. User saw the bare
  "Default model [...]" line and rightly assumed the picker was
  broken.

  Refactored PickModelInteractive into a four-step pipeline:
    1. Load any cached roster up-front.
    2. If a key is available (entered OR existing), attempt the
       live fetch; on success refresh the cache.
    3. Pick the data source: live > cache > nothing. Live wins;
       cache used when live fails. SourceLabel explains where
       the list came from ("Fetched live", "Showing the cached
       roster (refreshed 3 days ago)", "API key not entered —
       showing the cached roster…").
    4. Only when there's NO live and NO cache do we drop to the
       text-input prompt, and we print an explicit one-liner
       ("API key not entered — using the catalog default. Run
       `pasclaw model refresh <provider>` later …") so the
       operator knows why the picker isn't there.

  Extracted ShowPicker as a helper so the live-vs-cache paths
  share rendering. The cache file is never overwritten by a
  failed live fetch.

Also: `pasclaw model show` enhancement.

  The user had also been running `pasclaw model` looking for a
  list and only saw the cache COUNT, not the contents. Show now
  inlines a top-10 preview directly under the cache-freshness line:

    default provider: anthropic
    default model:    claude-opus-4-7
    models cached:    47 (refreshed 3 days ago)

      · claude-opus-4-8   (Claude Opus 4.8)
      · claude-opus-4-7   (Claude Opus 4.7)
      ...
      (+ 37 more — run `pasclaw model list anthropic` for the full roster)

  Same code path the picker uses; same Provider-Name keying from
  PR FMXExpress#171 Codex P2.

Verified on Linux/FPC:
  - Synthesised cache → `pasclaw model show` renders the inline
    preview (5 models, ordered by created_at desc).
  - Full test suite green: smoke + hashline + toolview +
    anthropic-server-tools + openai-server-tools + println-helper +
    utf8-codepage-tag + gemini-schema-strip + markdown-render +
    json-utf8-roundtrip + model-discovery.
  - Live-key re-onboard path not exercised here (no real Gemini
    key in CI), but the logic is bounded: existing-key lookup is
    a Cfg.Providers walk + APIKey check; failure modes (key absent,
    key empty) cleanly degrade through cache → text-input.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants