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:
liangmouse
2026-10-29 01:12:42 +08:00
committed by GitHub
parent 880cd9319c
commit f653369a77
6 changed files with 508 additions and 47 deletions
+10
View File
@@ -1,5 +1,15 @@
# 更新记录
## 0.2.0
- 按 JoyCode 模型目录中的 `extJson.adapterType` 自动选择 Chat Completions、Responses 或 Anthropic Messages,使 `/models` 返回的 GPT、Claude 及其他模型都能使用正确的 SDK 和网关。
- 请求转发支持 `Request` 输入,并正确清理宿主生成的鉴权头及长度/主机头。
- Anthropic `/messages/count_tokens` 在插件本地返回 404,避免被转发为一次付费生成;三种协议统一携带 `language`。
- 修复 Anthropic Messages 与 Responses 的正常非流式 JSON 被误判为无效响应的问题;`flatten` 仅用于 Chat Completions。
- 增量还原 JoyCode 多包一层的 Anthropic 和 Responses SSE,使官方 Anthropic SDK、OpenAI SDK 及 Claude Code 能消费流式事件,同时保持标准 SSE 和跨 chunk 边界不变。
验证:42 项回归测试通过;真实 JoyCode 账号的 `joycode_modelList` 返回 15 个模型,覆盖 10 个 chat、4 个 `openai-response` 和 1 个 `anthropic`。最终 `provider test` 中,`GPT-6 Astra` 的 Responses 请求返回 200(3.0 秒),`Claude-Opus-5-hq` 的 Anthropic Messages 请求返回 200(7.3 秒)。另经 magpie 网关用官方 OpenAI SDK 和官方 Anthropic SDK 各发一条真实流式短请求,均收到完整事件和文本 `OK`(分别为 2.9 秒、7.6 秒)。更早一次 Claude 冷启动曾耗时 34.7 秒;分段计时显示延迟发生在上游响应头,不是插件等待完整回复后才返回。
## 0.1.1
- 支持浏览器登录京东账号,自动接收并验证 JoyCode 票据,保存租户和登录类型。
+16 -12
View File
@@ -1,6 +1,6 @@
# JoyCode
把京东云 **JoyCode**(JoyCoder IDE 自带的模型额度)作为一个 OpenAI 兼容供应商接进 [magpie](https://usemagpie.ai)。装好后,所有 agent(Claude Code、Codex 等)都能通过 magpie 用 `joycode/<model>` 访问 JoyCode 的模型,并享受 magpie 的多账号号池、故障切换和用量统计。
把京东云 **JoyCode**(JoyCoder IDE 自带的模型额度)作为一个多协议供应商接进 [magpie](https://usemagpie.ai)。装好后,所有 agent(Claude Code、Codex 等)都能通过 magpie 用 `joycode/<model>` 访问 JoyCode 的模型,并享受 magpie 的多账号号池、故障切换和用量统计。
逆向了 JoyCode IDE 的「彩网关」协议(`https://api-ai.jd.com/api`,HMAC-SHA256 签名 query + `ptKey` 账号票据头)。请求与 IDE 本身走同一账号、同一额度。
@@ -25,15 +25,17 @@ magpie plugin login joycode
## 模型
| 模型 ID(magpie 里用 `joycode/…`) | 上下文 | 输出 | 推理 | 视觉 |
|---|---|---|---|---|
| `joycode/JoyAI-Code-1.6` | 200k | 64k | — | — |
| `joycode/GLM-5.3-agent` | 200k | 64k | ✓ | — |
| `joycode/Kimi-K2.6-agent` | 200k | 64k | ✓ | 实验 |
| `joycode/MiniMax-M3-agent` | 200k | 64k | ✓ | 实验 |
| `joycode/Doubao-Seed-2.0-pro-agent` | 200k | 64k | ✓ | 实验 |
模型由登录账号的 `joycode_modelList` 动态同步,不需要在插件里逐个维护。插件读取每个模型的 `extJson.adapterType`,为它选择对应的协议、AI SDK 和 JoyCode 网关:
登录后通过 `joycode_modelList` 同步账号可用模型,并通过 `plugin_config` 的 `billingRate` 场景同步积分消耗倍率。点击「重新获取模型」可更新模型和倍率;按 `chatApiModel` 匹配,不会把仅出现在计费表中的模型加入列表。模型自身的倍率优先;公共倍率配置遵守 `excludeTenants`,无租户或被排除的租户不套用公共倍率。明确的 0× 会标记免费;查不到的倍率不当作 0×,也不虚构优惠前倍率。
| `extJson.adapterType` | 上游协议 | AI SDK | JoyCode `functionId` |
|---|---|---|---|
| 缺失 / 其他 | OpenAI Chat Completions | `@ai-sdk/openai-compatible` | `chat_completions` |
| `openai-response` | OpenAI Responses | `@ai-sdk/openai` | `responses_completions` |
| `anthropic` | Anthropic Messages | `@ai-sdk/anthropic` | `anthropic_completions` |
因此 GPT 模型会走 Responses,Claude 模型会走 Anthropic Messages,GLM、Kimi、DeepSeek、MiniMax、Doubao 等继续走 Chat Completions。2026-10-28 使用真实账号核对时,`joycode_modelList` 返回 15 个模型:10 个 chat、4 个 `openai-response`、1 个 `anthropic`,三类均已覆盖。
同时通过 `plugin_config` 的 `billingRate` 场景同步积分消耗倍率。点击「重新获取模型」可更新模型和倍率;按 `chatApiModel` 匹配,不会把仅出现在计费表中的模型加入列表。模型自身的倍率优先;公共倍率配置遵守 `excludeTenants`,无租户或被排除的租户不套用公共倍率。明确的 0× 会标记免费;查不到的倍率不当作 0×,也不虚构优惠前倍率。
当前实测:JoyAI-Code-1.6 0×、GLM-5.3 0.6×、Kimi-K2.6 0.5×、MiniMax-M3 0.4×、Doubao-Seed-2.0-pro 0.4×。这些是查询结果,代码没有写死价格。它们是积分倍率,不是美元/token 价格。
@@ -41,11 +43,13 @@ magpie plugin login joycode
## 消息转发策略
默认保留完整多轮对话及工具调用:magpie 转换为 OpenAI chat completions 后,插件从当前账号的 `joycode_userInfo` 获取真实 `userId`、`tenant`、`orgFullName`,按 IDE 请求格式补入正文,并设置 `language: UNKNOWN`。身份信息按账号 loader 隔离缓存,不接受客户端指定的用户身份。缺少这些元数据时,已观察到网关返回 `AI_GRAY_ACCESS_DENIED`。
默认保留完整多轮对话、工具调用和模型原生请求格式。插件从当前账号的 `joycode_userInfo` 获取真实 `userId`、`tenant`、`orgFullName`,按 JoyCode 请求格式补入正文;三种协议统一设置 `language: UNKNOWN`。身份信息按账号 loader 隔离缓存,不接受客户端指定的用户身份。缺少这些元数据时,已观察到网关返回 `AI_GRAY_ACCESS_DENIED`。
网关可能以 HTTP 200 和 SSE 响应头返回裸 JSON 错误;插件会把这种错误转换为明确的失败响应,避免客户端一直等待。普通 403 权限错误不会再被误标为登录失效。
已实测 JoyAI-Code-1.6 完整流式文字回复、工具调用及工具结果往返,并通过 magpie `provider test`。用户已确认 Claude 桌面端正常使用。
JoyCode 的 Anthropic 与 Responses 网关还会给 SSE 多加一层 framing(Anthropic 为 `data: event: …` 和 `data: data: …`,Responses 为 `data: data: …`)。插件在流式转发时增量还原标准 SSE,不缓存完整回复;否则官方 Anthropic/OpenAI SDK 会分别表现为空流和 `malformed server-sent event JSON`。标准 SSE 会按原字节透传,跨上游 chunk 的边界也有回归测试。
0.1.1 已实测 JoyAI-Code-1.6 完整流式文字回复、工具调用及工具结果往返,并通过 magpie `provider test`。0.2.0 于 2026-10-28 通过真实账号验证:`provider test` 的 `GPT-6 Astra` Responses 请求返回 200(3.0 秒),`Claude-Opus-5-hq` Anthropic Messages 请求返回 200(7.3 秒);再经 magpie 网关用官方 OpenAI SDK 的 Responses 流和官方 Anthropic SDK 的 Messages 流各发一条短请求,均正确收到文本 `OK` 和完整事件序列(2.9 秒、7.6 秒)。更早的 Claude 冷启动曾出现 34.7 秒,分段计时显示时间耗在上游响应头而不是插件缓冲。Anthropic 的 `/v1/messages/count_tokens` 在插件本地返回 404,不访问 JoyCode,避免把 token 计数误发成一次付费生成。
如果实测 JoyCode 后端拒绝多轮/工具调用格式的消息,可以开启回退模式:
@@ -53,7 +57,7 @@ magpie plugin login joycode
magpie plugin options joycode '{"flatten": true}'
```
flatten 模式会把消息压平成 `system + 单条 user prompt`(工具调用和工具结果会被丢弃)。**开了 flatten 就别用 joycode 的模型跑需要工具的 agent 会话**,只适合纯对话。默认关闭。
flatten 模式会把 Chat Completions 消息压平成 `system + 单条 user prompt`(工具调用和工具结果会被丢弃),Responses 和 Anthropic Messages 不受影响。**开了 flatten 就别用 chat 模型跑需要工具的 agent 会话**,只适合纯对话。默认关闭。
## 已知限制
+231 -7
View File
@@ -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)
+239 -25
View File
@@ -4,15 +4,17 @@
* magpie / OpenCode provider.
*
* Protocol derived from the JoyCode IDE's bundled extension.js:
* POST https://api-ai.jd.com/api?appid=joycode_ide&functionId=chat_completions&t=<ms>&sign=<hmac>
* POST https://api-ai.jd.com/api?appid=joycode_ide&functionId=<protocol>_completions&t=<ms>&sign=<hmac>
* headers: ptKey (account ticket), loginType, optional tenant
* body: OpenAI chat completions JSON
* body: Chat Completions, Responses, or Anthropic Messages JSON
*
* magpie's gateway already converts any agent API into OpenAI chat
* completions format before calling our fetch. We sign each request, inject
* credential headers, and add authenticated account identity to the body.
* We inspect response prefixes for bare JSON gateway errors; valid SSE bytes
* are replayed unchanged, including tool-call deltas.
* The model catalogue's extJson.adapterType selects the model's SDK. We sign
* each request on the matching gateway, inject credential headers, and add
* authenticated account identity to the body. We inspect response prefixes
* for bare JSON gateway errors; valid SSE bytes are replayed unchanged,
* including tool-call deltas. JoyCode's Anthropic and Responses gateways add
* an extra SSE framing layer; we remove it incrementally so the official
* Anthropic and OpenAI SDKs receive standard events without extra buffering.
*
* Options (magpie plugin options joycode '{"…"}'):
* { "flatten": true } — flatten multi-turn messages into a single prompt
@@ -26,7 +28,16 @@ const PROVIDER = 'joycode'
const BASE = 'https://api-ai.jd.com'
const GATEWAY_PATH = '/api'
const APPID = 'joycode_ide'
const FUNCTION_ID = 'chat_completions'
const FUNCTION_IDS = {
chat: 'chat_completions',
responses: 'responses_completions',
anthropic: 'anthropic_completions',
}
const SDK = {
chat: '@ai-sdk/openai-compatible',
responses: '@ai-sdk/openai',
anthropic: '@ai-sdk/anthropic',
}
const LOGIN_TYPE = 'PIN_JD_CLOUD'
// HMAC signing key, extracted from the JoyCode IDE's bundled extension.js.
@@ -119,6 +130,47 @@ function buildGatewayHeaders(ptKey, tenant, loginType = LOGIN_TYPE) {
}
}
/** JoyCode's model catalogue names the wire protocol in extJson.adapterType. */
function adapterProtocol(model) {
let ext = model?.extJson
if (typeof ext === 'string') {
try { ext = JSON.parse(ext) } catch { ext = undefined }
}
const type = ext?.adapterType ?? model?.adapterType
if (typeof type !== 'string') return 'chat'
if (type === 'anthropic') return 'anthropic'
if (type === 'openai-response' || type === 'openai-responses' || type === 'responses') return 'responses'
return 'chat'
}
function requestPath(input) {
try {
return input instanceof Request ? new URL(input.url).pathname : new URL(String(input)).pathname
} catch {
return ''
}
}
function isCountTokensRequest(input) {
return /\/messages\/count_tokens\/?$/.test(requestPath(input))
}
/** The URL the host builds from a model's api.url says which request shape it sent. */
function requestProtocol(input, payload) {
const path = requestPath(input)
if (/\/responses\/?$/.test(path)) return 'responses'
if (/\/messages(?:\/count_tokens)?\/?$/.test(path)) return 'anthropic'
if (/\/chat\/completions\/?$/.test(path)) return 'chat'
if (Array.isArray(payload?.system)) return 'anthropic'
const tools = Array.isArray(payload?.tools) ? payload.tools : []
if (tools.some(tool => tool && typeof tool === 'object' && 'input_schema' in tool && !tool.function)) {
return 'anthropic'
}
if (payload?.input !== undefined && payload?.messages === undefined) return 'responses'
return 'chat'
}
/**
* OpenAI `messages` -> { prompt, system } — fallback for accounts/backends
* that reject multi-turn or tool-call payloads.
@@ -303,7 +355,123 @@ function chatError(status, code, message) {
})
}
async function normalizeChatResponse(response) {
function isSuccessfulJson(json, protocol) {
if (!json || typeof json !== 'object') return false
if (protocol === 'chat') return Boolean(json.choices)
if (protocol === 'anthropic') {
return Boolean(Array.isArray(json.content) || json.type === 'message' || json.stop_reason)
}
if (protocol === 'responses') {
return Boolean(json.object === 'response' || (json.id && Array.isArray(json.output)))
}
return false
}
/**
* JoyCode returns Anthropic events with one extra SSE framing layer:
*
* data: event: message_start
* data: data: {"type":"message_start",…}
*
* The official Anthropic SDK ignores `data:` events without an `event:` line,
* so passing those bytes through produces an empty stream. Rewrite only the
* two non-standard prefixes and coalesce their separating blank line into one
* standard SSE event, incrementally and without buffering the model output.
* Standard Anthropic SSE is left untouched. Buffering until a newline also
* handles either prefix being split across upstream chunks.
*/
function normalizeAnthropicSse(source) {
const decoder = new TextDecoder()
const encoder = new TextEncoder()
let pending = ''
let heldEvent
const processLine = (line, controller) => {
const ending = line.endsWith('\r\n') ? '\r\n' : line.endsWith('\n') ? '\n' : line.endsWith('\r') ? '\r' : ''
const body = ending ? line.slice(0, -ending.length) : line
if (!body) {
// JoyCode puts a blank line between `data: event` and `data: data`.
// Hold that separator back until both halves become one SSE event.
if (!heldEvent) controller.enqueue(encoder.encode(ending))
return
}
if (body.startsWith('data: event: ')) {
if (heldEvent) controller.enqueue(encoder.encode(heldEvent.text + heldEvent.ending))
heldEvent = { text: `event: ${body.slice('data: event: '.length)}`, ending }
return
}
if (body.startsWith('data: data: ')) {
if (heldEvent) {
controller.enqueue(encoder.encode(heldEvent.text + heldEvent.ending))
heldEvent = undefined
}
controller.enqueue(encoder.encode(`data: ${body.slice('data: data: '.length)}${ending}`))
return
}
if (heldEvent) {
controller.enqueue(encoder.encode(heldEvent.text + heldEvent.ending))
heldEvent = undefined
}
controller.enqueue(encoder.encode(line))
}
return source.pipeThrough(new TransformStream({
transform(chunk, controller) {
pending += decoder.decode(chunk, { stream: true })
let newline
while ((newline = pending.indexOf('\n')) !== -1) {
processLine(pending.slice(0, newline + 1), controller)
pending = pending.slice(newline + 1)
}
},
flush(controller) {
pending += decoder.decode()
if (pending) processLine(pending, controller)
if (heldEvent) controller.enqueue(encoder.encode(heldEvent.text + heldEvent.ending))
},
}))
}
/**
* JoyCode's Responses gateway wraps each SSE payload as `data: data: {…}`.
* Remove that extra layer without waiting for the response to finish.
* Standard Responses SSE, and every other line, is passed through unchanged.
*/
function normalizeResponsesSse(source) {
const decoder = new TextDecoder()
const encoder = new TextEncoder()
let pending = ''
const processLine = (line, controller) => {
const ending = line.endsWith('\r\n') ? '\r\n' : line.endsWith('\n') ? '\n' : line.endsWith('\r') ? '\r' : ''
const body = ending ? line.slice(0, -ending.length) : line
const normalized = body.startsWith('data: data: ')
? `data: ${body.slice('data: data: '.length)}${ending}`
: line
controller.enqueue(encoder.encode(normalized))
}
return source.pipeThrough(new TransformStream({
transform(chunk, controller) {
pending += decoder.decode(chunk, { stream: true })
let newline
while ((newline = pending.indexOf('\n')) !== -1) {
processLine(pending.slice(0, newline + 1), controller)
pending = pending.slice(newline + 1)
}
},
flush(controller) {
pending += decoder.decode()
if (pending) processLine(pending, controller)
},
}))
}
async function normalizeResponse(response, protocol = 'chat') {
if (!response.ok) {
const headers = new Headers(response.headers)
headers.set('x-magpie-sign-in', response.status === 401 ? 'expired' : 'kept')
@@ -345,14 +513,14 @@ async function normalizeChatResponse(response) {
const message = json.error?.message ?? json.message ?? json.msg
return chatError(status, code, typeof message === 'string' ? message.slice(0, 500) : 'JoyCode 请求被拒绝')
}
if (json?.choices) return Response.json(json)
if (isSuccessfulJson(json, protocol)) return Response.json(json)
return chatError(502, 'invalid_response', 'JoyCode 未返回有效的对话响应')
}
// Replay the inspected bytes and then stream normally, preserving tool deltas.
const headers = new Headers(response.headers)
headers.delete('content-length')
headers.delete('content-encoding')
return new Response(new ReadableStream({
const stream = new ReadableStream({
async pull(controller) {
if (buffered.length) { controller.enqueue(buffered.shift()); return }
try {
@@ -362,7 +530,16 @@ async function normalizeChatResponse(response) {
} catch (error) { controller.error(error) }
},
cancel(reason) { return reader.cancel(reason) },
}), { status: response.status, headers })
})
const normalized = protocol === 'anthropic'
? normalizeAnthropicSse(stream)
: protocol === 'responses'
? normalizeResponsesSse(stream)
: stream
return new Response(normalized, {
status: response.status,
headers,
})
}
// ---------------------------------------------------------------- account data
@@ -463,13 +640,14 @@ async function accountModels(provider, { auth } = {}) {
const features = Array.isArray(model.features) ? model.features : []
const image = features.includes('vision')
const rate = multiplier(model.billingRate) ?? rates.get(id)
const protocol = adapterProtocol(model)
// Remove old rate fields so unavailable pricing never becomes fake free usage.
const { rate: oldRate, rateWas, free, ...rest } = base
models[id] = {
...rest,
id,
name: model.label || id,
api: { id, url: `${BASE}/v1`, npm: '@ai-sdk/openai-compatible' },
api: { id, url: `${BASE}/v1`, npm: SDK[protocol] },
limit: {
...base.limit,
context: Number.isFinite(model.maxTotalTokens) ? model.maxTotalTokens : base.limit?.context ?? 200000,
@@ -548,37 +726,65 @@ export const JoyCodeAuthPlugin = async (_input, options) => {
}
return {
// Placeholder only — our fetch rewrites the full URL each request,
// because the signature embeds a fresh timestamp.
baseURL: `${BASE}/v1`,
// Each model's api.url carries the base. The fetch below rewrites the
// full URL because the gateway signature embeds a fresh timestamp.
baseURL: '',
async fetch(input, init) {
// JoyCode has no token-count endpoint. Let magpie fall back to its
// local estimator instead of signing a paid generation request.
if (isCountTokensRequest(input)) {
return Response.json({
error: {
type: 'unsupported_endpoint',
message: 'JoyCode does not provide token counting',
},
}, { status: 404 })
}
async fetch(_input, init) {
// Preserve chat structure; the IDE also adds authenticated metadata.
const account = await identity()
const source = typeof init?.body === 'string' ? init.body : new TextDecoder().decode(init?.body)
const request = input instanceof Request ? input : undefined
let source = init?.body
if (source === undefined && request) source = await request.clone().text()
source = typeof source === 'string'
? source
: source == null
? '{}'
: new TextDecoder().decode(source)
const payload = JSON.parse(source)
const protocol = requestProtocol(request ?? input, payload)
const body = JSON.stringify({
...(flatten ? flattenBody(payload) : payload),
...(flatten && protocol === 'chat' ? flattenBody(payload) : payload),
...account,
language: 'UNKNOWN',
})
// 2) URL: fresh signature per request.
const url = buildGatewayUrl(FUNCTION_ID)
// 2) URL: fresh signature per request, on the model's wire protocol.
const url = buildGatewayUrl(FUNCTION_IDS[protocol])
// 3) Headers: keep what magpie synthesized (content-type, …),
// add the gateway credentials, drop the OpenAI-style bearer
// JoyCode does not understand.
const headers = new Headers(init?.headers)
const headers = new Headers(init?.headers ?? request?.headers)
for (const [k, v] of Object.entries(buildGatewayHeaders(ptKey, account.tenant, loginType))) {
headers.set(k, v)
}
headers.delete('authorization')
headers.delete('x-api-key')
headers.delete('content-length')
headers.delete('host')
// 4) Forward (...init carries the abort signal).
const resp = await fetch(url, { ...init, headers, body })
const resp = await fetch(url, {
...init,
method: init?.method ?? request?.method,
headers,
body,
signal: init?.signal ?? request?.signal,
})
return normalizeChatResponse(resp)
return normalizeResponse(resp, protocol)
},
}
},
@@ -603,7 +809,15 @@ export const JoyCodeAuthPlugin = async (_input, options) => {
// Test surface (bun test). Everything testable lives on this object so the
// entry module exports no bare functions besides the plugin — see the note
// on the helpers above.
export const _internal = { signQuery, buildGatewayUrl, buildGatewayHeaders, flattenMessages, MODELS }
export const _internal = {
signQuery,
buildGatewayUrl,
buildGatewayHeaders,
flattenMessages,
adapterProtocol,
requestProtocol,
MODELS,
}
// OpenCode v1 form: with default { id, server } the host takes only
// `server` as the plugin and never iterates the module's other exports.
+11 -2
View File
@@ -5,6 +5,8 @@ import plugin from './index.mjs'
const catalogue = [
{ chatApiModel: 'JoyAI-Code-1.6', label: 'JoyAI-Code-1.6', maxTotalTokens: 200000, respMaxTokens: 64000, features: ['function_call'] },
{ chatApiModel: 'GLM-5.3-agent', label: 'GLM-5.3', maxTotalTokens: 200000, respMaxTokens: 64000, features: ['function_call'] },
{ chatApiModel: 'GPT-5.6 Sol', label: 'GPT-5.6 Sol', extJson: { adapterType: 'openai-response' } },
{ chatApiModel: 'Claude-Opus-5-hq', label: 'Claude-Opus-5', extJson: { adapterType: 'anthropic' } },
]
const billingRate = { excludeTenants: ['JD'], billingRates: [
{ chatApiModel: 'JoyAI-Code-1.6', billingRate: '0x' },
@@ -35,12 +37,19 @@ async function load(t, { tenant = 'personal', failRates = false, failList = fals
test('sync current model multipliers including zero without adding pricing-only models', async t => {
const { models } = await load(t)
assert.deepEqual(Object.keys(models), ['JoyAI-Code-1.6', 'GLM-5.3-agent'])
assert.deepEqual(Object.keys(models), ['JoyAI-Code-1.6', 'GLM-5.3-agent', 'GPT-5.6 Sol', 'Claude-Opus-5-hq'])
assert.equal(models['JoyAI-Code-1.6'].rate, 0)
assert.equal(models['JoyAI-Code-1.6'].free, true)
assert.equal(models['GLM-5.3-agent'].rate, 0.6)
assert.equal(models['GLM-5.3-agent'].capabilities.input.image, false)
})
test('model adapter chooses the SDK that speaks its upstream protocol', async t => {
const { models } = await load(t)
assert.equal(models['JoyAI-Code-1.6'].api.npm, '@ai-sdk/openai-compatible')
assert.equal(models['GPT-5.6 Sol'].api.npm, '@ai-sdk/openai')
assert.equal(models['Claude-Opus-5-hq'].api.npm, '@ai-sdk/anthropic')
for (const model of Object.values(models)) assert.equal(model.api.url, 'https://api-ai.jd.com/v1')
})
test('excluded tenants do not inherit public pricing', async t => {
const { models } = await load(t, { tenant: 'JD' })
assert.equal(models['GLM-5.3-agent'].rate, undefined)
@@ -52,7 +61,7 @@ test('model-specific billing rate takes priority', async t => {
})
test('pricing fetch failure retains models without invented rates', async t => {
const { models } = await load(t, { failRates: true })
assert.equal(Object.keys(models).length, 2)
assert.equal(Object.keys(models).length, 4)
assert.equal(models['GLM-5.3-agent'].rate, undefined)
})
test('catalogue fetch failure returns original fallback model list', async t => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-joycode-auth",
"version": "0.1.1",
"version": "0.2.0",
"description": "OpenCode provider plugin: JoyCode (JD Cloud JoyCoder IDE credits)",
"type": "module",
"main": "./index.mjs",