magpie-junie-auth 0.2.2 → 0.2.3

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.
Files changed (2) hide show
  1. package/lib/direct.mjs +243 -37
  2. package/package.json +1 -1
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(npm: @ai-sdk/openai-compatible),
6
- // 这里把它转成 Responses API:/v1/responses + input[] + model=gpt-6-luna,
7
- // 再把响应转回 chat completions(非流式 JSON / 流式 SSE)。
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,119 @@ export function directHeaders(token, { effort = "low", purpose = "ISSUE_AGENT",
33
46
  }
34
47
  }
35
48
 
36
- /** Chat Completions messages → Responses input[](system 提为 instructions)。 */
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
- const role = m?.role ?? "user"
42
- let text = m?.content ?? ""
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") {
103
+ const text = contentToText(m.content)
45
104
  instructions = instructions ? instructions + "\n" + text : text
46
105
  continue
47
106
  }
48
- input.push({ role, content: String(text) })
107
+ if (role === "tool") {
108
+ // Responses 没有 tool role;function_call_output 用 call_id 关联。
109
+ input.push({
110
+ type: "function_call_output",
111
+ call_id: m.tool_call_id ?? m.id ?? "",
112
+ output: contentToParts(m.content) ?? "",
113
+ })
114
+ continue
115
+ }
116
+ if (role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length) {
117
+ // 文本部分(可能为空)仍作为 assistant message 发出,避免历史断裂
118
+ const text = contentToText(m.content)
119
+ if (text) input.push({ role: "assistant", content: text })
120
+ for (const tc of m.tool_calls) {
121
+ input.push({
122
+ type: "function_call",
123
+ call_id: tc.id ?? tc.call_id ?? "",
124
+ name: tc.function?.name ?? tc.name ?? "",
125
+ arguments: tc.function?.arguments ?? tc.arguments ?? "{}",
126
+ })
127
+ }
128
+ continue
129
+ }
130
+ const parts = contentToParts(m.content)
131
+ input.push({ role, content: parts === undefined ? "" : parts })
49
132
  }
50
133
  return { input, instructions }
51
134
  }
52
135
 
136
+ /** chat tools / tool_choice → Responses 形状。 */
137
+ export function toResponsesTools(chat = {}) {
138
+ const out = {}
139
+ if (Array.isArray(chat.tools) && chat.tools.length) {
140
+ out.tools = chat.tools.map((t) => {
141
+ if (t?.type === "function" && t.function) {
142
+ return {
143
+ type: "function",
144
+ name: t.function.name ?? t.name,
145
+ ...(t.function.description != null ? { description: t.function.description } : {}),
146
+ parameters: t.function.parameters ?? {},
147
+ }
148
+ }
149
+ return t
150
+ })
151
+ }
152
+ if (chat.tool_choice != null) {
153
+ const c = chat.tool_choice
154
+ if (typeof c === "string") out.tool_choice = c
155
+ else if (c?.type === "function") {
156
+ out.tool_choice = { type: "function", name: c.function?.name ?? c.name }
157
+ } else out.tool_choice = c
158
+ }
159
+ return out
160
+ }
161
+
53
162
  /** 构造 Responses 请求 body。 */
54
163
  export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
55
164
  const { input, instructions } = toResponsesInput(chat?.messages)
@@ -60,6 +169,7 @@ export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
60
169
  stream: Boolean(chat?.stream),
61
170
  text: { format: { type: "text" } },
62
171
  store: false,
172
+ ...toResponsesTools(chat),
63
173
  }
64
174
  if (instructions) body.instructions = instructions
65
175
  if (eff && eff !== "none") body.reasoning = { effort: eff }
@@ -67,23 +177,40 @@ export function toResponsesBody(chat, { model = DIRECT_MODEL, effort } = {}) {
67
177
  return body
68
178
  }
69
179
 
