joycode 0.2.0: route models by adapterType to Chat, Responses and Messages (#464)
joycode 0.2.0 (liangmouse). Each JoyCode model is routed by the `extJson.adapterType` in its catalogue entry:
- missing/other → Chat Completions (`@ai-sdk/openai-compatible`, `chat_completions`)
- `openai-response` → Responses (`@ai-sdk/openai`, `responses_completions`)
- `anthropic` → Anthropic Messages (`@ai-sdk/anthropic`, `anthropic_completions`)
The routing matches JoyCoder.joycoder-fe 3.8.71's `buildApiHandler`. Other changes:
- Anthropic `/messages/count_tokens` gets a local 404 and nothing goes upstream, so magpie's `unsupportedCount` uses its local estimate.
- All three protocols send `language: UNKNOWN`, as JoyCode's own handlers do.
- Non-streaming JSON for Anthropic and Responses counts as success.
- `flatten` applies to chat only.
- JoyCode's extra SSE layer (`data: event:` / `data: data:`) is removed line by line as the stream arrives. Standard SSE passes through unchanged.
Reviewed and run at f1ccb2ab59b0570295264317f270b266c7a585da (on mote, macOS, Bun 1.4.2, HOME a temp dir):
- `bun test packages/joycode`: 42 pass. `node --test packages/joycode/*.test.mjs`: 42 pass. `bun scripts/check.mjs joycode`: ok.
- Broken by hand, one at a time, each went red:
- count_tokens guard off → the count_tokens test;
- Anthropic normalizer off → the Anthropic double-wrapped test;
- Responses normalizer off → the Responses double-wrapped test;
- `language` dropped → 2 tests.
- Official SDKs (`@anthropic-ai/sdk` 1.3.0, `openai` 7.45.1) read JoyCode-framed streams through the plugin's fetch, served locally and cut into 7-byte chunks:
- `messages.stream` got the full event sequence, text "OK", `end_turn`;
- `responses.create({stream})` got 9 events ending in `response.completed`, text "OK".
- The same bytes without the plugin: "request ended without sending any chunks" from Anthropic and "malformed server-sent event JSON" from OpenAI.
- Upstream functionIds seen were `anthropic_completions` and `responses_completions`.
Real account: the author's run is in the PR thread and the CHANGELOG (`provider test` GPT-6 Astra 200 in 3.0s, Claude-Opus-5-hq 200 in 7.3s). Not tried here: no JoyCode account.
This commit is contained in:
@@ -2,15 +2,26 @@ import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import plugin from './index.mjs'
|
||||
|
||||
async function request(t, response) {
|
||||
t.mock.method(globalThis, 'fetch', async url => new URL(url).searchParams.get('functionId') === 'joycode_userInfo'
|
||||
? Response.json({ code: 0, data: { userId: 'test-user', tenant: 'test-tenant', orgFullName: 'test-org' } })
|
||||
: response)
|
||||
async function request(t, response, {
|
||||
input = 'https://api-ai.jd.com/v1/chat/completions',
|
||||
payload = { model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], stream: true },
|
||||
init = {},
|
||||
upstream,
|
||||
} = {}) {
|
||||
t.mock.method(globalThis, 'fetch', async (url, requestInit) => {
|
||||
if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') {
|
||||
return Response.json({ code: 0, data: { userId: 'test-user', tenant: 'test-tenant', orgFullName: 'test-org' } })
|
||||
}
|
||||
upstream?.(url, requestInit)
|
||||
return typeof response === 'function' ? response(url, requestInit) : response
|
||||
})
|
||||
const hooks = await plugin.server({})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' }))
|
||||
return loader.fetch('https://api-ai.jd.com/v1/chat/completions', {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ model: 'JoyAI-Code-1.6', messages: [{ role: 'user', content: 'OK' }], stream: true }),
|
||||
return loader.fetch(input, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: typeof payload === 'string' ? payload : JSON.stringify(payload),
|
||||
...init,
|
||||
})
|
||||
}
|
||||
function chunks(parts) {
|
||||
@@ -92,6 +103,219 @@ test('chat adds authenticated account metadata while preserving tools and messag
|
||||
assert.equal(infoCalls, 1)
|
||||
})
|
||||
|
||||
for (const [name, input, payload, functionId, npmShape] of [
|
||||
[
|
||||
'Responses',
|
||||
'https://api-ai.jd.com/v1/responses',
|
||||
{ model: 'GPT-5.6 Sol', input: 'OK', stream: true },
|
||||
'responses_completions',
|
||||
'input',
|
||||
],
|
||||
[
|
||||
'Anthropic Messages',
|
||||
'https://api-ai.jd.com/v1/messages',
|
||||
{ model: 'Claude-Opus-5-hq', max_tokens: 8, messages: [{ role: 'user', content: 'OK' }], stream: true },
|
||||
'anthropic_completions',
|
||||
'messages',
|
||||
],
|
||||
]) {
|
||||
test(`${name} requests are signed on their own gateway and keep their shape`, async t => {
|
||||
let seen
|
||||
const r = await request(t, new Response('data: [DONE]\n\n', {
|
||||
headers: { 'content-type': 'text/event-stream' },
|
||||
}), {
|
||||
input,
|
||||
payload,
|
||||
init: { headers: { 'content-type': 'application/json', 'x-api-key': 'host-key' } },
|
||||
upstream(url, init) {
|
||||
seen = { url, init }
|
||||
},
|
||||
})
|
||||
assert.equal(new URL(seen.url).searchParams.get('functionId'), functionId)
|
||||
const sent = JSON.parse(seen.init.body)
|
||||
assert.equal(sent.model, payload.model)
|
||||
assert.deepEqual(sent[npmShape], payload[npmShape])
|
||||
assert.equal(sent.userId, 'test-user')
|
||||
assert.equal(sent.tenant, 'test-tenant')
|
||||
assert.equal(seen.init.headers.get('x-api-key'), null)
|
||||
assert.equal(seen.init.headers.get('ptkey'), 'fake-key')
|
||||
assert.equal(r.status, 200)
|
||||
assert.equal(await r.text(), 'data: [DONE]\n\n')
|
||||
})
|
||||
}
|
||||
|
||||
test('Chat Completions keeps using the chat gateway', async t => {
|
||||
let seen
|
||||
const r = await request(t, new Response('data: [DONE]\n\n', {
|
||||
headers: { 'content-type': 'text/event-stream' },
|
||||
}), {
|
||||
upstream(url) { seen = new URL(url) },
|
||||
})
|
||||
assert.equal(seen.searchParams.get('functionId'), 'chat_completions')
|
||||
assert.equal(r.status, 200)
|
||||
})
|
||||
|
||||
test('Request input carries its URL, body, method, and headers into routing', async t => {
|
||||
let seen
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') {
|
||||
return Response.json({ code: 0, data: { userId: 'test-user', tenant: 'test-tenant' } })
|
||||
}
|
||||
seen = { url, init }
|
||||
return new Response('event: message_stop\n\ndata: {}\n\n', {
|
||||
headers: { 'content-type': 'text/event-stream' },
|
||||
})
|
||||
})
|
||||
const hooks = await plugin.server({})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' }))
|
||||
const payload = {
|
||||
model: 'Claude-Opus-5-hq',
|
||||
max_tokens: 8,
|
||||
messages: [{ role: 'user', content: 'OK' }],
|
||||
stream: true,
|
||||
}
|
||||
const r = await loader.fetch(new Request('https://api-ai.jd.com/v1/messages', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-api-key': 'host-key' },
|
||||
body: JSON.stringify(payload),
|
||||
}))
|
||||
assert.equal(new URL(seen.url).searchParams.get('functionId'), 'anthropic_completions')
|
||||
assert.equal(seen.init.method, 'POST')
|
||||
const sent = JSON.parse(seen.init.body)
|
||||
assert.equal(sent.model, payload.model)
|
||||
assert.deepEqual(sent.messages, payload.messages)
|
||||
assert.equal(sent.userId, 'test-user')
|
||||
assert.equal(sent.language, 'UNKNOWN')
|
||||
assert.equal(seen.init.headers.get('x-api-key'), null)
|
||||
assert.equal(seen.init.headers.get('ptkey'), 'fake-key')
|
||||
assert.equal(await r.text(), 'event: message_stop\n\ndata: {}\n\n')
|
||||
})
|
||||
|
||||
test('Anthropic double-wrapped SSE is normalized across chunk boundaries', async t => {
|
||||
const upstreamText = [
|
||||
'data: event: message_start\n\n',
|
||||
'data: data: {"type":"message_start","message":{"id":"msg_1"}}\n\n',
|
||||
'data: event: content_block_delta\n\n',
|
||||
'data: data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"OK"}}\n\n',
|
||||
'data: event: message_stop\n\n',
|
||||
'data: data: {"type":"message_stop"}\n\n',
|
||||
'data: [DONE]\n\n',
|
||||
].join('')
|
||||
const split = upstreamText.indexOf('data: data:', 20) + 8
|
||||
const r = await request(t, new Response(chunks([
|
||||
upstreamText.slice(0, split),
|
||||
upstreamText.slice(split),
|
||||
]), { headers: { 'content-type': 'text/event-stream' } }), {
|
||||
input: 'https://api-ai.jd.com/v1/messages',
|
||||
payload: { model: 'Claude-Opus-5-hq', max_tokens: 8, messages: [{ role: 'user', content: 'OK' }], stream: true },
|
||||
})
|
||||
assert.equal(r.status, 200)
|
||||
assert.equal(await r.text(), [
|
||||
'event: message_start\n',
|
||||
'data: {"type":"message_start","message":{"id":"msg_1"}}\n\n',
|
||||
'event: content_block_delta\n',
|
||||
'data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"OK"}}\n\n',
|
||||
'event: message_stop\n',
|
||||
'data: {"type":"message_stop"}\n\n',
|
||||
'data: [DONE]\n\n',
|
||||
].join(''))
|
||||
})
|
||||
|
||||
test('standard Anthropic SSE is preserved byte for byte', async t => {
|
||||
const text = 'event: message_start\r\ndata: {"type":"message_start"}\r\n\r\nevent: message_stop\r\ndata: {"type":"message_stop"}\r\n\r\n'
|
||||
const r = await request(t, new Response(chunks([text.slice(0, 17), text.slice(17)]), {
|
||||
headers: { 'content-type': 'text/event-stream' },
|
||||
}), {
|
||||
input: 'https://api-ai.jd.com/v1/messages',
|
||||
payload: { model: 'Claude-Opus-5-hq', max_tokens: 8, messages: [{ role: 'user', content: 'OK' }], stream: true },
|
||||
})
|
||||
assert.equal(r.status, 200)
|
||||
assert.equal(await r.text(), text)
|
||||
})
|
||||
|
||||
test('Responses double-wrapped SSE is normalized across chunk boundaries', async t => {
|
||||
const upstreamText = [
|
||||
'data: data: {"type":"response.created","sequence_number":0}\n\n',
|
||||
'data: data: {"type":"response.output_text.delta","delta":"OK"}\n\n',
|
||||
'data: data: {"type":"response.completed","sequence_number":2}\n\n',
|
||||
].join('')
|
||||
const split = upstreamText.indexOf('output_text') - 4
|
||||
const r = await request(t, new Response(chunks([
|
||||
upstreamText.slice(0, split),
|
||||
upstreamText.slice(split),
|
||||
]), { headers: { 'content-type': 'text/event-stream' } }), {
|
||||
input: 'https://api-ai.jd.com/v1/responses',
|
||||
payload: { model: 'GPT-6 Astra', input: 'OK', stream: true },
|
||||
})
|
||||
assert.equal(r.status, 200)
|
||||
assert.equal(await r.text(), [
|
||||
'data: {"type":"response.created","sequence_number":0}\n\n',
|
||||
'data: {"type":"response.output_text.delta","delta":"OK"}\n\n',
|
||||
'data: {"type":"response.completed","sequence_number":2}\n\n',
|
||||
].join(''))
|
||||
})
|
||||
|
||||
test('Anthropic count_tokens returns 404 without contacting upstream', async t => {
|
||||
let fetchCalls = 0
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
fetchCalls++
|
||||
throw new Error('count_tokens must not call upstream')
|
||||
})
|
||||
const hooks = await plugin.server({})
|
||||
const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' }))
|
||||
const r = await loader.fetch('https://api-ai.jd.com/v1/messages/count_tokens', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
model: 'Claude-Opus-5-hq',
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
}),
|
||||
})
|
||||
assert.equal(r.status, 404)
|
||||
assert.equal(fetchCalls, 0)
|
||||
assert.equal((await r.json()).error.type, 'unsupported_endpoint')
|
||||
})
|
||||
|
||||
for (const [name, input, payload, body] of [
|
||||
[
|
||||
'Responses',
|
||||
'https://api-ai.jd.com/v1/responses',
|
||||
{ model: 'GPT-5.6 Sol', input: 'OK', stream: false },
|
||||
{ id: 'resp_1', object: 'response', status: 'completed', output: [] },
|
||||
],
|
||||
[
|
||||
'Anthropic Messages',
|
||||
'https://api-ai.jd.com/v1/messages',
|
||||
{ model: 'Claude-Opus-5-hq', max_tokens: 8, messages: [{ role: 'user', content: 'OK' }] },
|
||||
{ id: 'msg_1', type: 'message', role: 'assistant', content: [], stop_reason: 'end_turn' },
|
||||
],
|
||||
]) {
|
||||
test(`${name} non-streaming JSON is a valid success response`, async t => {
|
||||
const r = await request(t, Response.json(body), { input, payload })
|
||||
assert.equal(r.status, 200)
|
||||
assert.deepEqual(await r.json(), body)
|
||||
})
|
||||
}
|
||||
|
||||
test('flatten applies only to Chat Completions, never Responses', async t => {
|
||||
let sent
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
if (new URL(url).searchParams.get('functionId') === 'joycode_userInfo') {
|
||||
return Response.json({ code: 0, data: { userId: 'test-user' } })
|
||||
}
|
||||
sent = JSON.parse(init.body)
|
||||
return new Response('data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } })
|
||||
})
|
||||
const hooks = await plugin.server({}, { flatten: true })
|
||||
const loader = await hooks.auth.loader(async () => ({ type: 'api', key: 'fake-key' }))
|
||||
const r = await loader.fetch('https://api-ai.jd.com/v1/responses', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ model: 'GPT-5.6 Sol', input: 'OK', stream: true }),
|
||||
})
|
||||
await r.text()
|
||||
assert.equal(sent.input, 'OK')
|
||||
assert.equal(sent.messages, undefined)
|
||||
})
|
||||
|
||||
test('HTTP 403 permission denial is not marked as expired credentials', async t => {
|
||||
const r = await request(t, Response.json({ error: { code: 'AI_GRAY_ACCESS_DENIED', message: 'denied' } }, { status: 403 }))
|
||||
assert.equal(r.status, 403)
|
||||
|
||||
Reference in New Issue
Block a user