joycode 0.2.7: an empty or unterminated Responses stream is an error, not a silent success (liangmouse, #720)

JoyCode's Responses SSE is checked one event at a time, never buffered whole:

- a JoyCode FAILED_RESPONSE envelope (code non-zero) becomes a Responses
  "error" event that keeps its code, message and cause; anything after it
  is dropped;
- a response.completed with no output seen and none in its output list
  becomes error empty_response (an unreadable completed frame too);
- EOF with no completed, incomplete, failed or error event becomes error
  incomplete_response;
- text, refusals, tool and *_call items, reasoning with a summary or
  encrypted content, and explicit incomplete/failed pass byte for byte,
  CRLF included. A completed with no [DONE] after it passes as it came.

magpie's gateway reads a Responses "error" event as a failed turn and owns
the retries; the plugin sends no request of its own. Tests that called
t.mock.method(fetch) several times in one test leaked the mock under Bun
(copilot's tests got "Body already used"); each fixture is its own test now.

Run at the reviewed head 7b74d0c (main d9a6c45 plus this PR, Bun 1.4.4
38afee6c8, CI's version):
- Linux (WSL magpie-desktop), fresh HOME: bun test 5501 pass, 18 skip,
  0 fail; bun scripts/check.mjs ok.
- macOS (mote): bun test packages/joycode 94/94; node --test
  packages/joycode/*.test.mjs 100/100; joycode chat + copilot in one Bun
  process 104 pass, 0 fail (53bf359 alone: 4 fails, "Body already used").
- Broken by hand: index.mjs back to 0.2.6 with the new tests, the 4
  behaviour tests go red; payload.response without ?. , the malformed
  completed test goes red (Bun and Node).
- Probes through loader.fetch: completed without [DONE] or a trailing
  blank line, completed then [DONE], and a double-wrapped full stream pass
  untouched; [DONE] alone, a comment alone, created + [DONE] and a delta
  cut mid-line each end in one incomplete_response.

Not tried: a real JoyCode account (the author ran GPT-6 Astra through
magpie 0.1.2392).
This commit is contained in:
liangmouse
2026-11-04 19:18:48 +08:00
committed by GitHub
parent d677c436d3
commit 16769b21dc
5 changed files with 314 additions and 7 deletions
+5
View File
@@ -1,5 +1,10 @@
# 更新记录
## 0.2.7
- Responses SSE 不再把空完成当成功:空 `response.completed` 转成 `empty_response`,缺少终止事件的 EOF 转成 `incomplete_response`,流内 JoyCode `FAILED_RESPONSE` 错误保留原始字段并转成标准错误事件。按事件增量处理,不缓存整段回复。
- 实际 magpie 0.1.2392 隔离验证:原版原协议透传接受空完成;修复后明确失败,随后上游恢复时可重试成功。真实短工具结果续答在本机 magpie 通道 2.96 秒返回 `OK`。历史静默结束没有保留原始 SSE,不能证明全部历史触发原因。
## 0.2.6
- 将真实验证通过的 GPT-6.1 Sol 和 GLM-5.3 加入长上下文白名单,最高采用 900k;仍要求账号目录声明更大的 Desktop 窗口,输出上限不变。
+6
View File
@@ -96,3 +96,9 @@ bun test # 浏览器登录、额度映射、模型倍率回归测
这是非官方适配插件,与京东或 magpie 官方无隶属关系。JoyCode 图标及商标归其权利人所有;代码的 MIT 许可不授予这些品牌资产的权利。
2026-11-04 补测:`GPT-6.1 Sol` 和 `GLM-5.3` 的 900k 档均找回全部标记,分别耗时 15.95 秒和 98.31 秒;两者的 1,000k 档均被上游拒绝,因此取已验证的 900k 档,不声称精确边界。`GLM-5.3-jcloud`、`GLM-5.3-agent` 未测试,不继承 `GLM-5.3` 的窗口。
## Responses 流完整性
插件逐事件检查 Responses SSE:空完成返回 `empty_response`,未收到终止事件即 EOF 返回 `incomplete_response`,JoyCode 流内业务错误转为标准错误事件。正常文本、拒绝、工具输出以及明确的 incomplete/failed 状态保留;不等待完整回复才透传。是否重试及重试次数由 magpie 决定,插件不额外重发请求。
2026-11-04 使用 magpie 0.1.2392 隔离验证了空完成从静默成功变为明确错误,以及上游恢复后的重试成功。真实短工具结果续答在本机通道 2.96 秒返回 `OK`。这是已复现路径的修复;历史异常未保存原始 SSE,尚不能据此认定全部历史根因。
+172 -2
View File
@@ -27,6 +27,15 @@ async function request(t, response, {
function chunks(parts) {
return new ReadableStream({ start(c) { for (const p of parts) c.enqueue(new TextEncoder().encode(p)); c.close() } })
}
function responseEvents(text) {
return text.split(/\r?\n\r?\n/).flatMap(frame => {
const data = frame.split(/\r?\n/)
.filter(line => line.startsWith('data:'))
.map(line => line.slice(5).replace(/^ /, ''))
if (!data.length) return []
try { return [JSON.parse(data.join('\n'))] } catch { return [] }
})
}
test('HTTP 200 raw gateway denial becomes actionable error, not empty SSE', async t => {
const denial = () => new Response(chunks([' {"error":', '{"code":"AI_GRAY_ACCESS_DENIED","message":"访问受限,请联系管理员开通"}}']), { headers: { 'content-type': 'text/event-stream' } })
const r = await request(t, denial)
@@ -122,7 +131,10 @@ for (const [name, input, payload, functionId, npmShape] of [
]) {
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', {
const stream = name === 'Responses'
? 'data: {"type":"response.incomplete","response":{"status":"incomplete","output":[{"type":"reasoning","summary":[]}]}}\n\n'
: 'data: [DONE]\n\n'
const r = await request(t, new Response(stream, {
headers: { 'content-type': 'text/event-stream' },
}), {
input,
@@ -141,7 +153,7 @@ for (const [name, input, payload, functionId, npmShape] of [
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')
assert.equal(await r.text(), stream)
})
}
@@ -392,6 +404,164 @@ test('Responses double-wrapped SSE is normalized across chunk boundaries', async
].join(''))
})
test('Responses malformed completed payload emits one empty_response without throwing', async t => {
const r = await request(t, new Response('event: response.completed\ndata: oops\n\n', {
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)
let body
await assert.doesNotReject(async () => { body = await r.text() })
const events = responseEvents(body)
assert.equal(events.length, 1)
assert.equal(events[0].type, 'error')
assert.equal(events[0].code, 'empty_response')
})
test('Responses converts a double-wrapped JoyCode failure and suppresses later success', async t => {
const failure = {
code: 'QUOTA_EXHAUSTED',
message: 'credits exhausted',
cause: { detail: 'billing limit' },
status: 'FAILED_RESPONSE',
}
const upstreamText = [
`data: data: ${JSON.stringify(failure)}\n\n`,
`data: data: ${JSON.stringify({ type: 'response.completed', response: { output: [{ type: 'message', content: [{ type: 'output_text', text: 'unexpected' }] }] } })}\n\n`,
].join('')
const split = upstreamText.indexOf('credits') + 3
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 },
})
const body = await r.text()
const events = responseEvents(body)
assert.equal(r.status, 200)
assert.equal(events.length, 1)
assert.equal(events[0].type, 'error')
assert.equal(events[0].code, failure.code)
assert.equal(events[0].cause.detail, failure.cause.detail)
assert.equal(events.some(event => event.type === 'response.completed'), false)
})
// Separate contexts avoid stacked fetch mocks leaking under Bun's node:test adapter.
for (const [label, output] of [['no output', []], ['empty reasoning', [{ type: 'reasoning', summary: [] }]]]) {
test(`Responses converts an empty completion into empty_response: ${label}`, async t => {
const completed = { type: 'response.completed', response: { status: 'completed', output } }
const r = await request(t, new Response(`data: ${JSON.stringify(completed)}\n\n`, {
headers: { 'content-type': 'text/event-stream' },
}), {
input: 'https://api-ai.jd.com/v1/responses',
payload: { model: 'GPT-6 Astra', input: 'OK', stream: true },
})
const body = await r.text()
const events = responseEvents(body)
assert.equal(events.length, 1)
assert.equal(events[0].type, 'error')
assert.equal(events[0].code, 'empty_response')
assert.equal(body.includes('response.completed'), false)
})
}
test('Responses reports incomplete_response when EOF has no terminal event', async t => {
const delta = { type: 'response.output_text.delta', delta: 'partial' }
const upstreamText = `data: ${JSON.stringify(delta)}\n\n`
const r = await request(t, new Response(upstreamText, {
headers: { 'content-type': 'text/event-stream' },
}), {
input: 'https://api-ai.jd.com/v1/responses',
payload: { model: 'GPT-6 Astra', input: 'OK', stream: true },
})
const body = await r.text()
const events = responseEvents(body)
assert.equal(body.startsWith(upstreamText), true)
assert.equal(events.at(-1).type, 'error')
assert.equal(events.at(-1).code, 'incomplete_response')
})
test('Responses preserves standard CRLF events byte for byte', async t => {
const upstreamText = 'event: response.incomplete\r\ndata: {"type":"response.incomplete","response":{"status":"incomplete","output":[]}}\r\n\r\n'
const r = await request(t, new Response(chunks([upstreamText.slice(0, 19), upstreamText.slice(19)]), {
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(await r.text(), upstreamText)
})
{
const cases = [
['text delta', [
{ type: 'response.output_text.delta', delta: 'hello' },
{ type: 'response.completed', response: { output: [] } },
]],
['text and tool deltas', [
{ type: 'response.output_text.delta', delta: 'hello' },
{ type: 'response.function_call_arguments.delta', item_id: 'fc_1', delta: '{}' },
{ type: 'response.completed', response: { output: [] } },
]],
['function call', [
{ type: 'response.completed', response: { output: [{ type: 'function_call', call_id: 'call_1', name: 'lookup', arguments: '{}' }] } },
]],
['completed output text', [
{ type: 'response.completed', response: { output: [{ type: 'message', content: [{ type: 'output_text', text: 'from output' }] }] } },
]],
['refusal', [
{ type: 'response.completed', response: { output: [{ type: 'message', content: [{ type: 'refusal', refusal: 'cannot help' }] }] } },
]],
['search call', [
{ type: 'response.completed', response: { output: [{ type: 'web_search_call', id: 'search_1', status: 'completed', action: { query: 'weather' } }] } },
]],
['image call', [
{ type: 'response.completed', response: { output: [{ type: 'image_generation_call', id: 'image_1', status: 'completed', result: 'encoded-image' }] } },
]],
['reasoning incomplete', [
{ type: 'response.incomplete', response: { status: 'incomplete', output: [{ type: 'reasoning', summary: [] }] } },
]],
['failed terminal', [
{ type: 'response.failed', response: { status: 'failed', output: [] } },
]],
['reasoning completed item', [
{ type: 'response.completed', response: { output: [{ type: 'reasoning', summary: [{ type: 'summary_text', text: 'internal' }] }] } },
]],
['encrypted reasoning', [
{ type: 'response.completed', response: { output: [{ type: 'reasoning', encrypted_content: 'encrypted-reasoning' }] } },
]],
]
for (const [label, events] of cases) {
test(`Responses preserves output bytes: ${label}`, async t => {
const upstreamText = events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('')
const r = await request(t, new Response(upstreamText, {
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(await r.text(), upstreamText, label)
})
}
}
test('Responses does not append another error after an upstream error event', async t => {
const upstreamText = 'data: {"type":"error","code":"upstream_failure","message":"failed"}\n\n'
const r = await request(t, new Response(upstreamText, {
headers: { 'content-type': 'text/event-stream' },
}), {
input: 'https://api-ai.jd.com/v1/responses',
payload: { model: 'GPT-6 Astra', input: 'OK', stream: true },
})
const body = await r.text()
const errors = responseEvents(body).filter(event => event.type === 'error')
assert.equal(errors.length, 1)
assert.equal(body, upstreamText)
})
test('Responses drops unstored reasoning ids but keeps inline reasoning and other ids', async t => {
let sent
const payload = {
+130 -4
View File
@@ -534,14 +534,132 @@ function normalizeResponsesSse(source) {
const decoder = new TextDecoder()
const encoder = new TextEncoder()
let pending = ''
let frameLines = []
let sawOutput = false
let terminalSeen = false
let stopAfterError = false
let atEventBoundary = true
let lineEnding = '\n'
let lastLineEnding = '\n'
const nonEmpty = value => typeof value === 'string' && value.length > 0
const nonZeroCode = code => {
if (typeof code === 'number') return code !== 0
if (typeof code === 'string') {
if (!code.trim()) return false
const numeric = Number(code)
return !Number.isFinite(numeric) || numeric !== 0
}
return code !== undefined && code !== null && code !== false
}
const hasVisibleContent = content => Array.isArray(content) && content.some(part =>
part?.type === 'output_text' ? nonEmpty(part.text)
: part?.type === 'refusal' && nonEmpty(part.refusal))
const hasValidOutputItem = item => {
if (!item || typeof item !== 'object' || typeof item.type !== 'string') return false
if (item.type === 'reasoning') {
return (Array.isArray(item.summary) && item.summary.some(part =>
part?.type === 'summary_text' && nonEmpty(part.text))) || nonEmpty(item.encrypted_content)
}
if (item.type === 'message') {
return nonEmpty(item.content) || hasVisibleContent(item.content)
}
if (item.type.endsWith('_call')) {
return Object.entries(item).some(([key, value]) => key !== 'type' && value !== undefined && value !== null)
}
return false
}
const hasValidOutput = output => Array.isArray(output) && output.some(hasValidOutputItem)
const observeOutput = event => {
if (!event || typeof event !== 'object') return
const type = event.type
if (type === 'response.output_text.delta' || type === 'response.output_text.done') {
if (nonEmpty(event.delta) || nonEmpty(event.text)) sawOutput = true
} else if (type === 'response.refusal.delta' || type === 'response.refusal.done') {
if (nonEmpty(event.delta) || nonEmpty(event.refusal)) sawOutput = true
} else if (type === 'response.function_call_arguments.delta' || type === 'response.function_call_arguments.done') {
sawOutput = true
} else if (type === 'response.reasoning_summary_text.delta' && nonEmpty(event.delta)) {
sawOutput = true
} else if (type === 'response.output_item.added' || type === 'response.output_item.done') {
if (hasValidOutputItem(event.item)) sawOutput = true
} else if (type === 'response.content_part.added' || type === 'response.content_part.done') {
if (hasVisibleContent([event.part])) sawOutput = true
} else if (typeof type === 'string' && /^response\.[a-z_]+_call\./.test(type)) {
sawOutput = true
}
}
const emitError = (controller, event, ending = '\n', needsSeparator = false, previousEnding = ending) => {
const prefix = needsSeparator ? (previousEnding ? previousEnding : `${ending}${ending}`) : ''
controller.enqueue(encoder.encode(`${prefix}data: ${JSON.stringify(event)}${ending}${ending}`))
}
const processFrame = (controller, delimited = true) => {
if (!frameLines.length) return
const lines = frameLines
frameLines = []
atEventBoundary = delimited
if (stopAfterError) return
let eventName = ''
const data = []
for (const entry of lines) {
if (entry.body.startsWith('event:')) eventName = entry.body.slice(6).trim()
if (entry.body.startsWith('data:')) data.push(entry.body.slice(5).replace(/^ /, ''))
}
let payload
if (data.length) {
try { payload = JSON.parse(data.join('\n')) } catch {}
}
if (payload && typeof payload === 'object' && payload.status === 'FAILED_RESPONSE' && nonZeroCode(payload.code)) {
emitError(controller, { ...payload, type: 'error' }, lines.find(entry => entry.ending)?.ending || '\n')
terminalSeen = true
stopAfterError = true
return
}
const type = payload?.type || eventName
if (type === 'response.completed') {
const output = payload?.response?.output ?? payload?.output
if (!sawOutput && !hasValidOutput(output)) {
emitError(controller, {
type: 'error',
code: 'empty_response',
message: 'JoyCode 返回空响应',
...(payload?.sequence_number === undefined ? {} : { sequence_number: payload.sequence_number }),
}, lines.find(entry => entry.ending)?.ending || '\n')
terminalSeen = true
stopAfterError = true
return
}
}
observeOutput(payload)
if (type === 'response.completed' || type === 'response.incomplete' || type === 'response.failed' || type === 'error') {
terminalSeen = true
}
controller.enqueue(encoder.encode(lines.map(entry => entry.text).join('')))
}
const processLine = (line, controller) => {
if (stopAfterError) return
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))
const normalizedBody = body.startsWith('data: data: ')
? `data: ${body.slice('data: data: '.length)}`
: body
frameLines.push({ text: `${normalizedBody}${ending}`, body: normalizedBody, ending })
if (ending) lineEnding = ending
lastLineEnding = ending
if (!body) processFrame(controller)
else atEventBoundary = false
}
return source.pipeThrough(new TransformStream({
@@ -556,6 +674,14 @@ function normalizeResponsesSse(source) {
flush(controller) {
pending += decoder.decode()
if (pending) processLine(pending, controller)
if (frameLines.length) processFrame(controller, false)
if (!terminalSeen) {
emitError(controller, {
type: 'error',
code: 'incomplete_response',
message: 'JoyCode 响应流未正常终止',
}, lineEnding, !atEventBoundary, lastLineEnding || `${lineEnding}${lineEnding}`)
}
},
}))
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-joycode-auth",
"version": "0.2.6",
"version": "0.2.7",
"description": "OpenCode provider plugin: JoyCode (JD Cloud JoyCoder IDE credits)",
"type": "module",
"main": "./opencode.mjs",