Files
olp/lib/providers/index.mjs
T
taodengandClaude Opus 4.7 (noreply@anthropic.com) c175e8994c feat(phase-1): land Anthropic provider plugin (D4)
Phase 1 Day 2. Anthropic provider plugin code lands, plus contractVersion
field added across base.mjs and validated strictly. Anthropic stays
CANDIDATE per ALIGNMENT.md Provider Inventory — D5 flips to Enabled after
the real spawn E2E audit passes. POST /v1/chat/completions claude-* still
returns 503 until then.

Files:
  NEW:  lib/providers/anthropic.mjs (445 lines)
  MOD:  lib/providers/base.mjs (+8 lines — contractVersion enforcement)
  MOD:  lib/providers/index.mjs (+37 lines — STATIC_REGISTRY adds anthropic
        + getProviderByName helper)
  MOD:  models-registry.json — populates providers.anthropic with 3 models
        opus-4-7 / sonnet-4-6 / haiku-4-5, alias map, candidate marker
  MOD:  test-features.mjs (+481 lines — Suite 6: 37 new tests covering
        contract conformance, contractVersion enforcement, IR translation,
        mock-spawn behaviour, healthCheck, estimateCost)

Authority citations (all verified by independent reviewer against actual
OCP byte offsets):
  Spawn pattern: OCP server.mjs:542 stdio shape, port verbatim.
  CLI args: OCP server.mjs:384-414 buildCliArgs pattern — -p, --model X,
    --output-format text, --no-session-persistence (session-resume and
    permissions branches stripped per OLP no-state architecture).
  stdin write: OCP server.mjs:586-587 verbatim.
  Stdout text handling: OCP server.mjs:735-748 raw d.toString per chunk
    no JSON envelope, matches --output-format text.
  Auth chain: OCP server.mjs:864-888 (env CLAUDE_CODE_OAUTH_TOKEN ->
    ~/.claude/.credentials.json -> macOS keychain with both label formats
    "claude-code-credentials" and "Claude Code-credentials") ported in
    same priority order. One delta vs OCP: OLP guards keychain branch on
    process.platform === darwin, OCP relies on try/catch on Linux. Both
    behave identically; OLP avoids an unnecessary shell-out.
  Env cleanup: OCP server.mjs:530-534 — delete CLAUDECODE, ANTHROPIC_
    API_KEY, ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN. CLAUDECODE
    clobbering pitfall inherited per memory.

Architectural decisions:
  1. Anthropic stays Candidate at D4. STATIC_REGISTRY.length === 1 but
     loadProviders({}) returns empty Map. Suite 7 HTTP integration tests
     continue to verify 503 with no_enabled_provider for any claude-*
     model. D5 changes the config default to enable: { anthropic: true }
     and adds the real E2E spawn test.
  2. contractVersion === 1.0 strictly enforced (F3 fold-in from D3
     review). validateProvider in base.mjs rejects providers missing or
     having any other version string. Suite 6 includes 4 tests covering
     missing / 0.9 / 1.0 / undefined cases.
  3. quotaStatus returns null at D4 with a TODO comment pointing at the
     ALIGNMENT.md 2026-06-16 one-shot audit. Anthropic Agent SDK Credit
     pool balance API has not been pinned; verification scheduled for
     2026-06-16 per OLP one-shot audits.
  4. estimateCost returns shape but usd: null. Per-million-token rates
     not pinned at D4. Lands when models-registry.json gains a pricing
     field in a later phase.
  5. Lossy translations explicitly documented in anthropic.mjs file
     header per ADR 0003 § Lossy-translation documentation requirement.
     Includes response_format json_object (system-prompt augmented),
     top_p (no --top-p flag), tool_choice required (no flag), and
     request-level tools[] + assistant tool_calls + tool_call_id
     (text-in/text-out CLI cannot consume structured tool wire format).
     The tools[] documentation gap was a reviewer non-blocking finding;
     folded in this commit.

Mocking discipline: no real claude -p spawn in any D4 test. spawn-path
coverage uses __setSpawnImpl injection of fake child_process. No real
OAuth tokens or API keys in fixtures — all use placeholder strings
fake-oauth-token / fake-token. Auth path computed via
path.join(homedir(), .claude, .credentials.json), no hardcoded
/Users/<name> literal.

Reviewer chain (Iron Rule 10):
  Implementer: sonnet (general-purpose).
  Fresh-context reviewer: opus (ecc:code-reviewer). Verdict
    APPROVE_WITH_MINOR.
  Reviewer ran npm test (98/98 pass) and verified all five OCP citations
    at the actual byte offsets in /Users/taodeng/ocp/server.mjs. All
    citations confirmed accurate.

