magpie-junie-auth 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/lib/direct.mjs +167 -30
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -39,7 +39,14 @@ magpie accounts switch junie <email> # 切换默认
|
|
|
39
39
|
| 直连 | `POST /v1/responses` | `gpt-6-luna` | 否 |
|
|
40
40
|
| 桥接 | 本地 `POST /v1/chat/completions` → CLI headless | `junie-lite` | 是 |
|
|
41
41
|
|
|
42
|
-
对客户端统一暴露 OpenAI Chat Completions(流式 SSE 与非流式均支持)。插件内部把 chat completions 转成 Responses API
|
|
42
|
+
对客户端统一暴露 OpenAI Chat Completions(流式 SSE 与非流式均支持)。插件内部把 chat completions 转成 Responses API,再把响应转回,完整支持 agent 所需能力:
|
|
43
|
+
|
|
44
|
+
- **工具调用双向**:`tools`/`tool_choice` 转发;assistant `tool_calls` ↔ Responses `function_call`,`role:"tool"` ↔ `function_call_output`;多工具并行、`finish_reason:"tool_calls"`。
|
|
45
|
+
- **真流式**:边读边转,不缓冲整段;流末尾带 usage。
|
|
46
|
+
- **多模态输入**:图片等 content parts 保留为 `input_image`。
|
|
47
|
+
- 兼容 SSE 的 LF/CRLF 混用、缺失事件(delta 丢失时用 done 补齐)、上游错误/拒绝与 `finish_reason:"length"`(`max_output_tokens` 截断)。
|
|
48
|
+
|
|
49
|
+
`temperature`/`top_p`/`stop_sequences` 会被该免费模型拒绝,故主动丢弃;`parallel_tool_calls` 与 `response_format` 会转发。`n>1` 降级为单候选(Responses 无多候选概念)。
|
|
43
50
|
|
|
44
51
|
额度显示走 `GET /auth/test`:`plan` = licenseType、`balance` = balanceLeft + unit。上游不提供窗口百分比,`windows` 留空(不编造 `used: 0`)。
|
|
45
52
|
|
package/lib/direct.mjs
CHANGED
|
@@ -100,8 +100,16 @@ export function toResponsesInput(messages = []) {
|
|
|
100
100
|
if (!m || typeof m !== "object") continue
|
|
101
101
|
const role = m.role ?? "user"
|
|
102
102
|
if (role === "system") {
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
// 纯文本 system → instructions;含图片等非文本 part 时 instructions 放不下,
|
|
104
|
+
// 保留为 input 里的 system message,避免静默丢内容。
|
|
105
|
+
const hasNonText = Array.isArray(m.content) && m.content.some((p) =>
|
|
106
|
+
p && typeof p === "object" && (p.type === "image_url" || p.type === "input_image" || p.type === "file" || p.type === "input_file"))
|
|
107
|
+
if (!hasNonText) {
|
|
108
|
+
const text = contentToText(m.content)
|
|
109
|
+
instructions = instructions ? instructions + "\n" + text : text
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
input.push({ role: "system", content: contentToParts(m.content) })
|
|
105
113
|
continue
|
|
106
114
|
}
|
|
107
115
|
if (role === "tool") {
|
|
@@ -118,11 +126,16 @@ export function toResponsesInput(messages = []) {
|
|
|
118
126
|
const text = contentToText(m.content)
|
|
119
127
|
if (text) input.push({ role: "assistant", content: text })
|
|
120
128
|
for (const tc of m.tool_calls) {
|
|
129
|
+
// Responses 规范:arguments 必须是 JSON 字符串;AI SDK 有时给对象。
|
|
130
|
+
let args = tc.function?.arguments ?? tc.arguments ?? "{}"
|
|
131
|
+
if (args != null && typeof args !== "string") {
|
|
132
|
+
try { args = JSON.stringify(args) } catch { args = String(args) }
|
|
133
|
+
}
|
|
121
134
|
input.push({
|
|
122
135
|
type: "function_call",
|
|
123
136
|
call_id: tc.id ?? tc.call_id ?? "",
|
|
124
137
|
name: tc.function?.name ?? tc.name ?? "",
|
|
125
|
-
arguments:
|
|
138
|
+
arguments: args || "{}",
|
|
126
139
|
})
|
|
127
140
|
}
|
|
128
141
|
continue
|
|
@@ -174,17 +187,32 @@ export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
|
|
|
174
187
|
if (instructions) body.instructions = instructions
|
|
175
188
|
if (eff && eff !== "none") body.reasoning = { effort: eff }
|
|
176
189
|
if (chat?.max_tokens || chat?.max_completion_tokens) body.max_output_tokens = chat.max_tokens ?? chat.max_completion_tokens
|
|
190
|
+
// 生成控制字段:真机验证 gpt-6-luna 只接受 parallel_tool_calls;
|
|
191
|
+
// temperature / top_p / stop_sequences 会被上游 400(unsupported/unknown parameter),
|
|
192
|
+
// 所以这里主动丢弃,避免 agent 传它们时整请求失败。
|
|
193
|
+
if (chat?.parallel_tool_calls != null) body.parallel_tool_calls = Boolean(chat.parallel_tool_calls)
|
|
194
|
+
// n>1:Responses 无多候选概念,降级为单候选(返回 1 个 choice),不转发 n。
|
|
195
|
+
// response_format: chat 的 json_object / json_schema → Responses 的 text.format
|
|
196
|
+
const rf = chat?.response_format
|
|
197
|
+
if (rf && typeof rf === "object") {
|
|
198
|
+
if (rf.type === "json_object") body.text = { format: { type: "json_object" } }
|
|
199
|
+
else if (rf.type === "json_schema" && rf.json_schema) {
|
|
200
|
+
body.text = { format: { type: "json_schema", name: rf.json_schema.name ?? "schema", schema: rf.json_schema.schema ?? rf.json_schema } }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
177
203
|
return body
|
|
178
204
|
}
|
|
179
205
|
|
|
180
206
|
/** Responses output items → chat message(text + tool_calls)+ finish_reason。 */
|
|
181
207
|
function responseItemsToMessage(items = []) {
|
|
182
208
|
let text = ""
|
|
209
|
+
let reasoningText = ""
|
|
183
210
|
const toolCalls = []
|
|
184
211
|
for (const item of items) {
|
|
185
212
|
if (item?.type === "message") {
|
|
186
213
|
for (const c of item?.content ?? []) {
|
|
187
214
|
if ((c?.type === "output_text" || c?.type === "input_text") && typeof c.text === "string") text += c.text
|
|
215
|
+
else if (c?.type === "refusal" && typeof c.refusal === "string") text += `[refusal: ${c.refusal}]`
|
|
188
216
|
else if (c?.type === "output_image" && c.image_url) text += `[image: ${c.image_url}]`
|
|
189
217
|
else if (c?.text) text += String(c.text)
|
|
190
218
|
}
|
|
@@ -194,16 +222,38 @@ function responseItemsToMessage(items = []) {
|
|
|
194
222
|
type: "function",
|
|
195
223
|
function: { name: item.name ?? "", arguments: item.arguments ?? "{}" },
|
|
196
224
|
})
|
|
225
|
+
} else if (item?.type === "reasoning") {
|
|
226
|
+
// reasoning 不进 content,但兼容客户端通过 reasoning_content 读摘要。
|
|
227
|
+
const summary = (item.summary ?? []).map((s) => s?.text ?? "").filter(Boolean).join("\n")
|
|
228
|
+
if (summary) reasoningText += summary
|
|
197
229
|
}
|
|
198
230
|
}
|
|
199
231
|
const message = { role: "assistant", content: text }
|
|
232
|
+
if (reasoningText) message.reasoning_content = reasoningText
|
|
200
233
|
if (toolCalls.length) message.tool_calls = toolCalls
|
|
201
234
|
return { message, finish_reason: toolCalls.length ? "tool_calls" : "stop" }
|
|
202
235
|
}
|
|
203
236
|
|
|
204
237
|
/** Responses JSON → Chat Completions JSON。 */
|
|
238
|
+
/** Responses status/status_details → Chat finish_reason。 */
|
|
239
|
+
export function finishReasonOf(resp, defaultReason = "stop") {
|
|
240
|
+
if (resp?.status === "incomplete") {
|
|
241
|
+
const reason = resp?.status_details?.reason ?? resp?.status_details?.type
|
|
242
|
+
return reason === "max_output_tokens" || reason === "length" ? "length" : "content_filter"
|
|
243
|
+
}
|
|
244
|
+
if (resp?.status === "failed" || resp?.status === "cancelled") return "stop"
|
|
245
|
+
return defaultReason
|
|
246
|
+
}
|
|
247
|
+
|
|
205
248
|
export function fromResponsesJSON(resp, model = "junie-lite") {
|
|
206
|
-
const { message, finish_reason } = responseItemsToMessage(resp?.output)
|
|
249
|
+
const { message, finish_reason: itemReason } = responseItemsToMessage(resp?.output)
|
|
250
|
+
const finish_reason = finishReasonOf(resp, itemReason)
|
|
251
|
+
// HTTP 200 但 upstream 报错/失败时,把原因作为内容返回,别让 agent 当成空成功。
|
|
252
|
+
const failure = resp?.error ?? (resp?.status === "failed" ? (resp?.status_details ?? "upstream failed") : null)
|
|
253
|
+
if (failure) {
|
|
254
|
+
const msg = typeof failure === "string" ? failure : (failure?.message ?? failure?.type ?? "upstream error")
|
|
255
|
+
message.content = message.content || `[Junie upstream error: ${String(msg).slice(0, 500)}]`
|
|
256
|
+
}
|
|
207
257
|
const u = resp?.usage ?? {}
|
|
208
258
|
return {
|
|
209
259
|
id: resp?.id ?? `chatcmpl-${Date.now()}`,
|
|
@@ -236,7 +286,18 @@ export function responseEventToChatChunks(d, model, id, state) {
|
|
|
236
286
|
const out = []
|
|
237
287
|
const t = d?.type
|
|
238
288
|
if (t === "response.output_text.delta") {
|
|
239
|
-
if (d.delta)
|
|
289
|
+
if (d.delta) {
|
|
290
|
+
state.textDelta = (state.textDelta ?? "") + d.delta
|
|
291
|
+
out.push(chunk({ content: d.delta }))
|
|
292
|
+
}
|
|
293
|
+
} else if (t === "response.output_text.done") {
|
|
294
|
+
// 兜底:delta 缺失/截断时用完整 text 补齐差额(与 function_call_arguments.done 对称)。
|
|
295
|
+
const full = d.text ?? ""
|
|
296
|
+
const got = state.textDelta ?? ""
|
|
297
|
+
if (full && full !== got) {
|
|
298
|
+
out.push(chunk({ content: full.slice(got.length) }))
|
|
299
|
+
state.textDelta = full
|
|
300
|
+
}
|
|
240
301
|
} else if (t === "response.output_item.added" && d.item?.type === "function_call") {
|
|
241
302
|
const idx = state.toolIndex++
|
|
242
303
|
state.toolById.set(d.item.id ?? d.item.call_id, idx)
|
|
@@ -249,14 +310,45 @@ export function responseEventToChatChunks(d, model, id, state) {
|
|
|
249
310
|
}],
|
|
250
311
|
}))
|
|
251
312
|
} else if (t === "response.function_call_arguments.delta") {
|
|
313
|
+
// 有些上游不发 output_item.added;delta 本身也说明有工具调用,
|
|
314
|
+
// 补一个占位首帧让客户端拿到 index(name/id 未知时留空)。
|
|
315
|
+
if (!state.toolById.has(d.item_id)) {
|
|
316
|
+
const idx = state.toolIndex++
|
|
317
|
+
state.toolById.set(d.item_id, idx)
|
|
318
|
+
out.push(chunk({ tool_calls: [{ index: idx, type: "function", function: { name: "", arguments: "" } }] }))
|
|
319
|
+
}
|
|
320
|
+
const idx = state.toolById.get(d.item_id)
|
|
321
|
+
if (d.delta) {
|
|
322
|
+
state.argByTool ??= new Map()
|
|
323
|
+
state.argByTool.set(idx, (state.argByTool.get(idx) ?? "") + d.delta)
|
|
324
|
+
out.push(chunk({ tool_calls: [{ index: idx, function: { arguments: d.delta } }] }))
|
|
325
|
+
}
|
|
326
|
+
} else if (t === "response.function_call_arguments.done") {
|
|
327
|
+
// 兜底:若 delta 缺失/被截断,用 done 的完整 arguments 补齐。
|
|
252
328
|
const idx = state.toolById.get(d.item_id) ?? 0
|
|
253
|
-
|
|
329
|
+
const full = d.arguments ?? ""
|
|
330
|
+
const got = state.argByTool?.get(idx) ?? ""
|
|
331
|
+
if (full && full !== got) {
|
|
332
|
+
out.push(chunk({ tool_calls: [{ index: idx, function: { arguments: full.slice(got.length) } }] }))
|
|
333
|
+
if (state.argByTool) state.argByTool.set(idx, full)
|
|
334
|
+
}
|
|
335
|
+
} else if (t === "response.failed" || t === "response.error") {
|
|
336
|
+
// 上游失败/拒绝:把原因作为文本吐出,别让 agent 收到空 successful 回复。
|
|
337
|
+
const err = d.response?.error ?? d.error ?? d
|
|
338
|
+
const msg = typeof err === "string" ? err : (err?.message ?? err?.type ?? "upstream error")
|
|
339
|
+
out.push(chunk({ content: `[Junie upstream ${t}: ${String(msg).slice(0, 500)}]` }))
|
|
340
|
+
out.push(chunk({}, "stop"))
|
|
341
|
+
out.push("data: [DONE]\n\n")
|
|
342
|
+
state.done = true
|
|
254
343
|
} else if (t === "response.completed" || t === "response.incomplete") {
|
|
255
344
|
const u = d.response?.usage ?? {}
|
|
256
345
|
const usage = u.input_tokens != null || u.output_tokens != null
|
|
257
346
|
? { prompt_tokens: u.input_tokens ?? 0, completion_tokens: u.output_tokens ?? 0, total_tokens: u.total_tokens ?? 0 }
|
|
258
347
|
: undefined
|
|
259
|
-
|
|
348
|
+
const reason = t === "response.incomplete"
|
|
349
|
+
? finishReasonOf({ ...d.response, status: "incomplete" }, "stop")
|
|
350
|
+
: (state.toolIndex ? "tool_calls" : "stop")
|
|
351
|
+
out.push(chunk({}, reason, usage))
|
|
260
352
|
out.push("data: [DONE]\n\n")
|
|
261
353
|
state.done = true
|
|
262
354
|
}
|
|
@@ -267,19 +359,45 @@ export function responseEventToChatChunks(d, model, id, state) {
|
|
|
267
359
|
export function responsesSSEToChatSSE(bytes, model = "junie-lite") {
|
|
268
360
|
const state = { toolIndex: 0, toolById: new Map(), done: false }
|
|
269
361
|
const id = `chatcmpl-${Date.now()}`
|
|
270
|
-
|
|
362
|
+
let buf = new TextDecoder().decode(bytes)
|
|
271
363
|
const out = []
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
out.push(...responseEventToChatChunks(d, model, id, state))
|
|
364
|
+
let frame
|
|
365
|
+
while ((frame = nextSSEFrame(buf))) {
|
|
366
|
+
const raw = buf.slice(0, frame.index)
|
|
367
|
+
buf = buf.slice(frame.index + frame.sepLen)
|
|
368
|
+
const d = parseSSEFrame(raw)
|
|
369
|
+
if (d) out.push(...responseEventToChatChunks(d, model, id, state))
|
|
370
|
+
}
|
|
371
|
+
if (buf.trim()) {
|
|
372
|
+
const d = parseSSEFrame(buf)
|
|
373
|
+
if (d) out.push(...responseEventToChatChunks(d, model, id, state))
|
|
278
374
|
}
|
|
279
375
|
if (!state.done) out.push(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`, "data: [DONE]\n\n")
|
|
280
376
|
return new TextEncoder().encode(out.join(""))
|
|
281
377
|
}
|
|
282
378
|
|
|
379
|
+
/**
|
|
380
|
+
* 从 SSE 缓冲里取出下一个完整帧的边界,返回 {index, sepLen} 或 null。
|
|
381
|
+
* 同时兼容 \n\n 与 \r\n\r\n,并取位置更靠前的那个——
|
|
382
|
+
* 若总是优先找 CRLF,混用分隔符时会跳过先到的 LF 帧导致文本丢失。
|
|
383
|
+
*/
|
|
384
|
+
export function nextSSEFrame(buf) {
|
|
385
|
+
const a = buf.indexOf("\n\n")
|
|
386
|
+
const b = buf.indexOf("\r\n\r\n")
|
|
387
|
+
if (a < 0 && b < 0) return null
|
|
388
|
+
if (b >= 0 && (a < 0 || b < a)) return { index: b, sepLen: 4 }
|
|
389
|
+
return { index: a, sepLen: 2 }
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 解析一帧 SSE 的 data 载荷;不是 data 行或无有效 JSON 返回 null。 */
|
|
393
|
+
export function parseSSEFrame(raw) {
|
|
394
|
+
const line = raw.split(/\r?\n/).find((l) => l.startsWith("data:"))
|
|
395
|
+
if (!line) return null
|
|
396
|
+
const data = line.slice(5).trim()
|
|
397
|
+
if (!data || data === "[DONE]") return null
|
|
398
|
+
try { return JSON.parse(data) } catch { return null }
|
|
399
|
+
}
|
|
400
|
+
|
|
283
401
|
/**
|
|
284
402
|
* 直连 fetch:magpie 调它,返回标准 chat completions 响应。
|
|
285
403
|
* 流式用 ReadableStream 边读边转,长回答期间客户端持续收到 chunk。
|
|
@@ -318,7 +436,13 @@ export function makeDirectFetch(auth, options = {}) {
|
|
|
318
436
|
|
|
319
437
|
if (!res.ok) {
|
|
320
438
|
const text = await res.text()
|
|
321
|
-
|
|
439
|
+
// 透传退避相关头(retry-after / x-ratelimit-*),agent 的限流处理依赖它们。
|
|
440
|
+
const h = { "Content-Type": "application/json" }
|
|
441
|
+
for (const k of ["retry-after", "x-ratelimit-limit-requests", "x-ratelimit-remaining-requests", "x-ratelimit-reset-requests", "x-ratelimit-limit-tokens", "x-ratelimit-remaining-tokens", "x-ratelimit-reset-tokens"]) {
|
|
442
|
+
const v = res.headers?.get?.(k)
|
|
443
|
+
if (v) h[k] = v
|
|
444
|
+
}
|
|
445
|
+
return new Response(text, { status: res.status, statusText: res.statusText, headers: h })
|
|
322
446
|
}
|
|
323
447
|
|
|
324
448
|
const replyModel = chat.model ?? "junie-lite"
|
|
@@ -335,23 +459,36 @@ export function makeDirectFetch(auth, options = {}) {
|
|
|
335
459
|
let buf = ""
|
|
336
460
|
const dec = new TextDecoder()
|
|
337
461
|
try {
|
|
462
|
+
const emit = (d) => {
|
|
463
|
+
if (!d) return
|
|
464
|
+
for (const s of responseEventToChatChunks(d, replyModel, id, state)) controller.enqueue(enc.encode(s))
|
|
465
|
+
}
|
|
338
466
|
for (;;) {
|
|
339
467
|
const { value, done } = await reader.read()
|
|
340
468
|
if (done) break
|
|
341
469
|
buf += dec.decode(value, { stream: true })
|
|
342
|
-
let
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
470
|
+
let frame
|
|
471
|
+
while ((frame = nextSSEFrame(buf))) {
|
|
472
|
+
const raw = buf.slice(0, frame.index)
|
|
473
|
+
buf = buf.slice(frame.index + frame.sepLen)
|
|
474
|
+
emit(parseSSEFrame(raw))
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// 流结束时处理残留:最后一个 SSE 帧可能不带结尾空行;
|
|
478
|
+
// 也可能上游根本没发 SSE 而直接给了 JSON(错误/降级),别静默吞掉。
|
|
479
|
+
const tail = buf.trim() + dec.decode()
|
|
480
|
+
if (tail) {
|
|
481
|
+
const d = parseSSEFrame(tail)
|
|
482
|
+
if (d) emit(d)
|
|
483
|
+
else if (tail.startsWith("{")) {
|
|
484
|
+
try {
|
|
485
|
+
const raw = JSON.parse(tail)
|
|
486
|
+
const c = fromResponsesJSON(raw, replyModel)
|
|
487
|
+
const msg = c.choices?.[0]?.message
|
|
488
|
+
if (msg?.content) controller.enqueue(enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: replyModel, choices: [{ index: 0, delta: { content: msg.content }, finish_reason: null }] })}\n\n`))
|
|
489
|
+
if (msg?.tool_calls?.length) controller.enqueue(enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: replyModel, choices: [{ index: 0, delta: { tool_calls: msg.tool_calls.map((tc, i) => ({ index: i, ...tc })) }, finish_reason: null }] })}\n\n`))
|
|
490
|
+
// 不设 state.done:下面的兜底还要发 finish + [DONE]
|
|
491
|
+
} catch { /* 非 JSON 残留忽略 */ }
|
|
355
492
|
}
|
|
356
493
|
}
|
|
357
494
|
} catch (e) {
|
|
@@ -382,6 +519,6 @@ export function makeDirectFetch(auth, options = {}) {
|
|
|
382
519
|
|
|
383
520
|
export const _internal = {
|
|
384
521
|
directHeaders, toResponsesInput, toResponsesTools, toResponsesBody,
|
|
385
|
-
fromResponsesJSON, responseEventToChatChunks, responsesSSEToChatSSE,
|
|
386
|
-
makeDirectFetch,
|
|
522
|
+
fromResponsesJSON, finishReasonOf, responseEventToChatChunks, responsesSSEToChatSSE,
|
|
523
|
+
nextSSEFrame, parseSSEFrame, makeDirectFetch,
|
|
387
524
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "magpie-junie-auth",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "magpie provider plugin: JetBrains Junie free tier (gpt-6-luna) via direct Responses API or CLI bridge; multi-account with browser PKCE / CLI login reuse",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|