magpie-junie-auth 0.2.1 → 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.
- package/README.md +1 -0
- package/index.mjs +21 -4
- package/lib/auth.mjs +25 -0
- package/lib/direct.mjs +243 -37
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
1. **从本机 Junie CLI 导入登录态** —— 读取已登录 CLI 的 OAuth 凭据:macOS 从 Keychain(`security`,service `junie-cli`),Windows 从 `~/.junie/dpapi_credentials/*.dpapi`(DPAPI)。刷新令牌与过期时间会完整保存,便于自动续期。
|
|
19
19
|
2. **浏览器登录(JetBrains 账号)** —— 复刻 CLI 的 PKCE 授权码流程,本地回调端口 62345–62364。
|
|
20
20
|
3. **API key (`perm-*`)** —— 从 https://junie.jetbrains.com/cli 获取。
|
|
21
|
+
4. **Refresh token (`oW66…` / `fHx…` / `8Sl…`)** —— 直接粘贴 JetBrains OAuth refresh token,插件自动换取 access token 并完整保存 refresh/expires/email,无需浏览器或本机 CLI。
|
|
21
22
|
|
|
22
23
|
凭据存在 magpie 的 `plugin-auth.json`(权限 600)。`auth.refresh` 在到期前 90 秒自动续期;账号额度耗尽时 magpie 自动切到下一个。
|
|
23
24
|
|
package/index.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// magpie-junie:把 JetBrains Junie 接入 magpie 供应商 `junie`。
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
// 1. 导入本机 CLI
|
|
3
|
+
// 四种登录方式(按优先级):
|
|
4
|
+
// 1. 导入本机 CLI 登录态(macOS Keychain / Windows DPAPI)——最快,不用浏览器
|
|
5
5
|
// 2. 浏览器 PKCE(Junie CLI 同款)——没有本地 CLI 时用
|
|
6
|
-
// 3. API key(perm-*,从 junie.jetbrains.com/cli
|
|
6
|
+
// 3. API key(perm-*,从 junie.jetbrains.com/cli 获取)
|
|
7
|
+
// 4. 直接粘贴 OAuth refresh token(oW66… / fHx… / 8Sl…)——换取并完整保存
|
|
7
8
|
//
|
|
8
9
|
// 请求链路(两种,由 options.bridgeUrl 选择):
|
|
9
10
|
// A. 直连上游:loader.fetch 把标准请求发到 ingrazzio-cloud-prod.labs.jb.gg
|
|
@@ -16,7 +17,7 @@
|
|
|
16
17
|
import { PROVIDER, DISPLAY_NAME } from "./lib/constants.mjs"
|
|
17
18
|
import { MODELS, configModels } from "./lib/models.mjs"
|
|
18
19
|
import { readCliCredentials } from "./lib/credentials.mjs"
|
|
19
|
-
import { startPkceLogin, refreshAccessToken } from "./lib/auth.mjs"
|
|
20
|
+
import { startPkceLogin, refreshAccessToken, signInWithRefreshToken } from "./lib/auth.mjs"
|
|
20
21
|
import { makeFetch } from "./lib/fetch.mjs"
|
|
21
22
|
import { makeDirectFetch, DIRECT_MODEL } from "./lib/direct.mjs"
|
|
22
23
|
import { usageHook } from "./lib/usage.mjs"
|
|
@@ -111,6 +112,22 @@ export async function JuniePlugin(input, options = {}) {
|
|
|
111
112
|
label: "Junie API key (perm-*)",
|
|
112
113
|
placeholder: "perm-…",
|
|
113
114
|
},
|
|
115
|
+
{
|
|
116
|
+
// 直接粘贴 OAuth refresh token(oW66… / fHx… / 8Sl…):
|
|
117
|
+
// prompts + authorize 让宿主标记 keyAsked,magpie 不再额外问 key。
|
|
118
|
+
type: "api",
|
|
119
|
+
label: "Refresh token (oW66… / fHx…)",
|
|
120
|
+
prompts: [
|
|
121
|
+
{ type: "password", key: "refresh", message: "Junie refresh token" },
|
|
122
|
+
],
|
|
123
|
+
async authorize(inputs = {}) {
|
|
124
|
+
try {
|
|
125
|
+
return await signInWithRefreshToken(inputs.refresh)
|
|
126
|
+
} catch (err) {
|
|
127
|
+
return { type: "failed", error: `refresh token 无效或上游拒绝:${String(err?.message ?? err).slice(0, 300)}` }
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
},
|
|
114
131
|
],
|
|
115
132
|
|
|
116
133
|
async loader(getAuth, provider) {
|
package/lib/auth.mjs
CHANGED
|
@@ -178,6 +178,30 @@ export async function startPkceLogin() {
|
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
180
|
|
|
181
|
+
/**
|
|
182
|
+
* 直接用 refresh token 换取完整账号(登录方法「Refresh token」用)。
|
|
183
|
+
* refresh token 来自 JetBrains CLI/OAuth,形如 oW66… / fHx… / 8Sl…。
|
|
184
|
+
*/
|
|
185
|
+
export async function signInWithRefreshToken(refresh) {
|
|
186
|
+
const token = String(refresh ?? "").trim()
|
|
187
|
+
if (!token) throw new Error("refresh token 不能为空")
|
|
188
|
+
const t = await exchangeToken({ grant_type: "refresh_token", refresh_token: token })
|
|
189
|
+
const access = t.id_token ?? t.access_token
|
|
190
|
+
if (!access) throw new Error("上游没有返回 access/id token")
|
|
191
|
+
const accountId = await resolveAccountId(t.access_token ?? access)
|
|
192
|
+
return {
|
|
193
|
+
type: "success",
|
|
194
|
+
key: access,
|
|
195
|
+
access,
|
|
196
|
+
accessToken: t.access_token,
|
|
197
|
+
idToken: t.id_token,
|
|
198
|
+
refresh: t.refresh_token ?? token,
|
|
199
|
+
expires: t.expires_in ? Date.now() + t.expires_in * 1000 : 0,
|
|
200
|
+
accountId,
|
|
201
|
+
metadata: { source: "refresh-token", license: "free", email: accountId, freeGoogleApi: true },
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
181
205
|
export const _internal = {
|
|
182
206
|
generatePKCE,
|
|
183
207
|
buildAuthUrl,
|
|
@@ -185,5 +209,6 @@ export const _internal = {
|
|
|
185
209
|
refreshAccessToken,
|
|
186
210
|
resolveAccountId,
|
|
187
211
|
startCallbackServer,
|
|
212
|
+
signInWithRefreshToken,
|
|
188
213
|
pending,
|
|
189
214
|
}
|
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,119 @@ 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") {
|
|
103
|
+
const text = contentToText(m.content)
|
|
45
104
|
instructions = instructions ? instructions + "\n" + text : text
|
|
46
105
|
continue
|
|
47
106
|
}
|
|
48
|
-
|
|
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
|
|
71
|
-
|
|
180
|
+
/** Responses output items → chat message(text + tool_calls)+ finish_reason。 */
|
|
181
|
+
function responseItemsToMessage(items = []) {
|
|
72
182
|
let text = ""
|
|
73
|
-
const
|
|
74
|
-
for (const item of
|
|
75
|
-
if (item?.type
|
|
76
|
-
|
|
77
|
-
|
|
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
|
|
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
|
-
/**
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
*
|
|
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
|
|
165
|
-
|
|
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,
|
|
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.
|
|
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",
|