mirror of
https://github.com/dtzp555-max/olp.git
synced 2026-07-21 21:15:10 +00:00
feat(phase-1): land IR + plugin loader + server skeleton (D3)
Phase 1 Day 1. First executable code lands. Zero providers wired yet
(per ALIGNMENT.md "v0.1 ships 0 Enabled Providers"); the server starts
clean and POST /v1/chat/completions returns 503 with no_enabled_provider.
Files added:
lib/ir/types.mjs - IR v1.0 schema + validators (ADR 0003)
lib/ir/openai-to-ir.mjs - OpenAI Chat Completions to IR
lib/ir/ir-to-openai.mjs - IR chunks to OpenAI SSE / non-stream
lib/providers/base.mjs - Provider contract + validateProvider + ProviderError
lib/providers/index.mjs - Static empty registry stub (ADR 0002)
server.mjs - HTTP listener with createOlpServer factory + main guard
test-features.mjs - 61 tests across 7 suites (IR / provider / HTTP)
Files modified:
package.json - main and scripts.start/test added back; targets now exist.
Authority citations:
IR fields and translation direction: ADR 0003 sections Decision and
Translation direction model.
Provider contract (9 fields): ADR 0002 section Provider contract v1.0
interface.
Entry surface routes (health, v1/models, v1/chat/completions): OLP v0.1
spec section 4.1 single-protocol entry; ALIGNMENT.md Authority 2.
Zero-Enabled-Providers behaviour: ALIGNMENT.md Provider Inventory.
Architectural decisions worth recording:
1. server.mjs uses a createOlpServer factory plus an import.meta.url
main guard. The factory returns an unbound http.Server; only the
main-script invocation calls .listen(). Tests import the real
server.mjs and exercise the real router. No parallel implementation
in the test file.
This pattern was a fold-in from the orchestration step. The initial
sonnet draft put a top-level server.listen call in server.mjs, which
forced test-features.mjs to reimplement the router inline (a false-
confidence trap because the real server logic would never be tested).
Refactored before reviewer dispatch.
2. lib/providers/index.mjs ships an empty STATIC_REGISTRY array, not a
placeholder with dummy entries. ALIGNMENT.md Provider Inventory says
v0.1 ships zero Enabled Providers; the registry honors that exactly.
Phase 1 Day 2 adds the first import (Anthropic) when its plugin lands.
3. BadRequestError lives in openai-to-ir.mjs and ProviderError in
base.mjs. Reviewer suggested relocating to a shared lib/errors.mjs
once the count exceeds two; deferred to Phase 1 Day 2 to ship with
the third typed error class.
4. contractVersion: '1.0' on each provider plugin: not enforced at D3
because no providers exist yet. Reviewer flagged for Phase 1 Day 2
tightening when the first provider lands.
Reviewer chain (Iron Rule 10):
Initial implementer: sonnet (general-purpose).
Refactor (createOlpServer + main guard) by the orchestrator after
catching the inline-router parallel-implementation issue.
Fresh-context reviewer: opus (ecc:code-reviewer). Verdict
APPROVE_WITH_MINOR.
Reviewer's two non-blocking findings folded in:
F1: removed unused createServer import from test-features.mjs line 12,
left over from the refactor.
F2: replaced finish_reason value 'error' with 'stop' in both the
streaming error chunk path (lib/ir/ir-to-openai.mjs line 72) and
the non-streaming error aggregation path (lib/ir/ir-to-openai.mjs
line 153). The 'error' value is not in OpenAI's documented
finish_reason enum (stop / length / tool_calls / content_filter /
function_call / null), so emitting it would violate ALIGNMENT.md
Rule 2 (b). Provider errors are now surfaced via a top-level
response.error object plus an inline content marker. The matching
test assertion at test-features.mjs line 325 was updated to verify
finish_reason stays within the OpenAI enum.
Note on the F2 fold-in:
Reviewer pointed only at the streaming path (line 72). After applying
that fix I ran grep across lib/ and test-features.mjs for the same
invention pattern and caught a second hit at line 153 (non-streaming
aggregation). This is the "fold-in must grep the full repo, not only
the file the reviewer named" discipline from
~/.cc-rules/memory/feedback/evidence_first_under_speed_pressure.md.
Both hits are fixed in this commit.
Verification:
node --check on all 7 new files plus modified package.json plus
server.mjs plus lib/ir/ir-to-openai.mjs - all clean.
npm test - 61/61 pass in 209ms, no flakes, no skipped.
OLP_PORT=14001 node server.mjs followed by curl /health returns
proper JSON; curl /v1/models returns 200 empty list; server shuts
down cleanly on signal.
grep "finish_reason.*error" returns zero hits across lib/ and tests.
Co-Authored-By: Claude Opus 4.7 (noreply@anthropic.com)
This commit is contained in:
co-authored by
Claude Opus 4.7 (noreply@anthropic.com)
parent
dff428f3d0
commit
e2e67de23a
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* lib/providers/base.mjs — Provider contract definition and shared helpers
|
||||
*
|
||||
* Authority: ADR 0002 § "Provider contract (v1.0 interface)"
|
||||
*
|
||||
* This module does NOT implement the Provider contract itself.
|
||||
* Provider plugins compose the helpers exported here; they do not inherit
|
||||
* from a base class (per ADR 0002 § Consequences/Mitigations: "compose helpers,
|
||||
* do not inherit").
|
||||
*/
|
||||
|
||||
// ── Contract typedef ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {Object} ProviderAuth
|
||||
* @property {string} type - e.g. 'subscription', 'api-key', 'oauth'
|
||||
* @property {string} storage - e.g. 'cli-managed', 'env', 'keychain'
|
||||
* @property {string} path - artifact location hint
|
||||
* @property {string|null} refresh - refresh mechanism or null if not applicable
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ProviderHints
|
||||
* @property {boolean} requiresTTY
|
||||
* @property {boolean} concurrentSpawnSafe
|
||||
* @property {number} maxConcurrent
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ProviderContractV1
|
||||
* @property {string} name - unique lowercase key
|
||||
* @property {string} displayName - human-readable name
|
||||
* @property {string[]} models - model strings this provider serves
|
||||
* @property {ProviderAuth} auth
|
||||
* @property {function} spawn - async (irRequest, authContext) => AsyncIterator<IRResponseChunk>
|
||||
* @property {function} estimateCost - (request) => {inputTokens, outputTokensEstimate, currency, usd}|null
|
||||
* @property {function} quotaStatus - async (authContext) => {available, percentUsed, resetsAt, pool}|null
|
||||
* @property {function} healthCheck - async () => {ok: boolean, latencyMs: number, error?: string}
|
||||
* @property {ProviderHints} hints
|
||||
*/
|
||||
|
||||
// ── Contract validator ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Validates that a plugin object satisfies the v1.0 Provider contract.
|
||||
* Per ADR 0002 § "Loading model", the registry calls this at startup for
|
||||
* every registered provider; an invalid provider throws rather than silently
|
||||
* degrading.
|
||||
*
|
||||
* @param {*} p
|
||||
* @returns {{ valid: boolean, errors: string[] }}
|
||||
*/
|
||||
export function validateProvider(p) {
|
||||
const errors = [];
|
||||
|
||||
if (!p || typeof p !== 'object') {
|
||||
errors.push('provider must be an object');
|
||||
return { valid: false, errors };
|
||||
}
|
||||
|
||||
if (typeof p.name !== 'string' || p.name.trim() === '') {
|
||||
errors.push('name must be a non-empty string');
|
||||
} else if (!/^[a-z][a-z0-9_-]*$/.test(p.name)) {
|
||||
errors.push('name must be lowercase alphanumeric (with _ or -) starting with a letter');
|
||||
}
|
||||
|
||||
if (typeof p.displayName !== 'string' || p.displayName.trim() === '') {
|
||||
errors.push('displayName must be a non-empty string');
|
||||
}
|
||||
|
||||
if (!Array.isArray(p.models)) {
|
||||
errors.push('models must be an array of strings');
|
||||
} else if (p.models.some(m => typeof m !== 'string')) {
|
||||
errors.push('every entry in models must be a string');
|
||||
}
|
||||
|
||||
if (!p.auth || typeof p.auth !== 'object') {
|
||||
errors.push('auth must be an object with { type, storage, path, refresh }');
|
||||
} else {
|
||||
if (typeof p.auth.type !== 'string') errors.push('auth.type must be a string');
|
||||
if (typeof p.auth.storage !== 'string') errors.push('auth.storage must be a string');
|
||||
if (typeof p.auth.path !== 'string') errors.push('auth.path must be a string');
|
||||
if (p.auth.refresh !== null && typeof p.auth.refresh !== 'string') {
|
||||
errors.push('auth.refresh must be a string or null');
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof p.spawn !== 'function') {
|
||||
errors.push('spawn must be a function');
|
||||
}
|
||||
|
||||
if (typeof p.estimateCost !== 'function') {
|
||||
errors.push('estimateCost must be a function');
|
||||
}
|
||||
|
||||
if (typeof p.quotaStatus !== 'function') {
|
||||
errors.push('quotaStatus must be a function');
|
||||
}
|
||||
|
||||
if (typeof p.healthCheck !== 'function') {
|
||||
errors.push('healthCheck must be a function');
|
||||
}
|
||||
|
||||
if (!p.hints || typeof p.hints !== 'object') {
|
||||
errors.push('hints must be an object with { requiresTTY, concurrentSpawnSafe, maxConcurrent }');
|
||||
} else {
|
||||
if (typeof p.hints.requiresTTY !== 'boolean') errors.push('hints.requiresTTY must be a boolean');
|
||||
if (typeof p.hints.concurrentSpawnSafe !== 'boolean') errors.push('hints.concurrentSpawnSafe must be a boolean');
|
||||
if (typeof p.hints.maxConcurrent !== 'number' || !Number.isInteger(p.hints.maxConcurrent) || p.hints.maxConcurrent < 0) {
|
||||
errors.push('hints.maxConcurrent must be a non-negative integer');
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
|
||||
// ── Error class ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Error codes surfaced by provider plugins */
|
||||
export const PROVIDER_ERROR_CODES = /** @type {const} */ ([
|
||||
'AUTH_MISSING',
|
||||
'QUOTA_EXHAUSTED',
|
||||
'RATE_LIMITED',
|
||||
'CLI_NOT_FOUND',
|
||||
'SPAWN_FAILED',
|
||||
'OUTPUT_PARSE_ERROR',
|
||||
]);
|
||||
|
||||
export class ProviderError extends Error {
|
||||
/**
|
||||
* @param {string} message
|
||||
* @param {typeof PROVIDER_ERROR_CODES[number]} code
|
||||
*/
|
||||
constructor(message, code) {
|
||||
super(message);
|
||||
this.name = 'ProviderError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Wraps a promise with a timeout. Rejects with a ProviderError if the promise
|
||||
* does not settle within `ms` milliseconds.
|
||||
*
|
||||
* @template T
|
||||
* @param {Promise<T>} promise
|
||||
* @param {number} ms
|
||||
* @param {typeof PROVIDER_ERROR_CODES[number]} errorCode
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
export function withTimeout(promise, ms, errorCode) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new ProviderError(`Operation timed out after ${ms}ms`, errorCode));
|
||||
}, ms);
|
||||
promise.then(
|
||||
v => { clearTimeout(timer); resolve(v); },
|
||||
e => { clearTimeout(timer); reject(e); },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges two AsyncIterators into a single ordered stream.
|
||||
* Items from whichever source yields first are emitted first.
|
||||
* Useful when a provider plugin wants to interleave two internal streams.
|
||||
*
|
||||
* Not used at D3 (no providers yet) but provided as infrastructure so
|
||||
* provider authors don't each implement their own fan-in.
|
||||
*
|
||||
* @template T
|
||||
* @param {AsyncIterator<T>} iter1
|
||||
* @param {AsyncIterator<T>} iter2
|
||||
* @returns {AsyncGenerator<T>}
|
||||
*/
|
||||
export async function* mergeStreams(iter1, iter2) {
|
||||
// Convert each iterator to a pull-based promise queue
|
||||
const done1 = { done: true };
|
||||
const done2 = { done: true };
|
||||
|
||||
let p1 = iter1.next();
|
||||
let p2 = iter2.next();
|
||||
|
||||
while (true) {
|
||||
const winner = await Promise.race([
|
||||
p1.then(r => ({ r, which: 1 })),
|
||||
p2.then(r => ({ r, which: 2 })),
|
||||
]);
|
||||
|
||||
if (winner.which === 1) {
|
||||
if (winner.r.done) {
|
||||
// iter1 exhausted — drain iter2
|
||||
for await (const v of { [Symbol.asyncIterator]: () => iter2 }) yield v;
|
||||
return;
|
||||
}
|
||||
yield winner.r.value;
|
||||
p1 = iter1.next();
|
||||
} else {
|
||||
if (winner.r.done) {
|
||||
// iter2 exhausted — drain iter1
|
||||
for await (const v of { [Symbol.asyncIterator]: () => iter1 }) yield v;
|
||||
return;
|
||||
}
|
||||
yield winner.r.value;
|
||||
p2 = iter2.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 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 D3 (Phase 1 Day 1), the registry is intentionally empty.
|
||||
* 0 Enabled Providers per ALIGNMENT.md § Provider Inventory.
|
||||
* Phase 1 Day 2+ will add the anthropic plugin.
|
||||
*/
|
||||
|
||||
import { validateProvider } from './base.mjs';
|
||||
|
||||
// ── Static registry ───────────────────────────────────────────────────────
|
||||
|
||||
// Phase 1 Day 2+ will add imports here, e.g.:
|
||||
// import * as anthropic from './anthropic.mjs';
|
||||
// And push to STATIC_REGISTRY, e.g.:
|
||||
// STATIC_REGISTRY.push(anthropic.default ?? anthropic);
|
||||
|
||||
const STATIC_REGISTRY = [];
|
||||
|
||||
// ── Registry functions ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Loads and validates providers, filtering by the enabled set in config.
|
||||
*
|
||||
* @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 D3. 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all provider names in the static registry (whether enabled or not).
|
||||
* Used by /health and diagnostics.
|
||||
*
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function listAllProviderNames() {
|
||||
return STATIC_REGISTRY.map(p => p.name);
|
||||
}
|
||||
Reference in New Issue
Block a user