From c7708e345a4333ae6ab77232d41cb06f6e311b1e Mon Sep 17 00:00:00 2001 From: onevcat Date: Sat, 28 Nov 2026 10:17:09 +0900 Subject: [PATCH 1/2] Update Codex and Claude profile model suggestions --- .../Domain/AgentRuntime/AgentRuntimeAdapter.swift | 14 +++++++++----- App/Tests/AgentRuntimeAdapterTests.swift | 9 +++++---- docs/components/agent-profiles.md | 3 ++- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/App/Sources/Domain/AgentRuntime/AgentRuntimeAdapter.swift b/App/Sources/Domain/AgentRuntime/AgentRuntimeAdapter.swift index 28b1e9708..e92787b85 100644 --- a/App/Sources/Domain/AgentRuntime/AgentRuntimeAdapter.swift +++ b/App/Sources/Domain/AgentRuntime/AgentRuntimeAdapter.swift @@ -347,8 +347,11 @@ nonisolated private struct CodexRuntimeAdapter: AgentRuntimeAdapter { runtime: .codex, nativeEvents: AgentNativeHookDecoder.nativeEvents(for: .codex) ) - let reasoningEffortSuggestions = ["low", "medium", "high", "xhigh", "max"] + let reasoningEffortSuggestions = ["low", "medium", "high", "xhigh", "max", "ultra"] let modelSuggestions = [ + "gpt-6.2-sol", + "gpt-6.2-astra", + "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-astra", "gpt-6-sol", @@ -451,12 +454,13 @@ nonisolated private struct ClaudeCodeRuntimeAdapter: AgentRuntimeAdapter { ) let reasoningEffortSuggestions = ["low", "medium", "high", "xhigh", "max"] let modelSuggestions = [ - "claude-fable-5-1", + "claude-fable-5-2", "claude-opus-5-5", - "claude-sonnet-5", - "claude-haiku-4-5-20251001", - "claude-fable-5", + "claude-sonnet-5-5", + "claude-haiku-5-5", + "claude-fable-5-1", "claude-opus-5", + "claude-sonnet-5", ] func observe(arguments: [String]) -> AgentLaunchObservation { diff --git a/App/Tests/AgentRuntimeAdapterTests.swift b/App/Tests/AgentRuntimeAdapterTests.swift index aede9d9fd..060828b59 100644 --- a/App/Tests/AgentRuntimeAdapterTests.swift +++ b/App/Tests/AgentRuntimeAdapterTests.swift @@ -340,16 +340,17 @@ struct AgentRuntimeAdapterTests { #expect( codex?.modelSuggestions == [ - "gpt-6.1-sol", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", + "gpt-6.2-sol", "gpt-6.2-astra", "gpt-6.1-terra", "gpt-6.1-sol", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna", + "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", ] ) - #expect(codex?.reasoningEffortSuggestions == ["low", "medium", "high", "xhigh", "max"]) + #expect(codex?.reasoningEffortSuggestions == ["low", "medium", "high", "xhigh", "max", "ultra"]) let claude = AgentRuntimeAdapterRegistry.adapter(for: .claude) #expect( claude?.modelSuggestions == [ - "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5", "claude-haiku-4-5-20251001", - "claude-fable-5", "claude-opus-5", + "claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", + "claude-fable-5-1", "claude-opus-5", "claude-sonnet-5", ] ) #expect(claude?.reasoningEffortSuggestions == ["low", "medium", "high", "xhigh", "max"]) diff --git a/docs/components/agent-profiles.md b/docs/components/agent-profiles.md index 78582e575..bfebfdc41 100644 --- a/docs/components/agent-profiles.md +++ b/docs/components/agent-profiles.md @@ -174,7 +174,8 @@ after choosing the destination agent. **Model** and **Reasoning Effort** offer suggestions and accept custom values supported by your CLI and account. For example, a Codex profile can select -`gpt-6.1-sol` and `max` from the suggestions. Leave either field blank to use +`gpt-6.2-sol` and `ultra` from the suggestions. Not every model accepts every +effort: the Codex `luna` models stop at `max`. Leave either field blank to use the runtime default. Type in the right-aligned value field, or use the adjacent menu to select a suggestion. From c17b5b1cef90a09477d05564093878594146f9e9 Mon Sep 17 00:00:00 2001 From: onevcat Date: Sat, 28 Nov 2026 10:44:42 +0900 Subject: [PATCH 2/2] Read profile model suggestions from the installed agent's model catalog Codex and Claude Code cache their model list in their home folder. The profile editor now reads that list, keeps the agent's order, shows the first models at the top level and the rest under More Models, and falls back to the built-in list when no cache is readable. Reasoning effort suggestions follow the selected model. --- .../AgentRuntime/AgentModelCatalog.swift | 245 ++++++++++++++++++ .../Views/AgentProfileEditorView.swift | 85 ++++-- App/Tests/AgentModelCatalogTests.swift | 181 +++++++++++++ docs/components/agent-profiles.md | 14 +- 4 files changed, 507 insertions(+), 18 deletions(-) create mode 100644 App/Sources/Domain/AgentRuntime/AgentModelCatalog.swift create mode 100644 App/Tests/AgentModelCatalogTests.swift diff --git a/App/Sources/Domain/AgentRuntime/AgentModelCatalog.swift b/App/Sources/Domain/AgentRuntime/AgentModelCatalog.swift new file mode 100644 index 000000000..b4b6ab0f1 --- /dev/null +++ b/App/Sources/Domain/AgentRuntime/AgentModelCatalog.swift @@ -0,0 +1,245 @@ +import Foundation + +/// The model suggestions a profile editor offers for one runtime. When the +/// installed agent has cached its own model catalog, that list wins: it follows +/// the agent's version and account. Otherwise the adapter's built-in list is the +/// fallback. Suggestions never rewrite a model value that a profile already saved. +nonisolated struct AgentModelCatalog: Equatable, Sendable { + nonisolated struct Model: Equatable, Sendable { + let id: String + /// `nil` when the source does not say. An empty list means the model takes + /// no reasoning effort. + let reasoningEfforts: [String]? + + init(id: String, reasoningEfforts: [String]? = nil) { + self.id = id + self.reasoningEfforts = reasoningEfforts + } + } + + enum Source: Equatable, Sendable { + case installedAgent + case builtIn + } + + /// Models shown at the top level of the suggestion menu. + static let primaryLimit = 6 + /// Models shown in the "More Models" submenu. + static let overflowLimit = 24 + + let primary: [Model] + let overflow: [Model] + let source: Source + + /// - Parameters: + /// - models: All models, most relevant first. + /// - primaryCount: How many leading models the source marks as primary. + /// The primary limit still applies. + init(models: [Model], primaryCount: Int, source: Source) { + var seen: Set = [] + let unique = models.filter { !$0.id.isEmpty && seen.insert($0.id).inserted } + let split = min(max(primaryCount, 0), Self.primaryLimit, unique.count) + primary = Array(unique.prefix(split)) + overflow = Array(unique.dropFirst(split).prefix(Self.overflowLimit)) + self.source = source + } + + var allModelIDs: [String] { + (primary + overflow).map(\.id) + } + + /// The reasoning efforts the catalog lists for `modelID`, or `nil` when the + /// model is not in the catalog or the catalog does not say. + func reasoningEfforts(for modelID: String?) -> [String]? { + guard let modelID else { return nil } + return (primary + overflow).first { $0.id == modelID }?.reasoningEfforts + } + + static func builtIn(for runtime: AgentProfileRuntime) -> AgentModelCatalog? { + guard let suggestions = AgentRuntimeAdapterRegistry.profileAdapter(for: runtime)?.modelSuggestions, + !suggestions.isEmpty + else { return nil } + return AgentModelCatalog( + models: suggestions.map { Model(id: $0) }, + primaryCount: primaryLimit, + source: .builtIn + ) + } +} + +// MARK: - Installed agent catalogs + +// Both formats are private caches of the agent CLIs, with no stability promise. +// The parsers read only the fields they need and return nil for anything they +// cannot use, so a format change falls back to the built-in list. + +nonisolated extension AgentModelCatalog { + /// Codex writes `$CODEX_HOME/models_cache.json`. It is the same JSON that + /// `codex debug models` prints. The TUI picker shows the `list` models in + /// `priority` order. + static func parseCodex(_ data: Data) -> AgentModelCatalog? { + guard let cache = try? snakeCaseDecoder.decode(CodexModelCache.self, from: data) else { return nil } + let listed = cache.models.enumerated() + .filter { ($0.element.visibility ?? "list") == "list" } + .sorted { ($0.element.priority ?? .max, $0.offset) < ($1.element.priority ?? .max, $1.offset) } + .map { Model(id: $0.element.slug, reasoningEfforts: $0.element.supportedReasoningLevels?.map(\.effort)) } + guard !listed.isEmpty else { return nil } + return AgentModelCatalog(models: listed, primaryCount: primaryLimit, source: .installedAgent) + } + + /// Claude Code writes `$CLAUDE_CONFIG_DIR/cache/model-catalog/-cc.json`. + /// Its `/model` picker shows the `main` section first and the rest under + /// "more models". + static func parseClaude(_ data: Data) -> AgentModelCatalog? { + ClaudeModelCatalogFile.decode(data).flatMap(claudeCatalog(from:)) + } + + fileprivate static func claudeCatalog(from file: ClaudeModelCatalogFile) -> AgentModelCatalog? { + let entries = file.catalog.config.models + let main = entries.filter { $0.section == "main" } + let rest = entries.filter { $0.section != "main" } + let models = (main + rest).map { Model(id: $0.id, reasoningEfforts: $0.reasoningEfforts) } + guard !models.isEmpty else { return nil } + return AgentModelCatalog(models: models, primaryCount: main.count, source: .installedAgent) + } + + fileprivate static var snakeCaseDecoder: JSONDecoder { + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + return decoder + } +} + +private nonisolated struct CodexModelCache: Decodable { + let models: [CodexModelEntry] +} + +private nonisolated struct CodexModelEntry: Decodable { + let slug: String + let visibility: String? + let priority: Int? + let supportedReasoningLevels: [CodexReasoningLevel]? +} + +private nonisolated struct CodexReasoningLevel: Decodable { + let effort: String +} + +private nonisolated struct ClaudeModelCatalogFile: Decodable { + let fetchedAt: Double? + let catalog: ClaudeModelCatalogBody + + static func decode(_ data: Data) -> ClaudeModelCatalogFile? { + try? AgentModelCatalog.snakeCaseDecoder.decode(ClaudeModelCatalogFile.self, from: data) + } +} + +private nonisolated struct ClaudeModelCatalogBody: Decodable { + let config: ClaudeModelCatalogConfig +} + +private nonisolated struct ClaudeModelCatalogConfig: Decodable { + let models: [ClaudeModelCatalogEntry] +} + +private nonisolated struct ClaudeModelCatalogEntry: Decodable { + let id: String + let section: String? + let runtime: ClaudeModelRuntime? + let thinking: ClaudeModelThinking? + + var reasoningEfforts: [String]? { + if let levels = runtime?.effortLevels { return levels } + if let options = thinking?.effortOptions { return options.map(\.id) } + if thinking?.type == "none" { return [] } + return nil + } +} + +private nonisolated struct ClaudeModelRuntime: Decodable { + let effortLevels: [String]? +} + +private nonisolated struct ClaudeModelThinking: Decodable { + let type: String? + let effortOptions: [ClaudeModelEffortOption]? +} + +private nonisolated struct ClaudeModelEffortOption: Decodable { + let id: String +} + +// MARK: - Loading + +nonisolated enum AgentModelCatalogLoader { + /// Reads the installed agent's catalog off the main actor. Falls back to the + /// built-in list; returns nil when the runtime has no model suggestions. + @concurrent + static func load(for runtime: AgentProfileRuntime, dedicatedHome: URL?) async -> AgentModelCatalog? { + catalog( + for: runtime, + homes: homes( + for: runtime, + dedicatedHome: dedicatedHome, + environment: ProcessInfo.processInfo.environment, + userHome: FileManager.default.homeDirectoryForCurrentUser + ) + ) + } + + /// The first home with a readable catalog wins. A dedicated profile home has + /// no catalog until the agent runs there once, so the default home follows it. + static func catalog(for runtime: AgentProfileRuntime, homes: [URL]) -> AgentModelCatalog? { + for home in homes { + if let catalog = installedCatalog(for: runtime, home: home) { return catalog } + } + return AgentModelCatalog.builtIn(for: runtime) + } + + static func homes( + for runtime: AgentProfileRuntime, + dedicatedHome: URL?, + environment: [String: String], + userHome: URL + ) -> [URL] { + let variable: String + switch runtime { + case .codex: variable = "CODEX_HOME" + case .claude: variable = "CLAUDE_CONFIG_DIR" + default: return [] + } + let defaultHome: URL = + if let configured = environment[variable], !configured.isEmpty { + URL(filePath: configured, directoryHint: .isDirectory) + } else { + userHome.appending(path: runtime.defaultHomeDirectoryName, directoryHint: .isDirectory) + } + return [dedicatedHome, defaultHome].compactMap(\.self) + } + + private static func installedCatalog(for runtime: AgentProfileRuntime, home: URL) -> AgentModelCatalog? { + switch runtime { + case .codex: + guard let data = try? Data(contentsOf: home.appending(path: "models_cache.json")) else { return nil } + return AgentModelCatalog.parseCodex(data) + case .claude: + return newestClaudeCatalog(in: home.appending(path: "cache/model-catalog", directoryHint: .isDirectory)) + default: + return nil + } + } + + /// One file per signed-in account; the most recently fetched one describes + /// the account in use. + private static func newestClaudeCatalog(in directory: URL) -> AgentModelCatalog? { + guard + let files = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + else { return nil } + let newest = + files + .filter { $0.lastPathComponent.hasSuffix("-cc.json") } + .compactMap { url in (try? Data(contentsOf: url)).flatMap(ClaudeModelCatalogFile.decode) } + .max { ($0.fetchedAt ?? 0) < ($1.fetchedAt ?? 0) } + return newest.flatMap(AgentModelCatalog.claudeCatalog(from:)) + } +} diff --git a/App/Sources/Features/Settings/Views/AgentProfileEditorView.swift b/App/Sources/Features/Settings/Views/AgentProfileEditorView.swift index 04995aa8a..971af04ad 100644 --- a/App/Sources/Features/Settings/Views/AgentProfileEditorView.swift +++ b/App/Sources/Features/Settings/Views/AgentProfileEditorView.swift @@ -7,6 +7,7 @@ struct AgentProfileEditorView: View { @Bindable var store: StoreOf @State private var isIconPickerPresented = false @State private var isHoveringIconTile = false + @State private var loadedModelCatalog: LoadedModelCatalog? var body: some View { Form { @@ -19,6 +20,12 @@ struct AgentProfileEditorView: View { .formStyle(.grouped) .navigationTitle(store.profile.name) .task { store.send(.task) } + .task(id: modelCatalogKey) { + let key = modelCatalogKey + guard runtimeAdapter?.supportsModelSelection == true else { return } + let catalog = await AgentModelCatalogLoader.load(for: key.runtime, dedicatedHome: key.dedicatedHome) + loadedModelCatalog = LoadedModelCatalog(key: key, catalog: catalog) + } .alert($store.scope(state: \.alert, action: \.alert)) .sheet(isPresented: $isIconPickerPresented) { TabIconPickerView( @@ -61,7 +68,8 @@ struct AgentProfileEditorView: View { title: String(localized: "Model"), prompt: String(localized: "Runtime default"), text: $store.profile.model, - suggestions: modelSuggestions + suggestions: displayedModelCatalog?.primary.map(\.id) ?? [], + moreSuggestions: displayedModelCatalog?.overflow.map(\.id) ?? [] ) } if runtimeAdapter?.supportsReasoningEffort == true { @@ -327,9 +335,10 @@ struct AgentProfileEditorView: View { title: String, prompt: String, text: Binding, - suggestions: [String] + suggestions: [String], + moreSuggestions: [String] = [] ) -> some View { - let selection = suggestionSelection(for: text, suggestions: suggestions) + let selection = suggestionSelection(for: text, suggestions: suggestions + moreSuggestions) return HStack { Text(title) Spacer() @@ -339,19 +348,36 @@ struct AgentProfileEditorView: View { .labelsHidden() .multilineTextAlignment(.trailing) .accessibilityLabel(title) - Picker("", selection: selection) { - Text("Runtime Default").tag(AgentProfileSuggestionSelection.runtimeDefault) - ForEach(suggestions, id: \.self) { suggestion in - Text(suggestion).tag(AgentProfileSuggestionSelection.suggestion(suggestion)) + Menu { + Picker("", selection: selection) { + Text("Runtime Default").tag(AgentProfileSuggestionSelection.runtimeDefault) + ForEach(suggestions, id: \.self) { suggestion in + Text(suggestion).tag(AgentProfileSuggestionSelection.suggestion(suggestion)) + } + if case .custom = selection.wrappedValue { + Text("Custom Value").tag(selection.wrappedValue) + } } - if case .custom = selection.wrappedValue { - Text("Custom Value").tag(selection.wrappedValue) + .pickerStyle(.inline) + .labelsHidden() + if !moreSuggestions.isEmpty { + Menu("More Models") { + Picker("", selection: selection) { + ForEach(moreSuggestions, id: \.self) { suggestion in + Text(suggestion).tag(AgentProfileSuggestionSelection.suggestion(suggestion)) + } + } + .pickerStyle(.inline) + .labelsHidden() + } } + } label: { + Image(systemName: "chevron.up.chevron.down") } - .pickerStyle(.menu) + .menuStyle(.button) + .menuIndicator(.hidden) .controlSize(.small) - .labelsHidden() - .frame(width: 28) + .fixedSize() .accessibilityLabel("\(title) suggestions") .help("Pick a known value, or type any value.") } @@ -386,15 +412,44 @@ struct AgentProfileEditorView: View { return plan?.previewText ?? String(localized: "Unavailable") } + /// The selected model's own effort levels when the catalog knows them, so + /// the menu does not offer an effort that the model rejects. private var effortSuggestions: [String] { - runtimeAdapter?.reasoningEffortSuggestions ?? [] + displayedModelCatalog?.reasoningEfforts(for: store.profile.model) + ?? runtimeAdapter?.reasoningEffortSuggestions ?? [] + } + + /// The built-in list stands in until the installed agent's catalog loads. + private var displayedModelCatalog: AgentModelCatalog? { + guard let loadedModelCatalog, loadedModelCatalog.key == modelCatalogKey else { + return AgentModelCatalog.builtIn(for: store.profile.runtime) + } + return loadedModelCatalog.catalog } - private var modelSuggestions: [String] { - runtimeAdapter?.modelSuggestions ?? [] + private var modelCatalogKey: ModelCatalogKey { + ModelCatalogKey( + runtime: store.profile.runtime, + dedicatedHome: store.profile.bindsDedicatedHome + ? AgentProfileLaunchPlanner.dedicatedHomeDirectory( + for: store.profile.id, + base: ProwlPaths.agentProfileHomesDirectory + ) + : nil + ) } private var runtimeAdapter: (any AgentRuntimeAdapter)? { AgentRuntimeAdapterRegistry.profileAdapter(for: store.profile.runtime) } } + +private struct ModelCatalogKey: Hashable { + let runtime: AgentProfileRuntime + let dedicatedHome: URL? +} + +private struct LoadedModelCatalog { + let key: ModelCatalogKey + let catalog: AgentModelCatalog? +} diff --git a/App/Tests/AgentModelCatalogTests.swift b/App/Tests/AgentModelCatalogTests.swift new file mode 100644 index 000000000..366facb3f --- /dev/null +++ b/App/Tests/AgentModelCatalogTests.swift @@ -0,0 +1,181 @@ +import Foundation +import Testing + +@testable import Prowl + +struct AgentModelCatalogTests { + // MARK: - Codex + + @Test func codexCatalogListsVisibleModelsInPriorityOrder() throws { + let json = """ + {"models": [ + {"slug": "gpt-b", "visibility": "list", "priority": 2, + "supported_reasoning_levels": [{"effort": "low"}, {"effort": "max"}]}, + {"slug": "gpt-hidden", "visibility": "hide", "priority": 1}, + {"slug": "gpt-a", "visibility": "list", "priority": 1, + "supported_reasoning_levels": [{"effort": "low"}, {"effort": "ultra"}]} + ]} + """ + let catalog = try #require(AgentModelCatalog.parseCodex(Data(json.utf8))) + #expect(catalog.primary.map(\.id) == ["gpt-a", "gpt-b"]) + #expect(catalog.overflow.isEmpty) + #expect(catalog.source == .installedAgent) + #expect(catalog.reasoningEfforts(for: "gpt-a") == ["low", "ultra"]) + #expect(catalog.reasoningEfforts(for: "gpt-b") == ["low", "max"]) + } + + @Test func codexCatalogMovesModelsPastThePrimaryLimitToOverflow() throws { + let entries = (1...9).map { #"{"slug": "gpt-\#($0)", "visibility": "list", "priority": \#($0)}"# } + let json = #"{"models": [\#(entries.joined(separator: ","))]}"# + let catalog = try #require(AgentModelCatalog.parseCodex(Data(json.utf8))) + #expect(catalog.primary.map(\.id) == (1...AgentModelCatalog.primaryLimit).map { "gpt-\($0)" }) + #expect(catalog.overflow.map(\.id) == ((AgentModelCatalog.primaryLimit + 1)...9).map { "gpt-\($0)" }) + #expect(catalog.reasoningEfforts(for: "gpt-1") == nil) + } + + @Test func codexCatalogRejectsUnreadableOrEmptyData() { + #expect(AgentModelCatalog.parseCodex(Data("not json".utf8)) == nil) + #expect(AgentModelCatalog.parseCodex(Data(#"{"models": []}"#.utf8)) == nil) + #expect(AgentModelCatalog.parseCodex(Data(#"{"models": [{"slug": "x", "visibility": "hide"}]}"#.utf8)) == nil) + } + + // MARK: - Claude + + @Test func claudeCatalogPutsMainSectionFirstAndKeepsCatalogOrder() throws { + let json = """ + {"version": 2, "fetchedAt": 10, "catalog": {"config": {"models": [ + {"id": "claude-old", "section": "overflow", "runtime": {"effort_levels": ["low", "max"]}}, + {"id": "claude-new", "section": "main", "runtime": {"effort_levels": ["low", "xhigh"]}}, + {"id": "claude-light", "section": "overflow", + "thinking": {"type": "effort", "effort_options": [{"id": "low"}, {"id": "high"}]}}, + {"id": "claude-plain", "section": "overflow", "thinking": {"type": "none"}} + ]}}} + """ + let catalog = try #require(AgentModelCatalog.parseClaude(Data(json.utf8))) + #expect(catalog.primary.map(\.id) == ["claude-new"]) + #expect(catalog.overflow.map(\.id) == ["claude-old", "claude-light", "claude-plain"]) + #expect(catalog.reasoningEfforts(for: "claude-new") == ["low", "xhigh"]) + #expect(catalog.reasoningEfforts(for: "claude-light") == ["low", "high"]) + #expect(catalog.reasoningEfforts(for: "claude-plain") == []) + } + + @Test func claudeCatalogSpillsALongMainSectionIntoOverflow() throws { + let main = (1...8).map { #"{"id": "main-\#($0)", "section": "main"}"# } + let json = #"{"catalog": {"config": {"models": [\#(main.joined(separator: ",")), {"id": "extra"}]}}}"# + let catalog = try #require(AgentModelCatalog.parseClaude(Data(json.utf8))) + #expect(catalog.primary.count == AgentModelCatalog.primaryLimit) + #expect(catalog.overflow.map(\.id) == ["main-7", "main-8", "extra"]) + } + + @Test func claudeCatalogRejectsUnreadableData() { + #expect(AgentModelCatalog.parseClaude(Data("{}".utf8)) == nil) + #expect(AgentModelCatalog.parseClaude(Data(#"{"catalog": {"config": {"models": []}}}"#.utf8)) == nil) + } + + // MARK: - Shared rules + + @Test func catalogDropsDuplicatesAndCapsOverflow() { + let models = (["a", "a"] + (1...40).map { "m\($0)" }).map { AgentModelCatalog.Model(id: $0) } + let catalog = AgentModelCatalog(models: models, primaryCount: 1, source: .installedAgent) + #expect(catalog.primary.map(\.id) == ["a"]) + #expect(catalog.overflow.count == AgentModelCatalog.overflowLimit) + #expect(catalog.overflow.first?.id == "m1") + #expect(catalog.allModelIDs.count == 1 + AgentModelCatalog.overflowLimit) + } + + @Test func reasoningEffortsAreUnknownForModelsOutsideTheCatalog() { + let catalog = AgentModelCatalog( + models: [AgentModelCatalog.Model(id: "a", reasoningEfforts: ["low"])], + primaryCount: 1, + source: .installedAgent + ) + #expect(catalog.reasoningEfforts(for: nil) == nil) + #expect(catalog.reasoningEfforts(for: "custom-model") == nil) + #expect(catalog.reasoningEfforts(for: "a") == ["low"]) + } + + @Test func builtInCatalogUsesTheAdapterSuggestions() throws { + let catalog = try #require(AgentModelCatalog.builtIn(for: .codex)) + let adapter = try #require(AgentRuntimeAdapterRegistry.profileAdapter(for: .codex)) + #expect(catalog.source == .builtIn) + #expect(catalog.allModelIDs == adapter.modelSuggestions) + #expect(catalog.primary.count == AgentModelCatalog.primaryLimit) + #expect(AgentModelCatalog.builtIn(for: .gemini) == nil) + } + + // MARK: - Loader + + @Test func loaderPrefersTheDedicatedHomeCatalog() throws { + let root = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let dedicated = root.appending(path: "dedicated", directoryHint: .isDirectory) + let fallback = root.appending(path: "default", directoryHint: .isDirectory) + try writeCodexCache(["gpt-dedicated"], in: dedicated) + try writeCodexCache(["gpt-default"], in: fallback) + + let catalog = AgentModelCatalogLoader.catalog(for: .codex, homes: [dedicated, fallback]) + #expect(catalog?.allModelIDs == ["gpt-dedicated"]) + } + + @Test func loaderFallsBackToTheNextHomeAndThenToBuiltIn() throws { + let root = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: root) } + let empty = root.appending(path: "empty", directoryHint: .isDirectory) + let fallback = root.appending(path: "default", directoryHint: .isDirectory) + try writeCodexCache(["gpt-default"], in: fallback) + + #expect(AgentModelCatalogLoader.catalog(for: .codex, homes: [empty, fallback])?.allModelIDs == ["gpt-default"]) + #expect(AgentModelCatalogLoader.catalog(for: .codex, homes: [empty])?.source == .builtIn) + #expect(AgentModelCatalogLoader.catalog(for: .gemini, homes: [empty]) == nil) + } + + @Test func loaderReadsTheNewestClaudeCatalogAndIgnoresBadges() throws { + let home = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: home) } + let directory = home.appending(path: "cache/model-catalog", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try claudeCatalog(id: "claude-old", fetchedAt: 1).write(to: directory.appending(path: "a-cc.json")) + try claudeCatalog(id: "claude-new", fetchedAt: 2).write(to: directory.appending(path: "b-cc.json")) + try claudeCatalog(id: "claude-badge", fetchedAt: 3).write(to: directory.appending(path: "b-cc.badges.json")) + + let catalog = AgentModelCatalogLoader.catalog(for: .claude, homes: [home]) + #expect(catalog?.allModelIDs == ["claude-new"]) + #expect(catalog?.source == .installedAgent) + } + + @Test func defaultHomesHonorTheRuntimeHomeVariable() { + let user = URL(filePath: "/Users/someone", directoryHint: .isDirectory) + let dedicated = URL(filePath: "/profiles/1", directoryHint: .isDirectory) + #expect( + AgentModelCatalogLoader.homes(for: .codex, dedicatedHome: dedicated, environment: [:], userHome: user) + .map(\.path) == ["/profiles/1", "/Users/someone/.codex"] + ) + #expect( + AgentModelCatalogLoader.homes( + for: .claude, dedicatedHome: nil, environment: ["CLAUDE_CONFIG_DIR": "/custom/claude"], userHome: user + ) + .map(\.path) == ["/custom/claude"] + ) + } + + // MARK: - Helpers + + private func makeTemporaryDirectory() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appending(path: "AgentModelCatalogTests-\(UUID().uuidString)", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + private func writeCodexCache(_ slugs: [String], in home: URL) throws { + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + let entries = slugs.enumerated().map { #"{"slug": "\#($1)", "visibility": "list", "priority": \#($0)}"# } + try Data(#"{"models": [\#(entries.joined(separator: ","))]}"#.utf8) + .write(to: home.appending(path: "models_cache.json")) + } + + private func claudeCatalog(id: String, fetchedAt: Int) -> Data { + Data( + #"{"fetchedAt": \#(fetchedAt), "catalog": {"config": {"models": [{"id": "\#(id)", "section": "main"}]}}}"#.utf8) + } +} diff --git a/docs/components/agent-profiles.md b/docs/components/agent-profiles.md index bfebfdc41..462e25a0c 100644 --- a/docs/components/agent-profiles.md +++ b/docs/components/agent-profiles.md @@ -174,9 +174,17 @@ after choosing the destination agent. **Model** and **Reasoning Effort** offer suggestions and accept custom values supported by your CLI and account. For example, a Codex profile can select -`gpt-6.2-sol` and `ultra` from the suggestions. Not every model accepts every -effort: the Codex `luna` models stop at `max`. Leave either field blank to use -the runtime default. Type in the right-aligned value field, or use the adjacent +`gpt-6.2-sol` and `ultra` from the suggestions. Leave either field blank to use +the runtime default. + +For Codex and Claude Code, the model suggestions come from the model list that +the installed agent caches after it runs (`models_cache.json` in the Codex home, +`cache/model-catalog/` in the Claude Code config folder). A profile with a +dedicated home reads its own home first. The menu shows the agent's first models +in the agent's own order and puts the rest under **More Models**. When no cached +list is available, Prowl shows a built-in list. The Reasoning Effort suggestions +follow the selected model, so a model that stops at `max` does not offer +`ultra`. Suggestions never change a value that a profile already saved. Type in the right-aligned value field, or use the adjacent menu to select a suggestion. **Recommended** resolves in three tiers: the repo's **Default Agent Profile**