diff --git a/Integration.md b/Integration.md index ee22550..37dc377 100644 --- a/Integration.md +++ b/Integration.md @@ -15,7 +15,7 @@ This guide separates provider-specific setup from AIFIAR's shared rules. It comp ### Anthropic / Claude - **Instructions:** models/anthropic/INSTRUCTIONS.md and languages//anthropic/INSTRUCTIONS.md for coding. Connect repository/tools separately from any project prompt. -- **Runtime:** native Anthropic Messages API with API-key and version headers. Do not assume OpenAI request/response shapes. Verify model IDs, content blocks, token limits, usage, rate limits, and features against official docs. +- **Runtime:** native Anthropic Messages API with API-key and version headers, plus bounded paginated model discovery through `GET /v1/models`. Discovery returns provider-supplied model IDs and optional creation/display metadata only; it does not infer context windows, tool support, pricing, or model quality. Do not assume OpenAI request/response shapes. Verify model IDs, content blocks, token limits, usage, rate limits, and features against official docs. - **Rules:** distinguish refusal, truncation, API errors, and successful text. Current adapter is text-oriented and does not enable Anthropic tools. ### Google Gemini diff --git a/README.md b/README.md index ecded39..f1f3eaa 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ See [the architecture guide](docs/architecture.md) and [the workflow guide](docs | `models/providerRuntime.ts` | Environment-driven registry and dispatch for OpenAI, xAI, Anthropic, Qwen, and Qwen Code | | `models/qwen/` | General Qwen analysis, reading, research, and evidence-checking instructions | | `models/qwen-code/` | Qwen Code full-scope coding, integration, and verification instructions | -| `models/providerDiscovery.ts` | Bounded model discovery for OpenAI-compatible provider endpoints | +| `models/providerDiscovery.ts` | Bounded OpenAI-compatible model discovery; Anthropic uses its native paginated Models API | | `models/providerTelemetry.ts` | Bounded in-memory latency, outcome, token, and rate-limit telemetry | | `core/repositoryMemory.ts` | Durable repository-aware memory with freshness checks and symbol search | | `core/repositoryContext.ts` | Bounded task-specific source context with hash references and redaction | diff --git a/docs/provider-integration.md b/docs/provider-integration.md index 5108b5c..30e5fed 100644 --- a/docs/provider-integration.md +++ b/docs/provider-integration.md @@ -30,7 +30,7 @@ The adapter uses native fetch, no added runtime dependency, no shell, no provide ## Current limitations - The shared OpenAI-compatible adapter targets text-only Chat Completions-compatible APIs. OpenAI Responses is implemented separately in `models/openAIResponsesAdapter.ts`. The current adapters do not provide multimodal input, streaming, provider tool calls, OAuth, or provider-side tools. Model discovery is a separate bounded helper for OpenAI and xAI; it does not select models automatically. -- Generic local/self-hosted providers have an executable text-only OpenAI-compatible Chat Completions adapter, subject to HTTPS for remote endpoints and explicit keys for remote hosts. Gemini now has a text-only REST adapter and bounded discovery; it does not provide multimodal input, streaming, grounding/web search, provider tools, or OAuth. Anthropic has a native Messages API adapter but no model discovery, streaming, multimodal input, provider tools, or OAuth. Qwen is text-only, uses a host-configured compatible endpoint and region-matched key, and does not enable built-in search tools or web browsing. Configure the endpoint and key for the same region using the [official Alibaba Cloud Model Studio compatibility guide](https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope). See `models/provider-coverage.json` for current coverage. +- Generic local/self-hosted providers have an executable text-only OpenAI-compatible Chat Completions adapter, subject to HTTPS for remote endpoints and explicit keys for remote hosts. Gemini has a text-only REST adapter and bounded discovery; it does not provide multimodal input, streaming, grounding/web search, provider tools, or OAuth. Anthropic has a native Messages API adapter plus bounded, paginated model discovery through its native Models API; it still does not provide streaming, multimodal input, provider tools, or OAuth. Qwen is text-only, uses a host-configured compatible endpoint and region-matched key, and does not enable built-in search tools or web browsing. Configure the endpoint and key for the same region using the [official Alibaba Cloud Model Studio compatibility guide](https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope). See `models/provider-coverage.json` for current coverage. - Routing benchmark reports, model outcome comparison, verified-rate-card cost estimates, and the opt-in private in-memory result cache are documented in [evaluation and cache](evaluation-and-cache.md). These helpers do not prove live benchmark results or billing accuracy. - Provider APIs and model availability can change. Confirm current official documentation and account access before use. - Integration tests use mocked HTTP responses. They do not call paid provider APIs by default. @@ -55,7 +55,7 @@ The separate `models/openAIResponsesAdapter.ts` implements text-only requests to ## Model discovery -The runtime exposes `discoverModels("openai")`, `discoverModels("xai")`, `discoverModels("gemini")`, `discoverModels("qwen")`, and `discoverModels("qwen-code")`. Discovery requires a configured provider key, uses the official provider base URL, rejects insecure remote URLs and redirects, enforces a timeout and response-size cap, and returns model IDs plus available rate-limit headers. Discovery does not automatically change the selected model. Check account access and compatibility before changing configuration. +The runtime exposes `discoverModels("openai")`, `discoverModels("xai")`, `discoverModels("anthropic")`, `discoverModels("gemini")`, `discoverModels("qwen")`, and `discoverModels("qwen-code")`. OpenAI-compatible discovery uses the configured provider base URL; Anthropic discovery uses its native Models API with `x-api-key`, the API version header, bounded cursor pagination, a per-page timeout, and a 1 MiB response cap. It returns only provider-supplied model IDs and optional creation/display metadata. Discovery does not infer context windows, tool support, prices, or quality and does not automatically change the selected model. Check account access and compatibility before changing configuration. ## Telemetry diff --git a/docs/roadmap.md b/docs/roadmap.md index 4a12794..807f304 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -149,7 +149,8 @@ A checked item indicates that the framework helper or orchestration logic exists - [x] Implement and test the Anthropic and Gemini runtime adapters before advertising those providers as selectable. - [x] Implement a text-only generic local/self-hosted OpenAI-compatible runtime adapter with loopback HTTP restriction, HTTPS for remote endpoints, explicit remote key, mocked tests, and bounded model discovery. - [x] Add bounded Gemini model discovery and capability tests for models advertising generateContent support. -- [ ] Add verified model metadata discovery and capability tests for every remaining runtime, including schema, context, tools, limits, and usage behavior. +- [x] Add bounded, paginated Anthropic Models API discovery with native authentication, response/cursor validation, request/body bounds, and runtime wiring tests. This reports provider-supplied IDs and optional creation/display metadata only. +- [ ] Complete verified model metadata discovery and capability tests for the other runtimes, including schema, context, tools, limits, and usage behavior; do not infer unavailable metadata. ## Remaining Phase 0-5 work that needs a real host or external evidence diff --git a/models/anthropicAdapter.ts b/models/anthropicAdapter.ts index b61e473..68a811a 100644 --- a/models/anthropicAdapter.ts +++ b/models/anthropicAdapter.ts @@ -252,3 +252,125 @@ export function createAnthropicExecutor(config: AnthropicAdapterConfig): TaskExe } }; } + +export interface AnthropicModelDiscoveryOptions { + apiKey: string; + timeoutMs?: number; + maxModels?: number; + maxPages?: number; + fetchImpl?: typeof fetch; +} + +export async function discoverAnthropicModels( + options: AnthropicModelDiscoveryOptions +): Promise { + if (typeof options.apiKey !== "string" || !options.apiKey.trim()) { + throw new Error("Anthropic API key is required for model discovery."); + } + const timeoutMs = options.timeoutMs ?? 15_000; + const maxModels = options.maxModels ?? 500; + const maxPages = options.maxPages ?? 5; + if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 60_000) { + throw new Error("timeoutMs must be between 1000 and 60000."); + } + if (!Number.isInteger(maxModels) || maxModels < 1 || maxModels > 2000) { + throw new Error("maxModels must be between 1 and 2000."); + } + if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 20) { + throw new Error("maxPages must be between 1 and 20."); + } + + const fetchImpl = options.fetchImpl ?? fetch; + const models: import("./providerDiscovery.js").DiscoveredModel[] = []; + let afterId: string | undefined; + let truncated = false; + + for (let page = 0; page < maxPages && models.length < maxModels; page++) { + const url = new URL("https://api.anthropic.com/v1/models"); + url.searchParams.set("limit", String(Math.min(100, maxModels - models.length))); + if (afterId) url.searchParams.set("after_id", afterId); + + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetchImpl(url, { + method: "GET", + redirect: "error", + signal: controller.signal, + headers: { + "x-api-key": options.apiKey, + "anthropic-version": "2023-06-01", + accept: "application/json" + } + }); + if (response.status === 401 || response.status === 403) { + throw new Error("Anthropic rejected credentials or model-list permissions."); + } + if (!response.ok) throw new Error("Anthropic model discovery failed with HTTP " + response.status + "."); + if (!response.body) throw new Error("Anthropic model discovery returned an empty response body."); + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const part = await reader.read(); + if (part.done) break; + total += part.value.byteLength; + if (total > 1024 * 1024) { + await reader.cancel(); + throw new Error("Anthropic model discovery response exceeded 1 MiB."); + } + chunks.push(part.value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + + let parsed: unknown; + try { parsed = JSON.parse(new TextDecoder().decode(bytes)); } + catch { throw new Error("Anthropic model discovery returned invalid JSON."); } + if (!parsed || typeof parsed !== "object" || !Array.isArray((parsed as Record).data)) { + throw new Error("Anthropic model discovery returned an unsupported list schema."); + } + const payload = parsed as { data: unknown[]; has_more?: unknown; last_id?: unknown }; + for (const item of payload.data) { + if (!item || typeof item !== "object") continue; + const model = item as Record; + if (typeof model.id !== "string" || !model.id.trim()) continue; + const createdAt = typeof model.created_at === "string" ? Date.parse(model.created_at) : NaN; + models.push({ + id: model.id, + ...(Number.isFinite(createdAt) ? { created: Math.floor(createdAt / 1000) } : {}), + ...(typeof model.display_name === "string" ? { displayName: model.display_name.slice(0, 120) } : {}) + }); + if (models.length >= maxModels) break; + } + + if (payload.has_more !== true) { + afterId = undefined; + break; + } + if (typeof payload.last_id !== "string" || !payload.last_id || payload.last_id.length > 256) { + throw new Error("Anthropic model discovery pagination cursor is invalid."); + } + if (payload.last_id === afterId) throw new Error("Anthropic model discovery pagination did not advance."); + afterId = payload.last_id; + if (page === maxPages - 1 || models.length >= maxModels) truncated = true; + } finally { + clearTimeout(timer); + } + } + + models.sort((a, b) => a.id.localeCompare(b.id)); + const unique = models.filter((model, index) => index === 0 || model.id !== models[index - 1]?.id); + return { + provider: "anthropic", + models: unique, + fetchedAt: new Date().toISOString(), + ...(truncated ? { truncated: true } : {}) + }; +} diff --git a/models/provider-coverage.json b/models/provider-coverage.json index 74182b9..fc73310 100644 --- a/models/provider-coverage.json +++ b/models/provider-coverage.json @@ -52,6 +52,8 @@ ], "modelIds": "host-configured", "availability": "requires-valid-host-configuration", + "modelDiscovery": true, + "discoveryMode": "native-anthropic-models-api-bounded-pagination", "executionSettings": true }, { diff --git a/models/providerDiscovery.ts b/models/providerDiscovery.ts index 722dcaf..0bc7824 100644 --- a/models/providerDiscovery.ts +++ b/models/providerDiscovery.ts @@ -2,12 +2,14 @@ export interface DiscoveredModel { id: string; created?: number; ownedBy?: string; + displayName?: string; } export interface ModelDiscoveryResult { provider: string; models: DiscoveredModel[]; fetchedAt: string; rateLimit?: { limit?: number; remaining?: number; reset?: string }; + truncated?: boolean; } export interface ModelDiscoveryOptions { provider: string; diff --git a/models/providerRuntime.ts b/models/providerRuntime.ts index 9a26745..f9a982c 100644 --- a/models/providerRuntime.ts +++ b/models/providerRuntime.ts @@ -4,7 +4,7 @@ import type { TaskExecutor } from "../core/orchestrator.js"; import type { Task, TaskResult } from "../core/types.js"; import { createOpenAIExecutor, createXAIExecutor, createOpenAICompatibleExecutor } from "./openaiCompatibleAdapter.js"; import { createOpenAIResponsesExecutor } from "./openAIResponsesAdapter.js"; -import { createAnthropicExecutor } from "./anthropicAdapter.js"; +import { createAnthropicExecutor, discoverAnthropicModels } from "./anthropicAdapter.js"; import { createGeminiExecutor, discoverGeminiModels } from "./geminiAdapter.js"; import { InMemoryProviderTelemetry, type ProviderTelemetryEvent } from "./providerTelemetry.js"; import { discoverModels as fetchModels, type ModelDiscoveryResult } from "./providerDiscovery.js"; @@ -21,7 +21,7 @@ export interface ProviderRuntime { configuredProviders: string[]; telemetry: InMemoryProviderTelemetry; settings: Readonly>>; - discoverModels(provider: "openai" | "xai" | "qwen" | "qwen-code" | "gemini" | "local"): Promise; + discoverModels(provider: "openai" | "xai" | "anthropic" | "qwen" | "qwen-code" | "gemini" | "local"): Promise; } const taskKinds: ModelCapabilities["taskKinds"] = [ "repository-analysis", "research", "planning", "coding", "review", "testing", "documentation", "general" @@ -101,7 +101,7 @@ export function createProviderRuntime(options: ProviderRuntimeOptions = {}): Pro models.push({ provider: "anthropic", modelId: anthropicModel, taskKinds: [...taskKinds], supportsTools: false, supportsStructuredOutput: false, - supportedApiModes: ["anthropic-messages"], supportsModelDiscovery: false, + supportedApiModes: ["anthropic-messages"], supportsModelDiscovery: true, availability: "available", notes: "Text-only Anthropic Messages API adapter. Does not execute tools." }); executors.set("anthropic\u0000" + anthropicModel, createAnthropicExecutor({ @@ -111,7 +111,7 @@ export function createProviderRuntime(options: ProviderRuntimeOptions = {}): Pro models.push({ provider: "anthropic", modelId: anthropicModel || "unconfigured", taskKinds: [...taskKinds], supportsTools: false, supportsStructuredOutput: false, - supportedApiModes: ["anthropic-messages"], supportsModelDiscovery: false, + supportedApiModes: ["anthropic-messages"], supportsModelDiscovery: Boolean(anthropicKey), availability: "unconfigured", notes: "Set ANTHROPIC_API_KEY and AIFIAR_ANTHROPIC_MODEL to enable Anthropic Claude." }); @@ -224,7 +224,11 @@ export function createProviderRuntime(options: ProviderRuntimeOptions = {}): Pro executor, telemetry, settings, - discoverModels(provider: "openai" | "xai" | "qwen" | "qwen-code" | "gemini" | "local") { + discoverModels(provider: "openai" | "xai" | "anthropic" | "qwen" | "qwen-code" | "gemini" | "local") { + if (provider === "anthropic") { + if (!anthropicKey) throw new Error("Anthropic API credentials must be configured."); + return discoverAnthropicModels({ apiKey: anthropicKey, timeoutMs: settings.anthropic.timeoutMs, ...fetchOption }); + } if (provider === "gemini") { if (!geminiKey) throw new Error("Gemini API credentials must be configured."); return discoverGeminiModels({ apiKey: geminiKey, timeoutMs: settings.gemini.timeoutMs, ...fetchOption }); diff --git a/tests/anthropicAdapter.test.mjs b/tests/anthropicAdapter.test.mjs index b746f42..b4e9d4e 100644 --- a/tests/anthropicAdapter.test.mjs +++ b/tests/anthropicAdapter.test.mjs @@ -90,3 +90,77 @@ test("Anthropic adapter rejects mismatched provider/model selections without mak assert.equal(result.errors[0], "ADAPTER_MISMATCH"); assert.equal(calls, 0); }); + +import { discoverAnthropicModels } from "../dist/models/anthropicAdapter.js"; + +test("Anthropic model discovery uses native auth, validates schema, and follows bounded cursors", async () => { + const calls = []; + const result = await discoverAnthropicModels({ + apiKey: "discovery-secret", + maxModels: 3, + fetchImpl: async (url, init) => { + const parsed = new URL(String(url)); + calls.push({ url: parsed, init }); + assert.equal(parsed.pathname, "/v1/models"); + assert.equal(init.method, "GET"); + assert.equal(init.redirect, "error"); + assert.equal(init.headers["x-api-key"], "discovery-secret"); + assert.equal(init.headers["anthropic-version"], "2023-06-01"); + if (calls.length === 1) { + assert.equal(parsed.searchParams.get("limit"), "3"); + assert.equal(parsed.searchParams.has("after_id"), false); + return new Response(JSON.stringify({ + data: [ + { id: "claude-z", display_name: "Claude Z", created_at: "2025-01-01T00:00:00Z" }, + { id: "claude-a", display_name: "Claude A", created_at: "2025-01-02T00:00:00Z" } + ], + has_more: true, + last_id: "cursor-1" + }), { status: 200 }); + } + assert.equal(parsed.searchParams.get("after_id"), "cursor-1"); + return new Response(JSON.stringify({ + data: [{ id: "claude-m" }], + has_more: false + }), { status: 200 }); + } + }); + assert.equal(calls.length, 2); + assert.deepEqual(result.models.map(model => model.id), ["claude-a", "claude-m", "claude-z"]); + assert.equal(result.models.find(model => model.id === "claude-a").displayName, "Claude A"); + assert.equal(result.models.find(model => model.id === "claude-a").created, 1735776000); + assert.equal(result.provider, "anthropic"); + assert.equal(result.truncated, undefined); + assert.ok(!JSON.stringify(result).includes("discovery-secret")); +}); + +test("Anthropic model discovery rejects malformed cursors, invalid schemas, and auth failures", async () => { + await assert.rejects(discoverAnthropicModels({ + apiKey: "key", + fetchImpl: async () => new Response(JSON.stringify({ data: [], has_more: true }), { status: 200 }) + }), /cursor/); + await assert.rejects(discoverAnthropicModels({ + apiKey: "key", + fetchImpl: async () => new Response(JSON.stringify({ models: [] }), { status: 200 }) + }), /schema/); + await assert.rejects(discoverAnthropicModels({ + apiKey: "key", + fetchImpl: async () => new Response("{}", { status: 401 }) + }), /rejected credentials/); + await assert.rejects(discoverAnthropicModels({ apiKey: "key", maxPages: 21 }), /maxPages/); +}); + +test("Anthropic model discovery reports truncation when the page budget is exhausted", async () => { + let calls = 0; + const result = await discoverAnthropicModels({ + apiKey: "key", + maxPages: 1, + fetchImpl: async () => { + calls++; + return new Response(JSON.stringify({ data: [{ id: "claude-one" }], has_more: true, last_id: "next" }), { status: 200 }); + } + }); + assert.equal(calls, 1); + assert.equal(result.truncated, true); + assert.deepEqual(result.models.map(model => model.id), ["claude-one"]); +}); diff --git a/tests/providerRuntime.test.mjs b/tests/providerRuntime.test.mjs index da992c4..d7600eb 100644 --- a/tests/providerRuntime.test.mjs +++ b/tests/providerRuntime.test.mjs @@ -247,3 +247,28 @@ test("provider runtime applies configured execution limits to the selected API a assert.equal(calls.length, 1); assert.equal(calls[0].body.max_tokens, 4_096); }); + +test("provider runtime exposes Anthropic model discovery only with configured credentials", async () => { + const missing = createProviderRuntime({ env: {} }); + assert.equal(missing.registry.get("anthropic", "unconfigured")?.supportsModelDiscovery, false); + assert.throws(() => missing.discoverModels("anthropic"), /credentials/); + + let request; + const runtime = createProviderRuntime({ + env: { ANTHROPIC_API_KEY: "anthropic-discovery-key", AIFIAR_ANTHROPIC_MODEL: "claude-configured" }, + fetchImpl: async (url, init) => { + request = { url: String(url), init }; + return new Response(JSON.stringify({ + data: [{ id: "claude-discovered", display_name: "Claude Discovered", created_at: "2025-02-01T00:00:00Z" }], + has_more: false + }), { status: 200 }); + } + }); + assert.equal(runtime.registry.get("anthropic", "claude-configured")?.supportsModelDiscovery, true); + const result = await runtime.discoverModels("anthropic"); + assert.equal(request.url, "https://api.anthropic.com/v1/models?limit=100"); + assert.equal(request.init.headers["x-api-key"], "anthropic-discovery-key"); + assert.equal(result.provider, "anthropic"); + assert.deepEqual(result.models.map(model => model.id), ["claude-discovered"]); + assert.ok(!JSON.stringify(result).includes("anthropic-discovery-key")); +});