@phren/agent 0.3.31 → 0.3.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,18 @@
1
- import { getBuiltinModels, normalizeProviderId, REASONING_LEVELS } from "../models.js";
1
+ /**
2
+ * Interactive model picker with inline reasoning effort slider.
3
+ *
4
+ * /model opens a navigable picker:
5
+ * ▸ claude-sonnet-4-20250514 ◐◐◐○○ medium
6
+ * claude-opus-4-20250514 ●●●●● high
7
+ * gpt-4o ◐◐◐○○ medium
8
+ * o4-mini ●●●○○ high
9
+ * qwen2.5-coder:14b ───── n/a
10
+ *
11
+ * Up/Down to navigate, Left/Right to adjust reasoning, Enter to select, Esc to cancel.
12
+ */
13
+ import { pickerRows, pickerWindow, movePicker, moveReasoning } from "./picker-navigation.js";
14
+ import { getBuiltinModels, getDiscoveredModels, normalizeProviderId, REASONING_LEVELS } from "../models.js";
15
+ import { catalogStatusFor, discoverAllProviders, discoverProvider } from "../model-discovery.js";
2
16
  const ESC = "\x1b[";
3
17
  const s = {
4
18
  bold: (t) => `${ESC}1m${t}${ESC}0m`,
@@ -11,15 +25,21 @@ const s = {
11
25
  };
12
26
  /** Models available per provider. Extend as needed. */
13
27
  export function getAvailableModels(provider, currentModel) {
14
- const normalizedProvider = normalizeProviderId(provider) ?? "openrouter";
15
- const models = getBuiltinModels(normalizedProvider).map((model) => ({
16
- id: model.id,
17
- provider: model.provider,
18
- label: model.label,
19
- reasoning: model.reasoningDefault,
20
- reasoningRange: [...model.reasoningRange],
21
- contextWindow: model.contextWindow,
22
- }));
28
+ const providers = provider === "*"
29
+ ? ["openai-codex", "openai", "openrouter", "anthropic", "deepseek", "openai-compat", "ollama"]
30
+ : [normalizeProviderId(provider) ?? "openrouter"];
31
+ const models = providers.flatMap((normalizedProvider) => {
32
+ const entries = getDiscoveredModels(normalizedProvider) ?? getBuiltinModels(normalizedProvider);
33
+ return entries.map((model) => ({
34
+ id: model.id,
35
+ provider: model.provider,
36
+ label: provider === "*" ? `${model.provider}/${model.label}` : model.label,
37
+ reasoning: model.reasoningDefault,
38
+ reasoningRange: [...model.reasoningRange],
39
+ contextWindow: model.contextWindow,
40
+ catalogStatus: model.catalogSource === "fallback" ? "offline" : catalogStatusFor(normalizedProvider),
41
+ }));
42
+ });
23
43
  // If user has a custom model not in the list, add it
24
44
  if (currentModel && !models.some((m) => m.id === currentModel)) {
25
45
  models.unshift({
@@ -33,6 +53,26 @@ export function getAvailableModels(provider, currentModel) {
33
53
  }
34
54
  return models;
35
55
  }
56
+ /** Fetches all configured provider catalogues, then returns the same rows the picker uses. */
57
+ export async function discoverAvailableModels(currentProvider, currentModel) {
58
+ const provider = normalizeProviderId(currentProvider);
59
+ const catalogs = await discoverAllProviders();
60
+ if (provider && !catalogs.some((catalog) => catalog.provider === provider))
61
+ catalogs.push(await discoverProvider(provider));
62
+ const rows = catalogs.flatMap((catalog) => catalog.models.map((model) => ({
63
+ id: model.id,
64
+ provider: model.provider,
65
+ label: `${model.provider}/${model.label}`,
66
+ reasoning: model.reasoningDefault,
67
+ reasoningRange: [...model.reasoningRange],
68
+ contextWindow: model.contextWindow,
69
+ catalogStatus: catalog.status,
70
+ })));
71
+ if (currentModel && provider && !rows.some((model) => model.provider === provider && model.id === currentModel)) {
72
+ rows.unshift({ id: currentModel, provider, label: `${provider}/${currentModel}`, reasoning: null, reasoningRange: [], contextWindow: undefined, catalogStatus: "offline" });
73
+ }
74
+ return rows;
75
+ }
36
76
  // ── Reasoning meter rendering ───────────────────────────────────────────────
37
77
  function renderReasoningMeter(level, range) {
38
78
  if (range.length === 0 || level === null)
@@ -52,37 +92,42 @@ function renderReasoningMeter(level, range) {
52
92
  * Show interactive model picker. Returns selected model + reasoning, or null on cancel.
53
93
  * Works in raw mode — caller must be in raw mode already (TUI) or we'll set it.
54
94
  */
55
- export function showModelPicker(provider, currentModel, currentReasoning, w) {
56
- const models = getAvailableModels(provider, currentModel);
95
+ export async function showModelPicker(provider, currentModel, currentReasoning, w) {
96
+ const models = await discoverAvailableModels(provider, currentModel);
57
97
  if (models.length === 0) {
58
98
  w.write(s.dim(" No models available for this provider.\n"));
59
99
  return Promise.resolve(null);
60
100
  }
61
- let cursor = models.findIndex((m) => m.id === currentModel);
101
+ const currentProvider = normalizeProviderId(provider);
102
+ let cursor = models.findIndex((m) => m.provider === currentProvider && m.id === currentModel);
62
103
  if (cursor < 0)
63
104
  cursor = 0;
64
105
  // Clone reasoning levels so we can adjust them
65
- const reasoningState = models.map((m) => m.id === currentModel ? currentReasoning ?? m.reasoning : m.reasoning);
106
+ const reasoningState = models.map((m) => m.provider === currentProvider && m.id === currentModel && !!currentReasoning && m.reasoningRange.includes(currentReasoning)
107
+ ? currentReasoning
108
+ : m.reasoning);
109
+ let query = "";
110
+ let renderedLines = 0;
66
111
  function render() {
67
- // Clear previous render (move up by model count + header + footer + blank)
68
- const totalLines = models.length + 4;
69
- w.write(`${ESC}${totalLines}A${ESC}J`);
112
+ if (renderedLines)
113
+ w.write(`${ESC}${renderedLines}A${ESC}J`);
70
114
  drawPicker();
71
115
  }
72
116
  function drawPicker() {
73
- const maxLabel = Math.max(...models.map((m) => m.label.length));
74
- w.write(`\n ${s.bold("Select model")} ${s.dim("(↑↓ navigate, ←→ reasoning, enter select, esc cancel)")}\n\n`);
75
- for (let i = 0; i < models.length; i++) {
117
+ const rows = pickerRows(models, query);
118
+ const visible = pickerWindow(rows, cursor, Math.max(3, Math.min(12, (w.rows || 24) - 6)));
119
+ const width = Math.max(12, (w.columns || 100) - 35);
120
+ w.write(` ${s.bold("Select model")} ${s.dim("↑↓ move · ←→ effort · enter select · esc cancel")}\n`);
121
+ w.write(` Search: ${query || "type to filter"} (${rows.length} models)\n`);
122
+ for (const i of visible) {
76
123
  const m = models[i];
77
- const selected = i === cursor;
78
- const arrow = selected ? s.cyan("▸") : " ";
79
- const padded = m.label + " ".repeat(maxLabel - m.label.length);
80
- const labelStr = selected ? s.bold(padded) : s.dim(padded);
81
- const meter = renderReasoningMeter(reasoningState[i], m.reasoningRange);
82
- const ctx = s.dim(`${(m.contextWindow / 1000).toFixed(0)}k`);
83
- w.write(` ${arrow} ${labelStr} ${meter} ${ctx}\n`);
124
+ const name = m.label.length > width ? m.label.slice(0, width - 1) + "…" : m.label;
125
+ const text = name.padEnd(width);
126
+ w.write(` ${i === cursor ? s.cyan("▸") : " "} ${i === cursor ? s.bold(text) : s.dim(text)} ${renderReasoningMeter(reasoningState[i], m.reasoningRange)}\n`);
84
127
  }
85
- w.write(`\n`);
128
+ if (!visible.length)
129
+ w.write(" No matching models.\n");
130
+ renderedLines = Math.max(1, visible.length) + 2;
86
131
  }
87
132
  // Initial draw
88
133
  drawPicker();
@@ -95,19 +140,22 @@ export function showModelPicker(provider, currentModel, currentReasoning, w) {
95
140
  resolve(null);
96
141
  return;
97
142
  }
143
+ const rows = pickerRows(models, query);
98
144
  if (key.name === "return") {
145
+ if (!rows.length)
146
+ return;
99
147
  const m = models[cursor];
100
148
  cleanup();
101
- resolve({ model: m.id, reasoning: reasoningState[cursor] });
149
+ resolve({ model: m.id, provider: m.provider, reasoning: reasoningState[cursor] });
102
150
  return;
103
151
  }
104
152
  if (key.name === "up") {
105
- cursor = (cursor - 1 + models.length) % models.length;
153
+ cursor = movePicker(rows, cursor, -1);
106
154
  render();
107
155
  return;
108
156
  }
109
157
  if (key.name === "down") {
110
- cursor = (cursor + 1) % models.length;
158
+ cursor = movePicker(rows, cursor, 1);
111
159
  render();
112
160
  return;
113
161
  }
@@ -116,24 +164,17 @@ export function showModelPicker(provider, currentModel, currentReasoning, w) {
116
164
  const m = models[cursor];
117
165
  if (m.reasoningRange.length === 0)
118
166
  return; // no reasoning for this model
119
- const current = reasoningState[cursor];
120
- const idx = current ? REASONING_LEVELS.indexOf(current) : -1;
121
- const rangeIndices = m.reasoningRange.map((r) => REASONING_LEVELS.indexOf(r));
122
- if (key.name === "right") {
123
- // Go higher
124
- const next = rangeIndices.find((ri) => ri > idx);
125
- if (next !== undefined)
126
- reasoningState[cursor] = REASONING_LEVELS[next];
127
- }
128
- else {
129
- // Go lower
130
- const prev = [...rangeIndices].reverse().find((ri) => ri < idx);
131
- if (prev !== undefined)
132
- reasoningState[cursor] = REASONING_LEVELS[prev];
133
- }
167
+ reasoningState[cursor] = moveReasoning(m.reasoningRange, reasoningState[cursor], key.name === "right" ? 1 : -1);
134
168
  render();
135
169
  return;
136
170
  }
171
+ if (key.name === "backspace" || (_ch && !key.ctrl && !key.meta && !/[\x00-\x1f\x7f]/.test(_ch))) {
172
+ query = key.name === "backspace" ? query.slice(0, -1) : (query + _ch).slice(0, 100);
173
+ const matches = pickerRows(models, query);
174
+ if (matches.length && !matches.includes(cursor))
175
+ cursor = matches[0];
176
+ render();
177
+ }
137
178
  }
138
179
  function cleanup() {
139
180
  process.stdin.removeListener("keypress", onKey);
@@ -0,0 +1,28 @@
1
+ /** Provider-qualified rows keep identical model IDs on different connectors
2
+ * distinct. Filtering and viewport placement are shared by both pickers. */
3
+ export function pickerRows(models, query) {
4
+ const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
5
+ return models.flatMap((model, index) => {
6
+ const text = `${model.provider} ${model.id} ${model.label}`.toLowerCase();
7
+ return terms.every(term => text.includes(term)) ? [index] : [];
8
+ });
9
+ }
10
+ export function movePicker(rows, cursor, delta) {
11
+ if (!rows.length)
12
+ return cursor;
13
+ const at = rows.indexOf(cursor);
14
+ return rows[(Math.max(0, at) + delta % rows.length + rows.length) % rows.length];
15
+ }
16
+ export function pickerWindow(rows, cursor, size) {
17
+ const count = Math.max(1, size);
18
+ const start = Math.max(0, Math.min(Math.max(0, rows.indexOf(cursor)) - Math.floor(count / 2), rows.length - count));
19
+ return rows.slice(start, start + count);
20
+ }
21
+ /** Move within this model's supported scale, never another provider's scale. */
22
+ export function moveReasoning(range, current, delta) {
23
+ if (!range.length)
24
+ return current;
25
+ const index = range.indexOf(current);
26
+ const next = index < 0 ? (delta > 0 ? 0 : range.length - 1) : Math.max(0, Math.min(range.length - 1, index + delta));
27
+ return range[next];
28
+ }
@@ -9,74 +9,44 @@
9
9
  import * as fs from "fs";
10
10
  import * as path from "path";
11
11
  import * as os from "os";
12
- import { hasCodexToken } from "../providers/codex-auth.js";
13
- import { getAuthStatusEntries } from "@phren/cli/auth/profiles";
14
- import { getBuiltinModels } from "../models.js";
12
+ import { getBuiltinModels, getDiscoveredModels } from "../models.js";
13
+ import { catalogStatusFor } from "../model-discovery.js";
14
+ import { providerAuthStatuses } from "../provider-connectors.js";
15
15
  const CONFIG_DIR = path.join(os.homedir(), ".phren-agent");
16
16
  const PROVIDERS_FILE = path.join(CONFIG_DIR, "providers.json");
17
+ function modelIds(provider) {
18
+ return (getDiscoveredModels(provider) ?? getBuiltinModels(provider)).map((model) => model.id);
19
+ }
17
20
  export function getProviderStatuses() {
18
- const auth = new Map(getAuthStatusEntries().map((entry) => [entry.provider, entry]));
19
- return [
20
- {
21
- name: "openrouter",
22
- configured: auth.get("openrouter")?.configured ?? false,
23
- authMethod: "api-key",
24
- authSource: auth.get("openrouter")?.source ?? "none",
25
- keyEnvVar: "OPENROUTER_API_KEY",
26
- models: getBuiltinModels("openrouter").map((model) => model.id),
27
- },
28
- {
29
- name: "anthropic",
30
- configured: auth.get("anthropic")?.configured ?? false,
31
- authMethod: "api-key",
32
- authSource: auth.get("anthropic")?.source ?? "none",
33
- keyEnvVar: "ANTHROPIC_API_KEY",
34
- models: getBuiltinModels("anthropic").map((model) => model.id),
35
- },
36
- {
37
- name: "openai",
38
- configured: auth.get("openai")?.configured ?? false,
39
- authMethod: "api-key",
40
- authSource: auth.get("openai")?.source ?? "none",
41
- keyEnvVar: "OPENAI_API_KEY",
42
- models: getBuiltinModels("openai").map((model) => model.id),
43
- },
44
- {
45
- name: "openai-codex",
46
- configured: hasCodexToken(),
47
- authMethod: "oauth",
48
- authSource: auth.get("openai-codex")?.source ?? "none",
49
- models: getBuiltinModels("openai-codex").map((model) => model.id),
50
- },
51
- {
52
- name: "deepseek",
53
- configured: !!process.env.DEEPSEEK_API_KEY,
54
- authMethod: "api-key",
55
- authSource: process.env.DEEPSEEK_API_KEY ? "env" : "none",
56
- keyEnvVar: "DEEPSEEK_API_KEY",
57
- models: getBuiltinModels("deepseek").map((model) => model.id),
58
- },
59
- {
60
- name: "ollama",
61
- configured: (process.env.PHREN_OLLAMA_URL ?? "").toLowerCase() !== "off",
62
- authMethod: "local",
63
- models: getBuiltinModels("ollama").map((model) => model.id),
64
- },
65
- ];
21
+ return providerAuthStatuses().map((status) => ({
22
+ name: status.provider,
23
+ configured: status.configured,
24
+ authMethod: status.provider === "openai-codex" ? "oauth" : status.provider === "ollama" ? "local" : "api-key",
25
+ authSource: status.authSource,
26
+ ...((status.provider === "openai" || status.provider === "openrouter" || status.provider === "anthropic") ? { keyEnvVar: `${status.provider === "openrouter" ? "OPENROUTER" : status.provider.toUpperCase()}_API_KEY` } : {}),
27
+ ...(status.provider === "deepseek" ? { keyEnvVar: "DEEPSEEK_API_KEY" } : {}),
28
+ ...(status.provider === "openai-compat" ? { keyEnvVar: "PHREN_AGENT_API_KEY" } : {}),
29
+ models: modelIds(status.provider),
30
+ catalogStatus: catalogStatusFor(status.provider),
31
+ }));
66
32
  }
67
33
  function loadConfig() {
68
34
  try {
69
- return JSON.parse(fs.readFileSync(PROVIDERS_FILE, "utf-8"));
35
+ const config = JSON.parse(fs.readFileSync(process.env.PHREN_AGENT_PROVIDERS_CONFIG || PROVIDERS_FILE, "utf-8"));
36
+ return config && typeof config === "object" && !Array.isArray(config)
37
+ ? { ...config, customModels: Array.isArray(config.customModels) ? config.customModels : [] }
38
+ : { customModels: [] };
70
39
  }
71
40
  catch {
72
41
  return { customModels: [] };
73
42
  }
74
43
  }
75
44
  function saveConfig(config) {
76
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
77
- const tmp = `${PROVIDERS_FILE}.${process.pid}.tmp`;
45
+ const file = process.env.PHREN_AGENT_PROVIDERS_CONFIG || PROVIDERS_FILE;
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const tmp = `${file}.${process.pid}.tmp`;
78
48
  fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n");
79
- fs.renameSync(tmp, PROVIDERS_FILE);
49
+ fs.renameSync(tmp, file);
80
50
  }
81
51
  export function addCustomModel(id, provider, opts) {
82
52
  const config = loadConfig();
@@ -121,12 +91,12 @@ export function formatProviderList() {
121
91
  const auth = p.configured ? `${GREEN}configured${RESET}` : p.authMethod === "oauth"
122
92
  ? `${DIM}run: phren auth login${RESET}`
123
93
  : p.keyEnvVar
124
- ? `${DIM}set ${p.keyEnvVar} or phren auth set-key ${p.name}${RESET}`
94
+ ? `${DIM}set ${p.keyEnvVar} or configure providers.json${RESET}`
125
95
  : `${DIM}local${RESET}`;
126
96
  const source = p.configured && p.authSource && p.authSource !== "none"
127
97
  ? `${DIM}${p.authSource}${RESET}`
128
98
  : null;
129
- const modelCount = `${DIM}${p.models.length} models${RESET}`;
99
+ const modelCount = `${DIM}${p.models.length} models${p.catalogStatus && p.catalogStatus !== "offline" ? `, ${p.catalogStatus}` : ""}${RESET}`;
130
100
  lines.push(` ${icon} ${BOLD}${p.name}${RESET} ${auth}${source ? ` ${source}` : ""} ${modelCount}`);
131
101
  }
132
102
  const custom = getCustomModels();
@@ -0,0 +1,89 @@
1
+ /** One connection resolver for model discovery, inference and auth status.
2
+ * Keys stay in memory; status output never serializes a connection object. */
3
+ import { readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import path from "node:path";
6
+ import { resolveApiKey } from "@phren/cli/auth/profiles";
7
+ import { hasCodexToken } from "./providers/codex-auth.js";
8
+ const ORDER = ["openai-codex", "openai", "openrouter", "anthropic", "deepseek", "openai-compat", "ollama"];
9
+ const DEFAULT_URLS = {
10
+ openai: "https://api.openai.com/v1", openrouter: "https://openrouter.ai/api/v1",
11
+ anthropic: "https://api.anthropic.com", deepseek: "https://api.deepseek.com", ollama: "http://localhost:11434",
12
+ };
13
+ const KEY_ENV = {
14
+ openai: "OPENAI_API_KEY", openrouter: "OPENROUTER_API_KEY", anthropic: "ANTHROPIC_API_KEY",
15
+ deepseek: "DEEPSEEK_API_KEY", "openai-compat": "PHREN_AGENT_API_KEY",
16
+ };
17
+ function object(value) {
18
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
19
+ }
20
+ function text(value) { return typeof value === "string" && value.trim() ? value.trim() : undefined; }
21
+ function readObject(file) {
22
+ try {
23
+ const raw = readFileSync(file, "utf8");
24
+ return raw.length <= 1_048_576 ? object(JSON.parse(raw)) : {};
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ }
30
+ function endpoint(raw) {
31
+ if (!raw)
32
+ return undefined;
33
+ const url = new URL(raw);
34
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
35
+ throw new Error("Provider endpoints must be HTTP(S) URLs without embedded credentials, query parameters or fragments. Use apiKeyEnv for keys.");
36
+ }
37
+ return raw.replace(/\/+$/, "");
38
+ }
39
+ /** Explicit connection config wins; existing Phren and OpenCode API-key
40
+ * credentials are reused without copying or exposing them. OpenCode OAuth
41
+ * tokens are not treated as API keys. Codex keeps its existing OAuth flow. */
42
+ export function resolveConnector(provider, overrideBaseUrl, env = process.env) {
43
+ const config = readObject(env.PHREN_AGENT_PROVIDERS_CONFIG || path.join(homedir(), ".phren-agent", "providers.json"));
44
+ const own = object(object(config.providers)[provider]);
45
+ const dataHome = env.XDG_DATA_HOME || path.join(homedir(), ".local", "share");
46
+ const auth = readObject(path.join(dataHome, "opencode", "auth.json"));
47
+ const openCodeConfig = readObject(env.OPENCODE_CONFIG || path.join(env.XDG_CONFIG_HOME || path.join(homedir(), ".config"), "opencode", "opencode.json"));
48
+ const go = object(auth["opencode-go"]);
49
+ const defaultGo = provider === "openai-compat" && !overrideBaseUrl && !env.PHREN_AGENT_BASE_URL && !env.OPENCODE_BASE_URL && !own.baseUrl
50
+ && go.type === "api" && !!text(go.key);
51
+ const imported = text(own.opencodeProvider) ?? (defaultGo ? "opencode-go" : provider);
52
+ const importedAuth = object(auth[imported]);
53
+ const importedOptions = object(object(object(openCodeConfig.provider)[imported]).options);
54
+ const keyEnv = text(own.apiKeyEnv) ?? KEY_ENV[provider];
55
+ const envKey = keyEnv ? text(env[keyEnv]) ?? (provider === "openai-compat" && !own.apiKeyEnv ? text(env.OPENCODE_API_KEY) : undefined) : undefined;
56
+ const profileKey = ["openai", "openrouter", "anthropic"].includes(provider) && !own.apiKeyEnv
57
+ ? resolveApiKey(provider, KEY_ENV[provider]) ?? undefined : undefined;
58
+ const importedKey = importedAuth.type === "api" ? text(importedAuth.key) : undefined;
59
+ const apiKey = own.apiKeyEnv ? envKey : envKey ?? profileKey ?? importedKey;
60
+ const envUrl = provider === "openai-compat" ? text(env.PHREN_AGENT_BASE_URL) ?? text(env.OPENCODE_BASE_URL)
61
+ : provider === "ollama" ? (env.PHREN_OLLAMA_URL === "off" ? undefined : text(env.PHREN_OLLAMA_URL))
62
+ : provider === "deepseek" && env.PHREN_AGENT_PROVIDER === "deepseek" ? text(env.PHREN_AGENT_BASE_URL) : undefined;
63
+ const baseUrl = endpoint(overrideBaseUrl ?? envUrl ?? text(own.baseUrl) ?? text(importedOptions.baseURL)
64
+ ?? (provider === "openai-compat" && imported === "opencode-go" ? "https://opencode.ai/zen/go/v1" : DEFAULT_URLS[provider]));
65
+ let authSource = envKey ? "env" : profileKey ? "profile" : importedKey ? "opencode" : "none";
66
+ let configured = !!apiKey;
67
+ if (provider === "openai-codex") {
68
+ configured = hasCodexToken();
69
+ authSource = configured ? "codex-cli" : "none";
70
+ }
71
+ if (provider === "ollama") {
72
+ configured = env.PHREN_OLLAMA_URL !== "off" && (!!env.PHREN_OLLAMA_URL || Object.keys(own).length > 0);
73
+ authSource = "local";
74
+ }
75
+ if (provider === "openai-compat")
76
+ configured = !!baseUrl; // local compatible servers may be keyless
77
+ if (own.enabled === false)
78
+ configured = false;
79
+ return { provider, baseUrl, apiKey, model: text(own.model), configured, authSource };
80
+ }
81
+ export function configuredProviders(env = process.env) {
82
+ return ORDER.filter(provider => resolveConnector(provider, undefined, env).configured);
83
+ }
84
+ export function providerAuthStatuses() {
85
+ return ORDER.map(provider => {
86
+ const { apiKey: _key, ...status } = resolveConnector(provider);
87
+ return status;
88
+ });
89
+ }
@@ -5,10 +5,13 @@ const PROVIDER_NAME = "anthropic";
5
5
  /** Thinking budget per effort level; always clamped below max_tokens. */
6
6
  const THINKING_BUDGETS = {
7
7
  none: 0,
8
+ minimal: 1024,
8
9
  low: 2048,
9
10
  medium: 8192,
10
11
  high: 16384,
11
12
  xhigh: 32768,
13
+ max: 32768,
14
+ ultra: 32768,
12
15
  };
13
16
  /** Anthropic rejects budget_tokens below this. */
14
17
  const MIN_THINKING_BUDGET = 1024;
@@ -25,23 +28,25 @@ export class AnthropicProvider {
25
28
  contextWindow = 200_000;
26
29
  maxOutputTokens;
27
30
  apiKey;
31
+ baseUrl;
28
32
  model;
29
33
  cacheEnabled;
30
34
  reasoningEffort;
31
- constructor(apiKey, model, maxOutputTokens, cacheEnabled = true, reasoningEffort) {
35
+ constructor(apiKey, model, maxOutputTokens, cacheEnabled = true, reasoningEffort, baseUrl = "https://api.anthropic.com") {
32
36
  this.apiKey = apiKey;
37
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
33
38
  this.model = model ?? "claude-sonnet-5";
34
39
  this.maxOutputTokens = maxOutputTokens ?? 8192;
35
40
  this.cacheEnabled = cacheEnabled;
36
41
  // "none" is thinking off, which on Anthropic means sending no thinking config.
37
42
  this.reasoningEffort = reasoningEffort === "none" ? undefined : reasoningEffort;
38
43
  const metadata = getModelMetadata(PROVIDER_NAME, this.model);
39
- if (metadata)
44
+ if (metadata?.contextWindow)
40
45
  this.contextWindow = metadata.contextWindow;
41
46
  }
42
47
  /** True when the model takes adaptive thinking instead of budget_tokens. */
43
48
  usesAdaptiveThinking() {
44
- return ADAPTIVE_THINKING_RE.test(this.model);
49
+ return getModelMetadata(PROVIDER_NAME, this.model)?.reasoningMode === "adaptive" || ADAPTIVE_THINKING_RE.test(this.model);
45
50
  }
46
51
  /**
47
52
  * Resolved thinking budget, or null when thinking stays off. The budget
@@ -57,7 +62,7 @@ export class AnthropicProvider {
57
62
  }
58
63
  async chat(system, messages, tools, signal) {
59
64
  const body = this.buildRequestBody(system, messages, tools);
60
- const res = await fetch("https://api.anthropic.com/v1/messages", {
65
+ const res = await fetch(`${this.baseUrl}/v1/messages`, {
61
66
  method: "POST",
62
67
  headers: {
63
68
  "Content-Type": "application/json",
@@ -87,7 +92,7 @@ export class AnthropicProvider {
87
92
  async *chatStream(system, messages, tools, signal) {
88
93
  const body = this.buildRequestBody(system, messages, tools);
89
94
  body.stream = true;
90
- const res = await fetch("https://api.anthropic.com/v1/messages", {
95
+ const res = await fetch(`${this.baseUrl}/v1/messages`, {
91
96
  method: "POST",
92
97
  headers: {
93
98
  "Content-Type": "application/json",
@@ -241,19 +246,25 @@ export class AnthropicProvider {
241
246
  messages: mappedMessages,
242
247
  max_tokens: this.maxOutputTokens,
243
248
  };
249
+ const metadata = getModelMetadata(PROVIDER_NAME, this.model);
250
+ const advertisedEffort = this.reasoningEffort && metadata?.catalogSource && metadata.reasoningRange.length === 0
251
+ ? undefined
252
+ : this.reasoningEffort && metadata?.reasoningRange.length && !metadata.reasoningRange.includes(this.reasoningEffort)
253
+ ? undefined
254
+ : this.reasoningEffort;
244
255
  if (this.usesAdaptiveThinking()) {
245
256
  // Adaptive thinking: the model decides when/how much to think; effort
246
257
  // controls depth. budget_tokens would 400 on 4.7+/5-family models.
247
- if (this.reasoningEffort) {
258
+ if (advertisedEffort) {
248
259
  body.thinking = { type: "adaptive" };
249
- const effort = EFFORT_NO_XHIGH_RE.test(this.model) && this.reasoningEffort === "xhigh"
260
+ const effort = EFFORT_NO_XHIGH_RE.test(this.model) && advertisedEffort === "xhigh"
250
261
  ? "max"
251
- : this.reasoningEffort;
262
+ : advertisedEffort;
252
263
  body.output_config = { effort };
253
264
  }
254
265
  }
255
266
  else {
256
- const budget = this.thinkingBudget();
267
+ const budget = advertisedEffort ? this.thinkingBudget() : null;
257
268
  if (budget !== null) {
258
269
  body.thinking = { type: "enabled", budget_tokens: budget };
259
270
  }
@@ -1,7 +1,7 @@
1
1
  import { IncompleteStreamError, toolResultText } from "./types.js";
2
2
  import { getAccessToken } from "./codex-auth.js";
3
3
  import { stripForeignReasoning, IMAGE_OMITTED_MARKER } from "./history.js";
4
- import { wireReasoningEffort } from "./openai-compat.js";
4
+ import { wireAdvertisedReasoningEffort } from "./openai-compat.js";
5
5
  import { lookupContextWindow, lookupMaxOutputTokens, modelSupportsVision } from "../models.js";
6
6
  const CODEX_API = "https://chatgpt.com/backend-api/codex/responses";
7
7
  const PROVIDER_NAME = "openai-codex";
@@ -15,9 +15,9 @@ export function toResponsesTools(tools) {
15
15
  }));
16
16
  }
17
17
  /** Convert our messages to Responses API input format. Exported for tests. */
18
- export function toResponsesInput(messages, vision = false) {
18
+ export function toResponsesInput(messages, vision = false, providerName = PROVIDER_NAME) {
19
19
  const input = [];
20
- for (const msg of stripForeignReasoning(messages, PROVIDER_NAME)) {
20
+ for (const msg of stripForeignReasoning(messages, providerName)) {
21
21
  if (msg.role === "user") {
22
22
  if (typeof msg.content === "string") {
23
23
  input.push({
@@ -135,7 +135,7 @@ function reasoningSummaryText(item) {
135
135
  .join("\n");
136
136
  }
137
137
  /** Parse non-streaming Responses API output into our ContentBlock format. Exported for tests. */
138
- export function parseResponsesOutput(data) {
138
+ export function parseResponsesOutput(data, providerName = PROVIDER_NAME) {
139
139
  debugLog("parseResponsesOutput input", data);
140
140
  // The Responses API may return output at top-level or nested under a "response" key.
141
141
  // Handle both shapes defensively.
@@ -185,7 +185,7 @@ export function parseResponsesOutput(data) {
185
185
  content.push({
186
186
  type: "reasoning",
187
187
  text: reasoningSummaryText(item),
188
- provider: PROVIDER_NAME,
188
+ provider: providerName,
189
189
  ...(typeof item.id === "string" ? { id: item.id } : {}),
190
190
  ...(typeof encrypted === "string" ? { encrypted_content: encrypted } : {}),
191
191
  });
@@ -231,7 +231,7 @@ export class CodexProvider {
231
231
  // cannot round-trip (chatStream already requested it; chat() didn't).
232
232
  include: ["reasoning.encrypted_content"],
233
233
  };
234
- const effort = wireReasoningEffort(this.name, this.model, this.reasoningEffort);
234
+ const effort = wireAdvertisedReasoningEffort(this.name, this.model, this.reasoningEffort);
235
235
  if (effort)
236
236
  body.reasoning = { effort };
237
237
  if (tools.length > 0) {
@@ -250,7 +250,7 @@ export class CodexProvider {
250
250
  stream: true,
251
251
  include: ["reasoning.encrypted_content"],
252
252
  };
253
- const effort = wireReasoningEffort(this.name, this.model, this.reasoningEffort);
253
+ const effort = wireAdvertisedReasoningEffort(this.name, this.model, this.reasoningEffort);
254
254
  if (effort)
255
255
  body.reasoning = { effort };
256
256
  if (tools.length > 0) {
@@ -1,4 +1,5 @@
1
1
  import { IncompleteStreamError, RetryableProviderError, withPartialUsage } from "./types.js";
2
+ import { getModelMetadata } from "../models.js";
2
3
  import { stripForeignReasoning, IMAGE_OMITTED_MARKER } from "./history.js";
3
4
  /** Convert Anthropic tool defs to OpenAI function format. */
4
5
  export function toOpenAiTools(tools) {
@@ -23,14 +24,17 @@ export function replaysAllReasoning(providerName, model) {
23
24
  }
24
25
  /**
25
26
  * DeepSeek's reasoning_effort takes none, low, high and max; it has no medium
26
- * and treats xhigh as high, so map Phren's levels onto what it documents.
27
+ * so map Phren's medium/xhigh aliases onto high/max.
27
28
  */
28
29
  const DEEPSEEK_EFFORT = {
29
30
  none: "none",
31
+ minimal: "low",
30
32
  low: "low",
31
33
  medium: "high",
32
34
  high: "high",
33
35
  xhigh: "max",
36
+ max: "max",
37
+ ultra: "max",
34
38
  };
35
39
  /**
36
40
  * OpenAI models that take reasoning effort "none": GPT-5.1 and later, except
@@ -55,6 +59,27 @@ export function wireReasoningEffort(providerName, model, effort) {
55
59
  return undefined;
56
60
  return effort;
57
61
  }
62
+ /**
63
+ * A discovered catalogue may know that reasoning is supported without
64
+ * advertising every effort. In that case the picker offers none and the
65
+ * request must not invent a level. Built-in compatibility metadata retains
66
+ * the historical wire mapping for offline use.
67
+ */
68
+ export function wireAdvertisedReasoningEffort(providerName, model, effort) {
69
+ if (!effort)
70
+ return undefined;
71
+ const metadata = getModelMetadata(providerName, model ?? "");
72
+ // Compare the provider's wire level: DeepSeek accepts high/max for medium/xhigh.
73
+ const advertised = isDeepSeekRoute(providerName, model) ? DEEPSEEK_EFFORT[effort] : effort;
74
+ if (metadata?.catalogSource && effort !== "none") {
75
+ if (metadata.reasoningRange.length === 0 || !metadata.reasoningRange.includes(advertised))
76
+ return undefined;
77
+ }
78
+ else if (metadata?.reasoningRange.length && effort !== "none" && !metadata.reasoningRange.includes(advertised)) {
79
+ return undefined;
80
+ }
81
+ return wireReasoningEffort(providerName, model, effort);
82
+ }
58
83
  /**
59
84
  * Convert Anthropic messages to OpenAI messages.
60
85
  *