70
- /** Responses JSON → Chat Completions JSON。 */
71
- export function fromResponsesJSON(resp, model = "junie-lite") {
180
+ /** Responses output items → chat message(text + tool_calls)+ finish_reason。 */
181
+ function responseItemsToMessage(items = []) {
72
182
  let text = ""
73
- const outputs = resp?.output ?? []
74
- for (const item of outputs) {
75
- if (item?.type !== "message") continue
76
- for (const c of item?.content ?? []) {
77
- if (c?.type === "output_text" && typeof c.text === "string") text += c.text
183
+ const toolCalls = []
184
+ for (const item of items) {
185
+ if (item?.type === "message") {
186
+ for (const c of item?.content ?? []) {
187
+ if ((c?.type === "output_text" || c?.type === "input_text") && typeof c.text === "string") text += c.text
188
+ else if (c?.type === "output_image" && c.image_url) text += `[image: ${c.image_url}]`
189
+ else if (c?.text) text += String(c.text)
190
+ }
191
+ } else if (item?.type === "function_call") {
192
+ toolCalls.push({
193
+ id: item.call_id ?? item.id ?? `call_${Math.random().toString(36).slice(2)}`,
194
+ type: "function",
195
+ function: { name: item.name ?? "", arguments: item.arguments ?? "{}" },
196
+ })
78
197
  }
79
198
  }
199
+ const message = { role: "assistant", content: text }
200
+ if (toolCalls.length) message.tool_calls = toolCalls
201
+ return { message, finish_reason: toolCalls.length ? "tool_calls" : "stop" }
202
+ }
203
+
204
+ /** Responses JSON → Chat Completions JSON。 */
205
+ export function fromResponsesJSON(resp, model = "junie-lite") {
206
+ const { message, finish_reason } = responseItemsToMessage(resp?.output)
80
207
  const u = resp?.usage ?? {}
81
208
  return {
82
209
  id: resp?.id ?? `chatcmpl-${Date.now()}`,
83
210
  object: "chat.completion",
84
211
  created: resp?.created_at ?? Math.floor(Date.now() / 1000),
85
212
  model,
86
- choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }],
213
+ choices: [{ index: 0, message, finish_reason }],
87
214
  usage: {
88
215
  prompt_tokens: u.input_tokens ?? 0,
89
216
  completion_tokens: u.output_tokens ?? 0,
@@ -92,41 +219,76 @@ export function fromResponsesJSON(resp, model = "junie-lite") {
92
219
  }
93
220
  }
94
221
 
95
- /** 把 Responses SSE 流转成 Chat Completions SSE 流。 */
96
- export function responsesSSEToChatSSE(bytes, model = "junie-lite") {
97
- const dec = new TextDecoder()
98
- const events = dec.decode(bytes).split(/\r?\n\r?\n/)
222
+ /**
223
+ * Responses SSE 事件 → Chat Completions SSE chunk(可逐个事件调用)。
224
+ * 返回字符串数组(可能为空);工具调用按 index 递增。
225
+ */
226
+ export function responseEventToChatChunks(d, model, id, state) {
227
+ const created = Math.floor(Date.now() / 1000)
228
+ const chunk = (delta, finish_reason = null, usage) => {
229
+ const o = {
230
+ id, object: "chat.completion.chunk", created, model,
231
+ choices: [{ index: 0, delta, finish_reason }],
232
+ }
233
+ if (usage) o.usage = usage
234
+ return `data: ${JSON.stringify(o)}\n\n`
235
+ }
99
236
  const out = []
237
+ const t = d?.type
238
+ if (t === "response.output_text.delta") {
239
+ if (d.delta) out.push(chunk({ content: d.delta }))
240
+ } else if (t === "response.output_item.added" && d.item?.type === "function_call") {
241
+ const idx = state.toolIndex++
242
+ state.toolById.set(d.item.id ?? d.item.call_id, idx)
243
+ out.push(chunk({
244
+ tool_calls: [{
245
+ index: idx,
246
+ id: d.item.call_id ?? d.item.id,
247
+ type: "function",
248
+ function: { name: d.item.name ?? "", arguments: "" },
249
+ }],
250
+ }))
251
+ } else if (t === "response.function_call_arguments.delta") {
252
+ const idx = state.toolById.get(d.item_id) ?? 0
253
+ if (d.delta) out.push(chunk({ tool_calls: [{ index: idx, function: { arguments: d.delta } }] }))
254
+ } else if (t === "response.completed" || t === "response.incomplete") {
255
+ const u = d.response?.usage ?? {}
256
+ const usage = u.input_tokens != null || u.output_tokens != null
257
+ ? { prompt_tokens: u.input_tokens ?? 0, completion_tokens: u.output_tokens ?? 0, total_tokens: u.total_tokens ?? 0 }
258
+ : undefined
259
+ out.push(chunk({}, state.toolIndex ? "tool_calls" : "stop", usage))
260
+ out.push("data: [DONE]\n\n")
261
+ state.done = true
262
+ }
263
+ return out
264
+ }
265
+
266
+ /** 一次性把 Responses SSE 字节流转成 Chat SSE(测试/非浏览器用)。 */
267
+ export function responsesSSEToChatSSE(bytes, model = "junie-lite") {
268
+ const state = { toolIndex: 0, toolById: new Map(), done: false }
100
269
  const id = `chatcmpl-${Date.now()}`
270
+ const events = new TextDecoder().decode(bytes).split(/\r?\n\r?\n/)
271
+ const out = []
101
272
  for (const ev of events) {
102
273
  const line = ev.split(/\r?\n/).find((l) => l.startsWith("data:"))
103
274
  if (!line) continue
104
275
  let d
105
276
  try { d = JSON.parse(line.slice(5).trim()) } catch { continue }
106
- const t = d?.type
107
- if (t === "response.output_text.delta") {
108
- const delta = d.delta ?? ""
109
- out.push(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { content: delta }, finish_reason: null }] })}\n\n`)
110
- } else if (t === "response.completed") {
111
- 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`)
112
- out.push("data: [DONE]\n\n")
113
- }
277
+ out.push(...responseEventToChatChunks(d, model, id, state))
114
278
  }
