Files
olp/lib/ir/ir-to-openai.mjs
T
taodengandClaude Opus 4.7 (noreply@anthropic.com) e2e67de23a 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)
2026-05-23 17:06:30 +10:00

199 lines
6.2 KiB
JavaScript

/**
* lib/ir/ir-to-openai.mjs — IR v1.0 → OpenAI Chat Completions response translation
*
* Authority: ADR 0003 § "Translation direction model" (symmetric)
* Entry-surface authority: OpenAI Chat Completions API response shape
* https://platform.openai.com/docs/api-reference/chat/object
* https://platform.openai.com/docs/api-reference/chat/streaming
*
* Produces OpenAI-shaped responses from IR response chunks so that the
* entry surface (server.mjs) can emit them to clients without knowing
* which provider generated them.
*/
import { randomBytes } from 'node:crypto';
// ── ID generation ─────────────────────────────────────────────────────────
/**
* Generates a random chat-completion request ID.
* OpenAI format: chatcmpl-<alphanumeric>
* @returns {string}
*/
export function generateRequestId() {
return `chatcmpl-${randomBytes(12).toString('base64url')}`;
}
// ── Streaming translation ─────────────────────────────────────────────────
/**
* Converts a single IRResponseChunk to an OpenAI SSE event string.
*
* Per OpenAI streaming spec, each chunk is a `chat.completion.chunk` object
* with a `choices[0].delta` field.
*
* @param {import('./types.mjs').IRResponseChunk} irChunk
* @param {string} requestId - from generateRequestId()
* @param {string} model - the model string from the IR request
* @returns {string} SSE line in the form `data: {...}\n\n`
*/
export function irChunkToOpenAISSE(irChunk, requestId, model) {
const created = Math.floor(Date.now() / 1000);
if (irChunk.type === 'stop') {
const chunk = {
id: requestId,
object: 'chat.completion.chunk',
created,
model,
choices: [{
index: 0,
delta: {},
finish_reason: irChunk.finish_reason ?? 'stop',
}],
};
// Include usage if the provider surfaced token counts on the final chunk
if (irChunk.usage) {
chunk.usage = irChunk.usage;
}
return `data: ${JSON.stringify(chunk)}\n\n`;
}
if (irChunk.type === 'error') {
// SSE error chunk. ALIGNMENT.md Rule 2 (b) forbids inventing
// `finish_reason` values not in OpenAI's enum
// (https://platform.openai.com/docs/api-reference/chat/streaming
// enumerates: stop, length, tool_calls, content_filter, function_call,
// null). Surface the error via the top-level `error` object and use
// finish_reason: 'stop' on the choice — clients that respect the
// enum see a valid terminator; clients that read the `error` field
// see the failure detail.
const chunk = {
id: requestId,
object: 'chat.completion.chunk',
created,
model,
choices: [{
index: 0,
delta: { content: '' },
finish_reason: 'stop',
}],
error: { message: irChunk.error ?? 'Unknown provider error', type: 'provider_error' },
};
return `data: ${JSON.stringify(chunk)}\n\n`;
}
// type === 'delta'
const delta = {};
if (irChunk.role !== undefined) {
delta.role = irChunk.role;
}
if (typeof irChunk.content === 'string' && irChunk.content !== '') {
delta.content = irChunk.content;
} else if (irChunk.content === '') {
// Empty string delta is valid — pass through (first chunk often role-only + empty content)
delta.content = '';
}
if (Array.isArray(irChunk.tool_calls) && irChunk.tool_calls.length > 0) {
delta.tool_calls = irChunk.tool_calls;
}
const chunk = {
id: requestId,
object: 'chat.completion.chunk',
created,
model,
choices: [{
index: 0,
delta,
finish_reason: null,
}],
};
return `data: ${JSON.stringify(chunk)}\n\n`;
}
/** SSE stream terminator per OpenAI spec */
export const SSE_DONE = 'data: [DONE]\n\n';
// ── Non-streaming translation ─────────────────────────────────────────────
/**
* Assembles a non-streaming OpenAI chat.completion object from an array of
* IR response chunks (all chunks already collected from the provider).
*
* @param {import('./types.mjs').IRResponseChunk[]} irChunks
* @param {string} requestId
* @param {string} model
* @returns {object} OpenAI chat.completion object
*/
export function irResponseToOpenAINonStream(irChunks, requestId, model) {
let content = '';
let finish_reason = 'stop';
let usage = null;
let errorChunk = null;
const tool_calls = [];
for (const chunk of irChunks) {
if (chunk.type === 'delta') {
if (typeof chunk.content === 'string') {
content += chunk.content;
}
if (Array.isArray(chunk.tool_calls)) {
tool_calls.push(...chunk.tool_calls);
}
} else if (chunk.type === 'stop') {
if (chunk.finish_reason) {
finish_reason = chunk.finish_reason;
}
if (chunk.usage) {
usage = chunk.usage;
}
} else if (chunk.type === 'error') {
// Surface provider errors via the top-level `error` annotation on the
// response object below + an inline content marker. `finish_reason`
// stays 'stop' because ALIGNMENT.md Rule 2 (b) forbids inventing
// enum values OpenAI's spec does not define
// (https://platform.openai.com/docs/api-reference/chat/object —
// finish_reason ∈ {stop, length, tool_calls, content_filter,
// function_call, null}).
content += chunk.error ? `[provider error: ${chunk.error}]` : '[provider error]';
errorChunk = chunk;
}
}
const message = {
role: 'assistant',
content: content || null,
};
if (tool_calls.length > 0) {
message.tool_calls = tool_calls;
if (!content) message.content = null;
}
const response = {
id: requestId,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model,
choices: [{
index: 0,
message,
finish_reason,
}],
};
if (usage) {
response.usage = usage;
}
if (errorChunk) {
response.error = {
message: errorChunk.error ?? 'Unknown provider error',
type: 'provider_error',
};
}
return response;
}