Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
831b49a
Add bounded Anthropic model discovery
NotY215 Nov 30, 2026
dffa012
Expose bounded model discovery truncation status
NotY215 Nov 30, 2026
b097097
Wire Anthropic model discovery into provider runtime
NotY215 Nov 30, 2026
5a8afb1
Expose Anthropic discovery in runtime API
NotY215 Nov 30, 2026
6838400
Test bounded Anthropic model discovery and pagination
NotY215 Nov 30, 2026
a65d86c
Test Anthropic model discovery runtime wiring
NotY215 Nov 30, 2026
cdfb489
Document Anthropic model discovery support
NotY215 Nov 30, 2026
62df65a
Document Anthropic model discovery support
NotY215 Nov 30, 2026
69cc00e
Document Anthropic model discovery support
NotY215 Nov 30, 2026
6feb350
Track completed Anthropic discovery milestone in roadmap
NotY215 Nov 30, 2026
66050db
Represent provider display names without overloading owner metadata
NotY215 Nov 30, 2026
a476cff
Preserve Anthropic display names as distinct model metadata
NotY215 Nov 30, 2026
e04e9ac
Assert native Anthropic model display metadata
NotY215 Nov 30, 2026
d860b67
Document Anthropic model discovery runtime behavior
NotY215 Nov 30, 2026
aae5ffd
Update README provider discovery architecture
NotY215 Nov 30, 2026
8db4500
Fix provider runtime discovery branch formatting
NotY215 Nov 30, 2026
d4ecbfd
Correct synchronous missing-credential discovery assertion
NotY215 Nov 30, 2026
41458a6
Advertise Anthropic model discovery in capability registry
NotY215 Nov 30, 2026
5df9623
Test Anthropic discovery capability metadata
NotY215 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<language>/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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 2 additions & 2 deletions docs/provider-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
122 changes: 122 additions & 0 deletions models/anthropicAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<import("./providerDiscovery.js").ModelDiscoveryResult> {
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<string, unknown>).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<string, unknown>;
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 } : {})
};
}
2 changes: 2 additions & 0 deletions models/provider-coverage.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
],
"modelIds": "host-configured",
"availability": "requires-valid-host-configuration",
"modelDiscovery": true,
"discoveryMode": "native-anthropic-models-api-bounded-pagination",
"executionSettings": true
},
{
Expand Down
2 changes: 2 additions & 0 deletions models/providerDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 9 additions & 5 deletions models/providerRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -21,7 +21,7 @@ export interface ProviderRuntime {
configuredProviders: string[];
telemetry: InMemoryProviderTelemetry;
settings: Readonly<Record<RuntimeProvider, ReturnType<typeof resolveProviderExecutionSettings>>>;
discoverModels(provider: "openai" | "xai" | "qwen" | "qwen-code" | "gemini" | "local"): Promise<ModelDiscoveryResult>;
discoverModels(provider: "openai" | "xai" | "anthropic" | "qwen" | "qwen-code" | "gemini" | "local"): Promise<ModelDiscoveryResult>;
}
const taskKinds: ModelCapabilities["taskKinds"] = [
"repository-analysis", "research", "planning", "coding", "review", "testing", "documentation", "general"
Expand Down Expand Up @@ -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({
Expand All @@ -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."
});
Expand Down Expand Up @@ -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 });
Expand Down
74 changes: 74 additions & 0 deletions tests/anthropicAdapter.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
});
Loading
Loading