Reviewer non-blocking findings:
  1. tools[] and tool_calls lossy-translation undocumented — FOLDED IN
     this commit (anthropic.mjs header rewritten with full lossy list).
  2. with type json import attribute Node 20 compat — DEFERRED to CI
     verification. The syntax is stable on Node 20.10+ and the CI
     setup-node@v4 with node-version 20 resolves to latest 20.x. If
     CI Node 20 leg fails, mitigation is bump engines.node to >=20.10
     or swap both import-attribute lines for readFileSync + JSON.parse.
  3. CLI_NOT_FOUND error code declared but never thrown — DEFERRED to
     a future commit. Pure cosmetic; could distinguish ENOENT from
     generic spawn errors but no functional impact.

Test count: 61 -> 98 (+37 D4 tests).

Verification:
  node --check on all touched files: clean.
  npm test on Node 25.8.0: 98/98 pass in 209ms.
  Reviewer-run npm test independently: 98/98 pass.
  loadProviders({}) returns empty Map (verified by orchestrator and
    reviewer): Anthropic Candidate gate holds.
  hygiene grep: no personal names, no /Users/<name>/ literals, no real
    OAuth tokens or API keys.

Co-Authored-By: Claude Opus 4.7 (noreply@anthropic.com)
2026-05-23 17:59:48 +10:00

100 lines
3.5 KiB
JavaScript

/**
* lib/providers/index.mjs — Static provider registry
*
* Authority: ADR 0002 § "Loading model"
*
* This file is a hand-maintained static enumeration. There is no filesystem
* scan, no dynamic discovery, no npm-installed plugin loading. Adding a
* provider requires: (1) write lib/providers/<name>.mjs, (2) add one import +
* one entry to STATIC_REGISTRY below, (3) README § "Supported Providers",
* (4) inclusion ADR per ADR 0006.
*
* At D4 (Phase 1 Day 2), the anthropic plugin is added to STATIC_REGISTRY
* as a Candidate. It is NOT Enabled by default — a config with
* { enabled: { anthropic: true } } is required, which only happens after D5
* E2E audit passes per ALIGNMENT.md § Provider Inventory.
*/
import { validateProvider } from './base.mjs';
import anthropicDefault from './anthropic.mjs';
// Normalize default export pattern
const anthropic = anthropicDefault;
// ── Static registry ───────────────────────────────────────────────────────
const STATIC_REGISTRY = [
anthropic,
];
// ── Registry functions ────────────────────────────────────────────────────
/**
* Loads and validates providers, filtering by the enabled set in config.
* At D4, the anthropic provider is Candidate only — it will not appear in
* the loaded Map unless config.enabled.anthropic === true (set by D5 after E2E).
*
* @param {{ enabled?: Record<string,boolean> }} [config={}]
* @returns {Map<string, import('./base.mjs').ProviderContractV1>}
*/
export function loadProviders(config = {}) {
const loaded = new Map();
for (const p of STATIC_REGISTRY) {
const { valid, errors } = validateProvider(p);
if (!valid) {
throw new Error(`Provider ${p?.name ?? 'unknown'} fails contract validation: ${errors.join('; ')}`);
}
const enabled = config.enabled?.[p.name] === true;
if (enabled) {
loaded.set(p.name, p);
}
}
return loaded;
}
/**
* Returns the first provider in `loadedProviders` whose `models[]` includes
* the exact `modelString`. Returns null if no provider is found.
*
* This is the naive lookup strategy for D4. Phase 2+ may add prefix/alias
* matching once models-registry.json is consulted per AGENTS.md SPOT policy.
*
* @param {Map<string, import('./base.mjs').ProviderContractV1>} loadedProviders
* @param {string} modelString
* @returns {{ provider: import('./base.mjs').ProviderContractV1, name: string }|null}
*/
export function getProviderForModel(loadedProviders, modelString) {
for (const [name, p] of loadedProviders) {
if (p.models.includes(modelString)) {
return { provider: p, name };
}
}
return null;
}
/**
* Looks up a provider by name in the loaded Map. Returns null if not found.
* Useful for tests that need to access a specific provider directly.
*
* @param {Map<string, import('./base.mjs').ProviderContractV1>} loadedProviders
* @param {string} name
* @returns {import('./base.mjs').ProviderContractV1|null}
*/
export function getProviderByName(loadedProviders, name) {
return loadedProviders.get(name) ?? null;
}
/**
* Returns all provider names in the static registry (whether enabled or not).
* Used by /health and diagnostics.
* At D4: returns ['anthropic'] (the candidate roster).
*
* @returns {string[]}
*/
export function listAllProviderNames() {
return STATIC_REGISTRY.map(p => p.name);
}