Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 11 additions & 6 deletions convex/lib/nodeslideAutoRoutingPolicy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,22 +184,27 @@ describe('NodeSlide fail-closed auto routing policy', () => {
});

describe('per-request cost cap', () => {
// The estimate is the bundled pi-ai catalog's price for z-ai/glm-5.2. pi-ai 0.80.6 priced it at
// 0.532 / 1.672 USD per million (1k in + 1k out = 2_204 micro-USD; caps 0.002203 / 0.002204).
// pi-ai 1.1.0 prices it at 0.171 / 7.2, so 1k in + 1k out = 7_371 micro-USD (measured from the
// installed 1.1.0 catalog, 2026-10-15). The one-micro-dollar boundary is preserved: below by 1,
// exactly equal, well above.
it.each([
{ name: 'one micro-dollar below estimate', cap: 0.002203, kind: 'refused' },
{ name: 'exactly equal to estimate', cap: 0.002204, kind: 'selected' },
{ name: 'one micro-dollar below estimate', cap: 0.00737, kind: 'refused' },
{ name: 'exactly equal to estimate', cap: 0.007371, kind: 'selected' },
{ name: 'well above estimate', cap: 1, kind: 'selected' },
] as const)('$name is $kind', ({ cap, kind }) => {
const decision = decideNodeSlideAutoRoute(input({ maxUsd: cap }));

expect(decision.kind).toBe(kind);
expect(decision.costEstimate).toMatchObject({
status: 'estimated',
totalMicroUsd: 2_204,
totalUsd: 0.002204,
totalMicroUsd: 7_371,
totalUsd: 0.007371,
pricing: {
source: 'pi-ai-openrouter-catalog',
inputUsdPerMillionTokens: 0.532,
outputUsdPerMillionTokens: 1.672,
inputUsdPerMillionTokens: 0.171,
outputUsdPerMillionTokens: 7.2,
},
});
if (kind === 'refused') {
Expand Down
60 changes: 60 additions & 0 deletions convex/lib/nodeslideProvider.openrouterEndpoints.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* pi-ai 1.1.0 upgrade proof (SPEC Part A, section A.2.8 "Pre-PR").
*
* Situation: a person picks Claude Sonnet 5 or Claude Fable 5 in the NodeSlide model picker. pi-ai
* 1.1.0 ships OpenRouter's Claude rows as the `anthropic-messages` API at `https://openrouter.ai/api`;
* NodeSlide sends every OpenRouter route through the chat-completions client, so without a fix the
* request goes to `/api/chat/completions`, which is not an OpenRouter endpoint, and the route fails
* on the first call after the SDK bump. Nothing here calls a provider: the real request is built by
* this repo's own provider code and the HTTP transport is a fake `fetch` that records the URL.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { openrouterProviderWithOverrides, probeNodeSlideModelOnce } from './nodeslideProvider';

const sseDone = [
'data: {"id":"gen-fake","model":"fake/echo","choices":[{"index":0,"delta":{"role":"assistant","content":"1"},"finish_reason":null}]}\n\n',
'data: {"id":"gen-fake","model":"fake/echo","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4}}\n\n',
'data: [DONE]\n\n',
].join('');

const originalKey = process.env['OPENROUTER_API_KEY'];
let captured: { url: string; body: Record<string, unknown> }[] = [];

beforeEach(() => {
captured = [];
process.env['OPENROUTER_API_KEY'] = 'sk-or-test-fake-not-a-credential';
vi.stubGlobal('fetch', async (input: unknown, init?: { body?: unknown }) => {
const url =
typeof input === 'string' ? input : ((input as { url?: string }).url ?? String(input));
captured.push({ url, body: JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown> });
return new Response(sseDone, { status: 200, headers: { 'content-type': 'text/event-stream' } });
});
});

afterEach(() => {
vi.unstubAllGlobals();
if (originalKey === undefined) Reflect.deleteProperty(process.env, 'OPENROUTER_API_KEY');
else process.env['OPENROUTER_API_KEY'] = originalKey;
});

describe('Claude rows keep the OpenRouter chat-completions endpoint under pi-ai 1.1.0', () => {
it('pins every bundled anthropic-messages OpenRouter row to /api/v1 chat-completions', () => {
const claudeRows = openrouterProviderWithOverrides()
.getModels()
.filter((model) => model.id.startsWith('anthropic/claude-'));
expect(claudeRows.length).toBeGreaterThan(0);
for (const model of claudeRows) {
expect(model.api, model.id).toBe('openai-completions');
expect(model.baseUrl, model.id).toBe('https://openrouter.ai/api/v1');
}
});

it('sends the existing Claude rows (sonnet-5, fable-5) to a valid OpenRouter endpoint', async () => {
for (const modelId of ['anthropic/claude-sonnet-5', 'anthropic/claude-fable-5'] as const) {
captured = [];
await probeNodeSlideModelOnce(modelId);
expect(captured[0]?.url, modelId).toBe('https://openrouter.ai/api/v1/chat/completions');
expect(captured[0]?.body['model']).toBe(modelId);
}
});
});
27 changes: 26 additions & 1 deletion convex/lib/nodeslideProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,37 @@ export const NODESLIDE_OPENROUTER_MODEL_OVERRIDES: readonly Model<'openai-comple
NODESLIDE_KIMI_K3,
];

const OPENROUTER_CHAT_COMPLETIONS_BASE_URL = 'https://openrouter.ai/api/v1';

/**
* pi-ai 1.1.0 ships OpenRouter's Claude rows as `anthropic-messages` with base URL
* `https://openrouter.ai/api`. This provider speaks OpenRouter's normalized chat-completions
* contract for every route (reasoning.effort, max_price, response_format ride in that payload), so a
* Claude row left as the bundled catalog has it would be POSTed to `/api/chat/completions`, which is
* not an OpenRouter endpoint. Pin such rows to the chat-completions API and `/api/v1`, with the same
* compat pi-ai 0.80.6 carried for them (Anthropic cache_control on OpenRouter's reasoning format).
*/
function asOpenRouterChatCompletionsRoute(
model: ReturnType<ReturnType<typeof openrouterProvider>['getModels']>[number],
): ReturnType<ReturnType<typeof openrouterProvider>['getModels']>[number] {
if (model.api === 'openai-completions') return model;
return {
...model,
api: 'openai-completions',
baseUrl: OPENROUTER_CHAT_COMPLETIONS_BASE_URL,
compat: { thinkingFormat: 'openrouter', cacheControlFormat: 'anthropic' },
} as typeof model;
}

export function openrouterProviderWithOverrides() {
const builtin = openrouterProvider();
const overridden = new Map(
NODESLIDE_OPENROUTER_MODEL_OVERRIDES.map((model) => [model.id, model] as const),
);
const models = builtin.getModels().filter((model) => !overridden.has(model.id));
const models = builtin
.getModels()
.filter((model) => !overridden.has(model.id))
.map(asOpenRouterChatCompletionsRoute);
return createProvider({
id: 'openrouter',
name: 'OpenRouter',
Expand Down
2 changes: 1 addition & 1 deletion mcp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@earendil-works/pi-ai": "0.80.6",
"@earendil-works/pi-ai": "1.1.0",
"@modelcontextprotocol/sdk": "^1.30.0",
"@nodeslide/recipelang": "0.2.2",
"convex": "^1.31.7",
Expand Down
Loading
Loading