115
- if (!out.some((s) => s.includes("[DONE]"))) out.push("data: [DONE]\n\n")
279
+ 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
280
  return new TextEncoder().encode(out.join(""))
117
281
  }
118
282
 
119
283
  /**
120
284
  * 直连 fetch:magpie 调它,返回标准 chat completions 响应。
121
- * @param auth 已登录账号(access=id_token)
122
- * @param options 插件选项(model / effort / grazieAgentVersion / proxy)
285
+ * 流式用 ReadableStream 边读边转,长回答期间客户端持续收到 chunk。
123
286
  */
124
287
  export function makeDirectFetch(auth, options = {}) {
125
288
  const token = auth?.access ?? auth?.key
126
289
 
127
290
  return async function directFetch(input, init = {}) {
128
291
  const url = new URL(String(input))
129
- // magpie 可能发 /chat/completions、/responses 或模型名路径;统一到 /v1/responses
130
292
  url.pathname = "/v1/responses"
131
293
  url.search = ""
132
294
 
@@ -160,9 +322,52 @@ export function makeDirectFetch(auth, options = {}) {
160
322
  }
161
323
 
162
324
  const replyModel = chat.model ?? "junie-lite"
163
- if (stream) {
164
- const bytes = new Uint8Array(await res.arrayBuffer())
165
- return new Response(responsesSSEToChatSSE(bytes, replyModel), {
325
+ if (stream && res.body) {
326
+ const reader = res.body.getReader()
327
+ const state = { toolIndex: 0, toolById: new Map(), done: false }
328
+ const id = `chatcmpl-${Date.now()}`
329
+ const enc = new TextEncoder()
330
+ const readable = new ReadableStream({
331
+ start(controller) {
332
+ // 后台循环持续读上游、解析 SSE、立即 enqueue。
333
+ // 不用 pull:上游会有空/心跳 chunk,pull 不 enqueue 会暂停流导致挂死。
334
+ ;(async () => {
335
+ let buf = ""
336
+ const dec = new TextDecoder()
337
+ try {
338
+ for (;;) {
339
+ const { value, done } = await reader.read()
340
+ if (done) break
341
+ buf += dec.decode(value, { stream: true })
342
+ let i
343
+ // 上游 SSE 用 CRLF(\r\n\r\n);仅找 \n\n 会匹配不到。
344
+ while ((i = buf.indexOf("\r\n\r\n")) >= 0 || (i = buf.indexOf("\n\n")) >= 0) {
345
+ const sepLen = buf.startsWith("\r\n\r\n", i) ? 4 : 2
346
+ const raw = buf.slice(0, i)
347
+ buf = buf.slice(i + sepLen)
348
+ const line = raw.split(/\r?\n/).find((l) => l.startsWith("data:"))
349
+ if (!line) continue
350
+ const data = line.slice(5).trim()
351
+ if (!data || data === "[DONE]") continue
352
+ let d
353
+ try { d = JSON.parse(data) } catch { continue }
354
+ for (const s of responseEventToChatChunks(d, replyModel, id, state)) controller.enqueue(enc.encode(s))
355
+ }
356
+ }
357
+ } catch (e) {
358
+ try { controller.error(e) } catch {}
359
+ return
360
+ }
361
+ if (!state.done) {
362
+ 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`))
363
+ controller.enqueue(enc.encode("data: [DONE]\n\n"))
364
+ }
365
+ controller.close()
366
+ })()
367
+ },
368
+ cancel() { try { reader.cancel() } catch {} },
369
+ })
370
+ return new Response(readable, {
166
371
  status: 200,
167
372
  headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache" },
168
373
  })
@@ -176,6 +381,7 @@ export function makeDirectFetch(auth, options = {}) {
176
381
  }
177
382
 
178
383
  export const _internal = {
179
- directHeaders, toResponsesInput, toResponsesBody,
180
- fromResponsesJSON, responsesSSEToChatSSE, makeDirectFetch,
384
+ directHeaders, toResponsesInput, toResponsesTools, toResponsesBody,
385
+ fromResponsesJSON, responseEventToChatChunks, responsesSSEToChatSSE,
386
+ makeDirectFetch,
181
387
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie-junie-auth",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
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",