magpie-junie-auth 0.2.2 → 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 +387 -44
- 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
|
@@ -2,9 +2,22 @@
|
|
|
2
2
|
// 不需要 CLI 本体,纯 HTTP 直连即可用免费额度(gpt-6-luna)。
|
|
3
3
|
// 精确请求头/body 见 DIRECT-PROTOCOL.md。
|
|
4
4
|
//
|
|
5
|
-
// magpie 侧发来的是 OpenAI Chat Completions(
|
|
6
|
-
//
|
|
7
|
-
//
|
|
5
|
+
// magpie 侧发来的是 OpenAI Chat Completions(agent 常用 tools / 图片 / 流式),
|
|
6
|
+
// 这里做双向协议转换:
|
|
7
|
+
// chat.completions → /v1/responses(input[] + tools + tool_choice)
|
|
8
|
+
// responses 返回 → chat.completions(含 tool_calls / 真流式 SSE / usage)
|
|
9
|
+
//
|
|
10
|
+
// 关键映射(OpenAI Responses 规范,CLI 抓包确认事件名):
|
|
11
|
+
// chat tools[{type:function,function:{name,description,parameters}}]
|
|
12
|
+
// → responses tools[{type:function,name,description,parameters}]
|
|
13
|
+
// assistant.tool_calls[{id,function:{name,arguments}}]
|
|
14
|
+
// → input item {type:function_call,call_id,name,arguments}
|
|
15
|
+
// role:"tool" {tool_call_id,content}
|
|
16
|
+
// → input item {type:function_call_output,call_id,output}
|
|
17
|
+
// output item {type:function_call,...}
|
|
18
|
+
// → chat tool_calls[{id,type:function,function:{name,arguments}}]
|
|
19
|
+
// SSE response.function_call_arguments.delta/.done
|
|
20
|
+
// → chat delta.tool_calls[].function.arguments
|
|
8
21
|
|
|
9
22
|
import { proxyFetch } from "./proxy.mjs"
|
|
10
23
|
|
|
@@ -33,23 +46,132 @@ export function directHeaders(token, { effort = "low", purpose = "ISSUE_AGENT",
|
|
|
33
46
|
}
|
|
34
47
|
}
|
|
35
48
|
|
|
36
|
-
/**
|
|
49
|
+
/** chat content(字符串或 parts) → 纯文本(system/instructions 用)。 */
|
|
50
|
+
function contentToText(content) {
|
|
51
|
+
if (typeof content === "string") return content
|
|
52
|
+
if (!Array.isArray(content)) return content == null ? "" : String(content)
|
|
53
|
+
return content.map((p) => {
|
|
54
|
+
if (typeof p === "string") return p
|
|
55
|
+
if (p?.type === "text") return p.text ?? ""
|
|
56
|
+
if (p?.type === "input_text") return p.text ?? ""
|
|
57
|
+
return ""
|
|
58
|
+
}).join("\n")
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* chat content parts → Responses input content parts。
|
|
63
|
+
* 保留 text / image_url / input_image;未识别的 part 保留其 text 字段而不静默丢弃。
|
|
64
|
+
*/
|
|
65
|
+
function contentToParts(content) {
|
|
66
|
+
if (content == null) return undefined
|
|
67
|
+
if (typeof content === "string") return content
|
|
68
|
+
if (!Array.isArray(content)) return String(content)
|
|
69
|
+
const parts = []
|
|
70
|
+
for (const p of content) {
|
|
71
|
+
if (typeof p === "string") { parts.push({ type: "input_text", text: p }); continue }
|
|
72
|
+
if (!p || typeof p !== "object") continue
|
|
73
|
+
if (p.type === "text" || p.type === "input_text") {
|
|
74
|
+
parts.push({ type: "input_text", text: String(p.text ?? "") })
|
|
75
|
+
} else if (p.type === "image_url" || p.type === "input_image") {
|
|
76
|
+
const url = typeof p.image_url === "string" ? p.image_url : p.image_url?.url
|
|
77
|
+
const detail = typeof p.image_url === "object" ? p.image_url.detail : p.detail
|
|
78
|
+
const out = { type: "input_image" }
|
|
79
|
+
if (url) out.image_url = url
|
|
80
|
+
if (detail) out.detail = detail
|
|
81
|
+
parts.push(out)
|
|
82
|
+
} else if (p.type === "input_file" || p.type === "file") {
|
|
83
|
+
parts.push({ type: "input_file", ...(p.file_id ? { file_id: p.file_id } : {}), ...(p.filename ? { filename: p.filename } : {}) })
|
|
84
|
+
} else if (p.text != null) {
|
|
85
|
+
// 不静默丢内容:未知 part 有 text 就按文本发
|
|
86
|
+
parts.push({ type: "input_text", text: String(p.text) })
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return parts.length ? parts : ""
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Chat Completions messages → Responses input[](system 提为 instructions)。
|
|
94
|
+
* assistant.tool_calls → function_call item;role:"tool" → function_call_output item。
|
|
95
|
+
*/
|
|
37
96
|
export function toResponsesInput(messages = []) {
|
|
38
97
|
const input = []
|
|
39
98
|
let instructions
|
|
40
99
|
for (const m of messages) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
if (Array.isArray(text)) text = text.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("\n")
|
|
100
|
+
if (!m || typeof m !== "object") continue
|
|
101
|
+
const role = m.role ?? "user"
|
|
44
102
|
if (role === "system") {
|
|
45
|
-
|
|
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) })
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
if (role === "tool") {
|
|
116
|
+
// Responses 没有 tool role;function_call_output 用 call_id 关联。
|
|
117
|
+
input.push({
|
|
118
|
+
type: "function_call_output",
|
|
119
|
+
call_id: m.tool_call_id ?? m.id ?? "",
|
|
120
|
+
output: contentToParts(m.content) ?? "",
|
|
121
|
+
})
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
if (role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length) {
|
|
125
|
+
// 文本部分(可能为空)仍作为 assistant message 发出,避免历史断裂
|
|
126
|
+
const text = contentToText(m.content)
|
|
127
|
+
if (text) input.push({ role: "assistant", content: text })
|
|
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
|
+
}
|
|
134
|
+
input.push({
|
|
135
|
+
type: "function_call",
|
|
136
|
+
call_id: tc.id ?? tc.call_id ?? "",
|
|
137
|
+
name: tc.function?.name ?? tc.name ?? "",
|
|
138
|
+
arguments: args || "{}",
|
|
139
|
+
})
|
|
140
|
+
}
|
|
46
141
|
continue
|
|
47
142
|
}
|
|
48
|
-
|
|
143
|
+
const parts = contentToParts(m.content)
|
|
144
|
+
input.push({ role, content: parts === undefined ? "" : parts })
|
|
49
145
|
}
|
|
50
146
|
return { input, instructions }
|
|
51
147
|
}
|
|
52
148
|
|
|
149
|
+
/** chat tools / tool_choice → Responses 形状。 */
|
|
150
|
+
export function toResponsesTools(chat = {}) {
|
|
151
|
+
const out = {}
|
|
152
|
+
if (Array.isArray(chat.tools) && chat.tools.length) {
|
|
153
|
+
out.tools = chat.tools.map((t) => {
|
|
154
|
+
if (t?.type === "function" && t.function) {
|
|
155
|
+
return {
|
|
156
|
+
type: "function",
|
|
157
|
+
name: t.function.name ?? t.name,
|
|
158
|
+
...(t.function.description != null ? { description: t.function.description } : {}),
|
|
159
|
+
parameters: t.function.parameters ?? {},
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return t
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
if (chat.tool_choice != null) {
|
|
166
|
+
const c = chat.tool_choice
|
|
167
|
+
if (typeof c === "string") out.tool_choice = c
|
|
168
|
+
else if (c?.type === "function") {
|
|
169
|
+
out.tool_choice = { type: "function", name: c.function?.name ?? c.name }
|
|
170
|
+
} else out.tool_choice = c
|
|
171
|
+
}
|
|
172
|
+
return out
|
|
173
|
+
}
|
|
174
|
+
|
|
53
175
|
/** 构造 Responses 请求 body。 */
|
|
54
176
|
export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
|
|
55
177
|
const { input, instructions } = toResponsesInput(chat?.messages)
|
|
@@ -60,30 +182,85 @@ export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
|
|
|
60
182
|
stream: Boolean(chat?.stream),
|
|
61
183
|
text: { format: { type: "text" } },
|
|
62
184
|
store: false,
|
|
185
|
+
...toResponsesTools(chat),
|
|
63
186
|
}
|
|
64
187
|
if (instructions) body.instructions = instructions
|
|
65
188
|
if (eff && eff !== "none") body.reasoning = { effort: eff }
|
|
66
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
|
+
}
|
|
67
203
|
return body
|
|
68
204
|
}
|
|
69
205
|
|
|
70
|
-
/** Responses
|
|
71
|
-
|
|
206
|
+
/** Responses output items → chat message(text + tool_calls)+ finish_reason。 */
|
|
207
|
+
function responseItemsToMessage(items = []) {
|
|
72
208
|
let text = ""
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
209
|
+
let reasoningText = ""
|
|
210
|
+
const toolCalls = []
|
|
211
|
+
for (const item of items) {
|
|
212
|
+
if (item?.type === "message") {
|
|
213
|
+
for (const c of item?.content ?? []) {
|
|
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}]`
|
|
216
|
+
else if (c?.type === "output_image" && c.image_url) text += `[image: ${c.image_url}]`
|
|
217
|
+
else if (c?.text) text += String(c.text)
|
|
218
|
+
}
|
|
219
|
+
} else if (item?.type === "function_call") {
|
|
220
|
+
toolCalls.push({
|
|
221
|
+
id: item.call_id ?? item.id ?? `call_${Math.random().toString(36).slice(2)}`,
|
|
222
|
+
type: "function",
|
|
223
|
+
function: { name: item.name ?? "", arguments: item.arguments ?? "{}" },
|
|
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
|
|
78
229
|
}
|
|
79
230
|
}
|
|
231
|
+
const message = { role: "assistant", content: text }
|
|
232
|
+
if (reasoningText) message.reasoning_content = reasoningText
|
|
233
|
+
if (toolCalls.length) message.tool_calls = toolCalls
|
|
234
|
+
return { message, finish_reason: toolCalls.length ? "tool_calls" : "stop" }
|
|
235
|
+
}
|
|
236
|
+
|
|
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
|
+
|
|
248
|
+
export function fromResponsesJSON(resp, model = "junie-lite") {
|
|
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
|
+
}
|
|
80
257
|
const u = resp?.usage ?? {}
|
|
81
258
|
return {
|
|
82
259
|
id: resp?.id ?? `chatcmpl-${Date.now()}`,
|
|
83
260
|
object: "chat.completion",
|
|
84
261
|
created: resp?.created_at ?? Math.floor(Date.now() / 1000),
|
|
85
262
|
model,
|
|
86
|
-
choices: [{ index: 0, message
|
|
263
|
+
choices: [{ index: 0, message, finish_reason }],
|
|
87
264
|
usage: {
|
|
88
265
|
prompt_tokens: u.input_tokens ?? 0,
|
|
89
266
|
completion_tokens: u.output_tokens ?? 0,
|
|
@@ -92,41 +269,144 @@ export function fromResponsesJSON(resp, model = "junie-lite") {
|
|
|
92
269
|
}
|
|
93
270
|
}
|
|
94
271
|
|
|
95
|
-
/**
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
272
|
+
/**
|
|
273
|
+
* Responses SSE 事件 → Chat Completions SSE chunk(可逐个事件调用)。
|
|
274
|
+
* 返回字符串数组(可能为空);工具调用按 index 递增。
|
|
275
|
+
*/
|
|
276
|
+
export function responseEventToChatChunks(d, model, id, state) {
|
|
277
|
+
const created = Math.floor(Date.now() / 1000)
|
|
278
|
+
const chunk = (delta, finish_reason = null, usage) => {
|
|
279
|
+
const o = {
|
|
280
|
+
id, object: "chat.completion.chunk", created, model,
|
|
281
|
+
choices: [{ index: 0, delta, finish_reason }],
|
|
282
|
+
}
|
|
283
|
+
if (usage) o.usage = usage
|
|
284
|
+
return `data: ${JSON.stringify(o)}\n\n`
|
|
285
|
+
}
|
|
99
286
|
const out = []
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
out.push(
|
|
112
|
-
|
|
287
|
+
const t = d?.type
|
|
288
|
+
if (t === "response.output_text.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
|
+
}
|
|
301
|
+
} else if (t === "response.output_item.added" && d.item?.type === "function_call") {
|
|
302
|
+
const idx = state.toolIndex++
|
|
303
|
+
state.toolById.set(d.item.id ?? d.item.call_id, idx)
|
|
304
|
+
out.push(chunk({
|
|
305
|
+
tool_calls: [{
|
|
306
|
+
index: idx,
|
|
307
|
+
id: d.item.call_id ?? d.item.id,
|
|
308
|
+
type: "function",
|
|
309
|
+
function: { name: d.item.name ?? "", arguments: "" },
|
|
310
|
+
}],
|
|
311
|
+
}))
|
|
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 补齐。
|
|
328
|
+
const idx = state.toolById.get(d.item_id) ?? 0
|
|
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)
|
|
113
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
|
|
343
|
+
} else if (t === "response.completed" || t === "response.incomplete") {
|
|
344
|
+
const u = d.response?.usage ?? {}
|
|
345
|
+
const usage = u.input_tokens != null || u.output_tokens != null
|
|
346
|
+
? { prompt_tokens: u.input_tokens ?? 0, completion_tokens: u.output_tokens ?? 0, total_tokens: u.total_tokens ?? 0 }
|
|
347
|
+
: undefined
|
|
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))
|
|
352
|
+
out.push("data: [DONE]\n\n")
|
|
353
|
+
state.done = true
|
|
114
354
|
}
|
|
115
|
-
|
|
355
|
+
return out
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** 一次性把 Responses SSE 字节流转成 Chat SSE(测试/非浏览器用)。 */
|
|
359
|
+
export function responsesSSEToChatSSE(bytes, model = "junie-lite") {
|
|
360
|
+
const state = { toolIndex: 0, toolById: new Map(), done: false }
|
|
361
|
+
const id = `chatcmpl-${Date.now()}`
|
|
362
|
+
let buf = new TextDecoder().decode(bytes)
|
|
363
|
+
const out = []
|
|
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))
|
|
374
|
+
}
|
|
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")
|
|
116
376
|
return new TextEncoder().encode(out.join(""))
|
|
117
377
|
}
|
|
118
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
|
+
|
|
119
401
|
/**
|
|
120
402
|
* 直连 fetch:magpie 调它,返回标准 chat completions 响应。
|
|
121
|
-
*
|
|
122
|
-
* @param options 插件选项(model / effort / grazieAgentVersion / proxy)
|
|
403
|
+
* 流式用 ReadableStream 边读边转,长回答期间客户端持续收到 chunk。
|
|
123
404
|
*/
|
|
124
405
|
export function makeDirectFetch(auth, options = {}) {
|
|
125
406
|
const token = auth?.access ?? auth?.key
|
|
126
407
|
|
|
127
408
|
return async function directFetch(input, init = {}) {
|
|
128
409
|
const url = new URL(String(input))
|
|
129
|
-
// magpie 可能发 /chat/completions、/responses 或模型名路径;统一到 /v1/responses
|
|
130
410
|
url.pathname = "/v1/responses"
|
|
131
411
|
url.search = ""
|
|
132
412
|
|
|
@@ -156,13 +436,75 @@ export function makeDirectFetch(auth, options = {}) {
|
|
|
156
436
|
|
|
157
437
|
if (!res.ok) {
|
|
158
438
|
const text = await res.text()
|
|
159
|
-
|
|
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 })
|
|
160
446
|
}
|
|
161
447
|
|
|
162
448
|
const replyModel = chat.model ?? "junie-lite"
|
|
163
|
-
if (stream) {
|
|
164
|
-
const
|
|
165
|
-
|
|
449
|
+
if (stream && res.body) {
|
|
450
|
+
const reader = res.body.getReader()
|
|
451
|
+
const state = { toolIndex: 0, toolById: new Map(), done: false }
|
|
452
|
+
const id = `chatcmpl-${Date.now()}`
|
|
453
|
+
const enc = new TextEncoder()
|
|
454
|
+
const readable = new ReadableStream({
|
|
455
|
+
start(controller) {
|
|
456
|
+
// 后台循环持续读上游、解析 SSE、立即 enqueue。
|
|
457
|
+
// 不用 pull:上游会有空/心跳 chunk,pull 不 enqueue 会暂停流导致挂死。
|
|
458
|
+
;(async () => {
|
|
459
|
+
let buf = ""
|
|
460
|
+
const dec = new TextDecoder()
|
|
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
|
+
}
|
|
466
|
+
for (;;) {
|
|
467
|
+
const { value, done } = await reader.read()
|
|
468
|
+
if (done) break
|
|
469
|
+
buf += dec.decode(value, { stream: true })
|
|
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 残留忽略 */ }
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
} catch (e) {
|
|
495
|
+
try { controller.error(e) } catch {}
|
|
496
|
+
return
|
|
497
|
+
}
|
|
498
|
+
if (!state.done) {
|
|
499
|
+
controller.enqueue(enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: replyModel, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`))
|
|
500
|
+
controller.enqueue(enc.encode("data: [DONE]\n\n"))
|
|
501
|
+
}
|
|
502
|
+
controller.close()
|
|
503
|
+
})()
|
|
504
|
+
},
|
|
505
|
+
cancel() { try { reader.cancel() } catch {} },
|
|
506
|
+
})
|
|
507
|
+
return new Response(readable, {
|
|
166
508
|
status: 200,
|
|
167
509
|
headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache" },
|
|
168
510
|
})
|
|
@@ -176,6 +518,7 @@ export function makeDirectFetch(auth, options = {}) {
|
|
|
176
518
|
}
|
|
177
519
|
|
|
178
520
|
export const _internal = {
|
|
179
|
-
directHeaders, toResponsesInput, toResponsesBody,
|
|
180
|
-
fromResponsesJSON,
|
|
521
|
+
directHeaders, toResponsesInput, toResponsesTools, toResponsesBody,
|
|
522
|
+
fromResponsesJSON, finishReasonOf, responseEventToChatChunks, responsesSSEToChatSSE,
|
|
523
|
+
nextSSEFrame, parseSSEFrame, makeDirectFetch,
|
|
181
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",
|