magpie-junie-auth 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,70 @@
1
+ # Junie Lite 直连协议(逆向实测,2026-11-25)
2
+
3
+ **结论:不需要 CLI 本体,纯 HTTP 直连即可用免费额度出字。** 延迟约 3-4 秒(对比 CLI 桥接的 30-36 秒)。
4
+
5
+ 之前直连全部失败是因为请求头组合不对。协议是从 CLI v4171.6 的真实请求中抓出来的(JVM `-Djavax.net.debug=ssl:plaintext` 会打印 TLS 内 HTTP 明文)。
6
+
7
+ ## 端点
8
+
9
+ ```
10
+ POST https://ingrazzio-cloud-prod.labs.jb.gg/v1/responses
11
+ ```
12
+
13
+ ## 必需请求头(缺一不可)
14
+
15
+ | Header | 值 | 备注 |
16
+ |---|---|---|
17
+ | `Authorization` | `Bearer <id_token>` | 用 id_token,不是 access_token;从 OAuth refresh 或 keychain 取 |
18
+ | `Accept` | `text/event-stream,text/event-stream` | 非流式也这么发 |
19
+ | `X-LLM-Model` | `openai` | **关键**,之前猜 jbai 全错 |
20
+ | `X-Keep-Path` | `true` | |
21
+ | `X-Forced-License-Free` | `2` | **关键**,不是 `true`(新版值) |
22
+ | `X-Accept-EAP-License` | `false` | **关键**,之前传 true 导致失败 |
23
+ | `X-Accept-Release-License` | `false` | 同上 |
24
+ | `Grazie-Agent` | `{"name":"junie:cli","version":"4171.6:4171.6"}` | 版本格式是 `V:V` |
25
+ | `X-Client-Feature-Id` | `junie` | 不是 `junie-cli/版本` |
26
+ | `X-Client-Execution-Id` | 任意字符串 | |
27
+ | `Accept-Encoding` | `identity` | |
28
+ | `JetBrains-LLM-Context` | `purpose=LANGUAGE_DETECTION` 或 `purpose=ISSUE_AGENT` | CLI 按用途区分 |
29
+ | `Openai-Version` | `2020-11-07` | |
30
+ | `User-Agent` | `junie-cli-batch:26.11.3` | marketing 版本 |
31
+ | `Cache-Control` | `no-store` | |
32
+ | `Content-Type` | `application/json` | |
33
+
34
+ ## Body(Responses API 格式,不是 chat completions)
35
+
36
+ ```json
37
+ {
38
+ "model": "gpt-6-luna",
39
+ "input": [{"role": "user", "content": "只回复OK"}],
40
+ "stream": false,
41
+ "text": {"format": {"type": "text"}},
42
+ "reasoning": {"effort": "low"},
43
+ "store": false,
44
+ "prompt_cache_retention": "24h"
45
+ }
46
+ ```
47
+
48
+ - `model` 必须是 wireName `gpt-6-luna`(不是 `junie-lite`、不是 `openai-gpt-6-luna`)
49
+ - `input` 是 Responses API 格式;CLI 里元素用 `{"type":"input_text","text":...}`,简单字符串也可工作
50
+ - `stream: true` 返回标准 SSE(`response.created` / `response.output_text.delta` / ...)
51
+
52
+ ## 响应
53
+
54
+ 非流式 HTTP 200 JSON:`output[].content[]` 中 `type=output_text` 的 `text` 即回复;`status`、`usage` 正常。
55
+ 流式 SSE 逐字 `delta`,结构同 OpenAI Responses API。
56
+
57
+ ## 验证记录
58
+
59
+ - 2026-11-25 00:43 HKT:非流式 `HTTP 200 / 3.77s`,回复 "OK",usage 14 tokens
60
+ - 同日:流式 SSE 正常输出 "流式"
61
+
62
+ ## Token 获取
63
+
64
+ `POST https://oauth.account.jetbrains.com/oauth2/token`,`grant_type=refresh_token`,
65
+ `client_id=junie-cli`,`refresh_token=<keychain 里的 refresh>`;取 `id_token`。
66
+ macOS keychain 读取见 `lib/credentials.mjs` 的 `readMacKeychainCredentials()`。
67
+
68
+ ## 待做
69
+
70
+ 把这套协议写进插件的 `lib/fetch.mjs`(替换现有直连逻辑),让 `junie` provider 不配 `bridgeUrl` 也能用免费额度,从而去掉 CLI 本体依赖。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aqiu817
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # magpie-junie-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把 **JetBrains Junie 的免费模型**接入 magpie 的供应商插件(provider id:`junie`)。
4
+
5
+ 免费档(`licenseType: GZL/NONE`)直连旧上游会被 `403 NO_LICENSE` 或 `400 UPDATE_REQUIRED` 拒绝。本插件实现了两条可用路径:
6
+
7
+ - **直连模式(默认,推荐)**:直接请求 Ingrazzio 的 `/v1/responses`,用逆向自 Junie CLI 的精确请求头 + `gpt-6-luna` 模型。**不需要在本机安装 Junie CLI**,单次约 2–4 秒。协议细节见 [DIRECT-PROTOCOL.md](./DIRECT-PROTOCOL.md)。
8
+ - **桥接模式(兜底)**:配 `bridgeUrl` 后把请求转给随附的 `bridge-server.mjs`,它调用本机 CLI headless 的 `junie-lite` 通道。需要装 CLI,单次约 30 秒;好处是上游协议变化时 CLI 会自动跟进。
9
+
10
+ 只暴露一个模型 `junie-lite`(底层当前为 OpenAI GPT-6 Luna,JetBrains 可能更换)。
11
+
12
+ > ⚠️ **风险声明**:本插件通过逆向非公开协议使用 JetBrains 的商业服务,不受 JetBrains 支持,可能随时失效。自动化/脚本化使用可能违反 [JetBrains AI Service Terms](https://www.jetbrains.com/legal/docs/terms/jetbrains-ai-service/)。请仅用于你自己的账号,风险自负。
13
+
14
+ ## 登录方式
15
+
16
+ 给 `junie` 添加账号时可选(支持**多个账号同时接入**,由 magpie 管理轮换):
17
+
18
+ 1. **从本机 Junie CLI 导入登录态** —— 读取已登录 CLI 的 OAuth 凭据:macOS 从 Keychain(`security`,service `junie-cli`),Windows 从 `~/.junie/dpapi_credentials/*.dpapi`(DPAPI)。刷新令牌与过期时间会完整保存,便于自动续期。
19
+ 2. **浏览器登录(JetBrains 账号)** —— 复刻 CLI 的 PKCE 授权码流程,本地回调端口 62345–62364。
20
+ 3. **API key (`perm-*`)** —— 从 https://junie.jetbrains.com/cli 获取。
21
+
22
+ 凭据存在 magpie 的 `plugin-auth.json`(权限 600)。`auth.refresh` 在到期前 90 秒自动续期;账号额度耗尽时 magpie 自动切到下一个。
23
+
24
+ ## 多账号
25
+
26
+ 插件无需自己实现轮换——magpie 原生支持:
27
+
28
+ ```sh
29
+ magpie plugin login junie # 每执行一次新增一个账号
30
+ magpie accounts junie # 列出所有账号(● 启用,○ 待命)
31
+ magpie accounts switch junie <email> # 切换默认
32
+ ```
33
+
34
+ ## 模型与请求
35
+
36
+ | 模式 | 上游路径 | 模型 | 是否要 CLI |
37
+ |---|---|---|---|
38
+ | 直连 | `POST /v1/responses` | `gpt-6-luna` | 否 |
39
+ | 桥接 | 本地 `POST /v1/chat/completions` → CLI headless | `junie-lite` | 是 |
40
+
41
+ 对客户端统一暴露 OpenAI Chat Completions(流式 SSE 与非流式均支持)。插件内部把 chat completions 转成 Responses API,再把响应转回。
42
+
43
+ 额度显示走 `GET /auth/test`:`plan` = licenseType、`balance` = balanceLeft + unit。上游不提供窗口百分比,`windows` 留空(不编造 `used: 0`)。
44
+
45
+ ## 安装
46
+
47
+ ```sh
48
+ magpie plugin add magpie-junie-auth
49
+ # 开发时
50
+ magpie plugin add /path/to/magpie-junie-auth
51
+ ```
52
+
53
+ 直连模式无需额外配置。要用桥接兜底时在插件 options 里设:
54
+
55
+ ```sh
56
+ magpie plugin options magpie-junie-auth '{"bridgeUrl":"http://127.0.0.1:4141/v1"}'
57
+ ```
58
+
59
+ ## 代理
60
+
61
+ 部分地区的 IP 直连 Ingrazzio 会返回 403。确保 fetch 走代理:
62
+
63
+ - magpie 宿主(Bun)有原生代理选项,插件会读宿主/环境变量里的代理设置。
64
+ - Node 可用 `NODE_USE_ENV_PROXY=1` 读取 `HTTP_PROXY`/`HTTPS_PROXY`。
65
+ - 插件选项 `proxy` 可显式指定。
66
+
67
+ ## 开发
68
+
69
+ ```sh
70
+ npm test # node --test,56 个测试
71
+ ```
72
+
73
+ ## 桥接服务(可选兜底)
74
+
75
+ ```sh
76
+ node bridge-server.mjs # 默认 127.0.0.1:4141
77
+ PORT=4142 JUNIE_MODEL=junie-lite node bridge-server.mjs
78
+ ```
79
+
80
+ 接口:`GET /health`、`GET /v1/models`、`POST /v1/chat/completions`(支持 `stream`)。
81
+ 环境变量:`PORT`、`HOST`、`JUNIE_BIN`(默认 `~/.local/bin/junie` 或 Windows 对应路径)、`JUNIE_MODEL`、`JUNIE_TIMEOUT_MS`、`JUNIE_AUTO_UPDATE`。
82
+ 桥接服务内置 CLI 版本检查(6 小时节流,自动执行 `junie update`),因为上游会提高免费模型的最低 CLI 版本要求。
83
+
84
+ ## 许可证
85
+
86
+ MIT —— 插件自身代码。Junie 与 JetBrains 是 JetBrains s.r.o. 的商标。
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env node
2
+ // Junie CLI headless → OpenAI 兼容本地服务。
3
+ //
4
+ // 背景:直连 Grazie 端点被 license=NONE 拒绝(403 NO_LICENSE),但 Junie CLI 内部的
5
+ // junie-lite 通道能正常回答(隔壁实测结论)。本服务把 OpenAI chat completions 翻译成
6
+ // 一次 CLI headless 调用:
7
+ // OpenAI messages → prompt 文本 → 临时文件(真实文件 fd 作 stdin)
8
+ // → spawn junie.bat --output-format json --model junie-lite
9
+ // → 从 stdout 找 JSON 行 → { result } → assistant 回复
10
+ //
11
+ // 坑(实锤 2026-11-24):
12
+ // 1. CLI 的 readPipedInput() 用 FileInputStream.available(),stdin 是 pipe 时 Windows 抛
13
+ // "函数不正确";必须给一个**真实文件**作 stdin(用 fs.openSync + spawn stdio fd)。
14
+ // 2. CLI stdout 混有日志行("Junie ... log file:" / "Junie update ... available."),
15
+ // 真正的 JSON 是其中一行,要以 `{` 开头解析。
16
+ // 3. `--task` 与 stdin 输入互斥;用 stdin 传 prompt 时不能带 --task。
17
+ // 4. 当前 CLI 26.11.2 的 junie-lite 被上游拒绝("version ... doesn't support this free
18
+ // model"),CLI 提示可升级 26.11.3;服务本身与版本无关,升级后即可用。
19
+
20
+ import { createServer } from "node:http"
21
+ import { spawn } from "node:child_process"
22
+ import { closeSync, mkdtempSync, openSync, rmSync, writeFileSync } from "node:fs"
23
+ import { tmpdir, homedir } from "node:os"
24
+ import { join } from "node:path"
25
+ import { checkAndUpdate } from "./lib/auto-update.mjs"
26
+
27
+ const AUTO_UPDATE = process.env.JUNIE_AUTO_UPDATE !== "off" // 默认开
28
+ const UPDATE_INTERVAL_MS = Number(process.env.JUNIE_UPDATE_INTERVAL_MS ?? 6 * 60 * 60 * 1000)
29
+
30
+ let lastUpdateInfo = null
31
+
32
+ /** 按需检查 CLI 版本(6h 节流),失败不影响服务。 */
33
+ async function maybeUpdate() {
34
+ if (!AUTO_UPDATE) return null
35
+ try {
36
+ const info = await checkAndUpdate({ intervalMs: UPDATE_INTERVAL_MS })
37
+ if (info.checked) {
38
+ lastUpdateInfo = info
39
+ console.log(`[auto-update] ${info.reason}: version=${info.version}${info.output.trim() ? ` | ${info.output.trim().slice(0, 300)}` : ""}`)
40
+ }
41
+ return info
42
+ } catch (err) {
43
+ console.warn(`[auto-update] check failed: ${err?.message ?? err}`)
44
+ return null
45
+ }
46
+ }
47
+
48
+ const PORT = Number(process.env.PORT ?? 4141)
49
+ const HOST = process.env.HOST ?? "127.0.0.1"
50
+ const DEFAULT_JUNIE = process.platform === "win32"
51
+ ? join(homedir(), ".local", "bin", "junie.bat")
52
+ : join(homedir(), ".local", "bin", "junie")
53
+ const JUNIE = process.env.JUNIE_BIN ?? DEFAULT_JUNIE
54
+ const MODEL = process.env.JUNIE_MODEL ?? "junie-lite"
55
+ const TIMEOUT_MS = Number(process.env.JUNIE_TIMEOUT_MS ?? 120_000)
56
+
57
+ /** OpenAI messages → 单个 prompt 文本(保留角色语义) */
58
+ export function messagesToPrompt(messages) {
59
+ if (!Array.isArray(messages)) return ""
60
+ return messages.map((m) => {
61
+ let content = m?.content ?? ""
62
+ if (Array.isArray(content)) content = content.map((p) => p?.text ?? "").join("\n")
63
+ const role = m?.role ?? "user"
64
+ if (role === "system") return `## 系统指令\n${content}`
65
+ if (role === "assistant") return `## 助手此前回复\n${content}`
66
+ return `## 用户\n${content}`
67
+ }).join("\n\n")
68
+ }
69
+
70
+ /**
71
+ * 从 CLI stdout 里找最后一个 JSON 对象行并解析。
72
+ *
73
+ * 编码坑(2026-11-24 实测):中文 Windows 上 CLI 的 stdout 是 **GBK** 字节
74
+ * (JSON 结构 ASCII + 中文 GBK 双字节),按 UTF-8 解码会得到 "Ŀǰ..." 乱码。
75
+ * 策略:先把 Buffer 按 UTF-8 解,若出现替换字符(U+FFFD)说明不是 UTF-8,
76
+ * 改用 GBK(TextDecoder('gbk'),Node 24 ICU 支持;GBK 兼容 ASCII,结构不受影响)。
77
+ */
78
+ export function decodeCliStdout(stdout) {
79
+ const buf = Buffer.isBuffer(stdout) ? stdout : Buffer.from(String(stdout), "utf8")
80
+ const utf8 = buf.toString("utf8")
81
+ if (!utf8.includes("\uFFFD")) return utf8
82
+ try { return new TextDecoder("gbk").decode(buf) } catch { return utf8 }
83
+ }
84
+
85
+ export function parseCliOutput(stdout) {
86
+ const lines = decodeCliStdout(stdout).split(/\r?\n/)
87
+ for (let i = lines.length - 1; i >= 0; i--) {
88
+ const line = lines[i].trim()
89
+ if (!line.startsWith("{")) continue
90
+ try {
91
+ const obj = JSON.parse(line)
92
+ if (obj && typeof obj === "object") return obj
93
+ } catch { /* 不是 JSON 行,继续往前找 */ }
94
+ }
95
+ return null
96
+ }
97
+
98
+ /** 正确实现:用 fs.openSync 把真实文件 fd 传给 spawn 的 stdin。 */
99
+ export function callJunie(prompt, { model = MODEL, timeoutMs = TIMEOUT_MS, bin = JUNIE } = {}) {
100
+ return new Promise((resolve, reject) => {
101
+ const dir = mkdtempSync(join(tmpdir(), "magpie-junie-"))
102
+ const stdinPath = join(dir, "prompt.txt")
103
+ // prompt 用 UTF-8 写:实测 CLI 从真实文件 stdin 读 UTF-8 中文能正确理解
104
+ // ("函数不正确"是 pipe stdin 的问题,与编码无关)。
105
+ writeFileSync(stdinPath, prompt, "utf8")
106
+ let fd
107
+ try { fd = openSync(stdinPath, "r") } catch (err) { rmSync(dir, { recursive: true, force: true }); return reject(err) }
108
+ // Windows 上 .bat 不能由 spawn 直接执行(EINVAL),必须经 cmd.exe /c。
109
+ const isWindows = process.platform === "win32"
110
+ const cmd = isWindows ? "cmd.exe" : bin
111
+ const args = isWindows ? ["/c", bin, "--output-format", "json", "--model", model]
112
+ : ["--output-format", "json", "--model", model]
113
+ const child = spawn(cmd, args, {
114
+ cwd: process.cwd(),
115
+ windowsHide: true,
116
+ stdio: [fd, "pipe", "pipe"],
117
+ })
118
+ closeSync(fd)
119
+ // 必须累积 Buffer:中文 Windows 上 CLI stdout 是 GBK 字节,
120
+ // 若用 `stdout += c`(Buffer 隐式 toString/utf8)会在这一步就破坏原始字节。
121
+ const outChunks = [], errChunks = []
122
+ let done = false
123
+ const timer = setTimeout(() => child.kill(), timeoutMs)
124
+ const finish = (err, value) => {
125
+ if (done) return
126
+ done = true
127
+ clearTimeout(timer)
128
+ rmSync(dir, { recursive: true, force: true })
129
+ err ? reject(err) : resolve(value)
130
+ }
131
+ child.stdout?.on("data", (c) => outChunks.push(c))
132
+ child.stderr?.on("data", (c) => errChunks.push(c))
133
+ child.on("error", (err) => finish(err))
134
+ child.on("close", (code) => {
135
+ try {
136
+ const stdoutBuf = Buffer.concat(outChunks)
137
+ const obj = parseCliOutput(stdoutBuf)
138
+ if (!obj) return finish(new Error(`CLI exited ${code} without JSON: ${decodeCliStdout(stdoutBuf || Buffer.concat(errChunks)).slice(0, 400)}`))
139
+ finish(null, {
140
+ code,
141
+ obj,
142
+ result: obj.result ?? "",
143
+ errors: obj.errors ?? [],
144
+ llmUsage: obj.llmUsage ?? [],
145
+ sessionId: obj.sessionId ?? "",
146
+ })
147
+ } catch (err) { finish(err) }
148
+ })
149
+ })
150
+ }
151
+
152
+ /**
153
+ * Junie CLI 作为 coding agent,会在答案后固定附一段模板:
154
+ * ### Changes\n- ...\n\n### Verification\n- ... (有时还有 ### Notes)
155
+ * 对纯对话场景这些是噪音,从第一个已知段落标题起截断。
156
+ * 只匹配已知标题,避免用户正文里出现 "### " 时被误伤。
157
+ */
158
+ const AGENT_SECTIONS = ["Changes", "Verification", "Notes"]
159
+
160
+ export function cleanResult(result) {
161
+ if (typeof result !== "string") return ""
162
+ let cut = result.length
163
+ for (const title of AGENT_SECTIONS) {
164
+ // 支持标题在开头(^)或换行后(\n);CLI 偶尔让模板段落在 result 最前面。
165
+ const re = new RegExp(`(?:^|\\n)#{1,3}\\s*${title}\\b`, "i")
166
+ const m = re.exec(result)
167
+ if (m && m.index < cut) cut = m.index
168
+ }
169
+ return result.slice(0, cut).trim()
170
+ }
171
+
172
+ /** CLI llmUsage 数组 → OpenAI usage(缓存输入计入 prompt_tokens)。 */
173
+ export function usageFromLlmUsage(llmUsage) {
174
+ let input = 0, output = 0, cacheRead = 0, cacheWrite = 0
175
+ for (const u of (Array.isArray(llmUsage) ? llmUsage : [])) {
176
+ input += Number(u?.inputTokens) || 0
177
+ output += Number(u?.outputTokens) || 0
178
+ cacheRead += Number(u?.cacheInputTokens) || 0
179
+ cacheWrite += Number(u?.cacheCreateTokens) || 0
180
+ }
181
+ const prompt = input + cacheRead + cacheWrite
182
+ return {
183
+ prompt_tokens: prompt,
184
+ completion_tokens: output,
185
+ total_tokens: prompt + output,
186
+ prompt_tokens_details: { cached_tokens: cacheRead, cache_write_tokens: cacheWrite },
187
+ }
188
+ }
189
+
190
+ /** OpenAI chat completion 响应体 */
191
+ export function completionBody(result, model, usage) {
192
+ return {
193
+ id: `chatcmpl-${Date.now()}`,
194
+ object: "chat.completion",
195
+ created: Math.floor(Date.now() / 1000),
196
+ model,
197
+ choices: [{
198
+ index: 0,
199
+ message: { role: "assistant", content: result },
200
+ finish_reason: "stop",
201
+ }],
202
+ usage: usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
203
+ }
204
+ }
205
+
206
+ /** SSE 流式:CLI 不支持增量,把 result 切成块发出。usage 放最后一个 chunk。 */
207
+ export function streamChunks(result, model, usage) {
208
+ const id = `chatcmpl-${Date.now()}`
209
+ const created = Math.floor(Date.now() / 1000)
210
+ const chunk = (delta, finish_reason = null, extra = {}) =>
211
+ `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason }], ...extra })}\n\n`
212
+ const out = [chunk({ role: "assistant" })]
213
+ for (let i = 0; i < result.length; i += 64) out.push(chunk({ content: result.slice(i, i + 64) }))
214
+ out.push(chunk({}, "stop"))
215
+ out.push(chunk({}, null, { usage: usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 } }))
216
+ out.push("data: [DONE]\n\n")
217
+ return out.join("")
218
+ }
219
+
220
+ export const modelsResponse = () => ({
221
+ object: "list",
222
+ data: [MODEL, "junie-lite"].filter((v, i, a) => a.indexOf(v) === i)
223
+ .map((id) => ({ id, object: "model", created: 0, owned_by: "junie-cli" })),
224
+ })
225
+
226
+ export function createBridgeServer() {
227
+ return createServer(async (req, res) => {
228
+ try {
229
+ const url = new URL(req.url ?? "/", `http://${HOST}:${PORT}`)
230
+ if (url.pathname === "/v1/models" || url.pathname === "/models") {
231
+ res.writeHead(200, { "Content-Type": "application/json" })
232
+ res.end(JSON.stringify(modelsResponse()))
233
+ return
234
+ }
235
+ if ((url.pathname === "/v1/chat/completions" || url.pathname === "/chat/completions") && req.method === "POST") {
236
+ const chunks = []
237
+ for await (const c of req) chunks.push(c)
238
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"))
239
+ // 每次对话前按需检查版本(6h 节流),确保 CLI 不被上游版本门槛卡住。
240
+ await maybeUpdate()
241
+ const prompt = messagesToPrompt(body.messages)
242
+ const { result, errors, llmUsage } = await callJunie(prompt, { model: body.model && body.model !== "junie-lite" ? MODEL : MODEL })
243
+ if (errors.length) {
244
+ res.writeHead(400, { "Content-Type": "application/json" })
245
+ res.end(JSON.stringify({ error: { message: errors.join("; "), type: "junie_error" } }))
246
+ return
247
+ }
248
+ const replyModel = body.model ?? MODEL
249
+ const answer = cleanResult(result)
250
+ const usage = usageFromLlmUsage(llmUsage)
251
+ if (body.stream) {
252
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" })
253
+ res.end(streamChunks(answer, replyModel, usage))
254
+ } else {
255
+ res.writeHead(200, { "Content-Type": "application/json" })
256
+ res.end(JSON.stringify(completionBody(answer, replyModel, usage)))
257
+ }
258
+ return
259
+ }
260
+ if (url.pathname === "/health") {
261
+ res.writeHead(200, { "Content-Type": "application/json" })
262
+ res.end(JSON.stringify({
263
+ ok: true,
264
+ model: MODEL,
265
+ bin: JUNIE,
266
+ autoUpdate: AUTO_UPDATE,
267
+ lastUpdate: lastUpdateInfo && {
268
+ checked: lastUpdateInfo.checked,
269
+ updated: lastUpdateInfo.updated,
270
+ version: lastUpdateInfo.version,
271
+ reason: lastUpdateInfo.reason,
272
+ },
273
+ }))
274
+ return
275
+ }
276
+ res.writeHead(404)
277
+ res.end()
278
+ } catch (err) {
279
+ res.writeHead(500, { "Content-Type": "application/json" })
280
+ res.end(JSON.stringify({ error: { message: String(err?.message ?? err), type: "server_error" } }))
281
+ }
282
+ })
283
+ }
284
+
285
+ // 直接运行时启动服务(ESM 入口检测;用 pathToFileURL 兼容 macOS/Linux 绝对路径)
286
+ import { pathToFileURL } from "node:url"
287
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
288
+ const server = createBridgeServer()
289
+ server.listen(PORT, HOST, () => {
290
+ console.log(`junie-openai bridge listening on http://${HOST}:${PORT}/v1 (model=${MODEL})`)
291
+ maybeUpdate() // 启动后后台检查一次(6h 节流),不阻塞服务可用
292
+ })
293
+ }
package/icon.svg ADDED
@@ -0,0 +1,17 @@
1
+ <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <g clip-path="url(#clip0_2506_1549)">
3
+ <g clip-path="url(#clip1_2506_1549)">
4
+ <path d="M21 11.0001L31 11V12.6638C31 24.3042 25.9621 31 12.6638 31H11V21H12.6638C18.4811 21 21 18.4749 21 12.6576V11.0001Z" fill="#48E054"/>
5
+ <path d="M11 11H1V21H11V11Z" fill="#48E054"/>
6
+ <path d="M21 1H11V11H21V1Z" fill="#48E054"/>
7
+ </g>
8
+ </g>
9
+ <defs>
10
+ <clipPath id="clip0_2506_1549">
11
+ <rect width="32" height="32" fill="white"/>
12
+ </clipPath>
13
+ <clipPath id="clip1_2506_1549">
14
+ <rect width="32" height="32" fill="white"/>
15
+ </clipPath>
16
+ </defs>
17
+ </svg>
package/index.mjs ADDED
@@ -0,0 +1,171 @@
1
+ // magpie-junie:把 JetBrains Junie 接入 magpie 供应商 `junie`。
2
+ //
3
+ // 三种登录方式(按优先级):
4
+ // 1. 导入本机 CLI 登录态(~/.junie/dpapi_credentials,DPAPI 解密)——最快,不用浏览器
5
+ // 2. 浏览器 PKCE(Junie CLI 同款)——没有本地 CLI 时用
6
+ // 3. API key(perm-*,从 junie.jetbrains.com/cli 获取)——兜底
7
+ //
8
+ // 请求链路(两种,由 options.bridgeUrl 选择):
9
+ // A. 直连上游:loader.fetch 把标准请求发到 ingrazzio-cloud-prod.labs.jb.gg
10
+ // (见 lib/fetch.mjs)。需代理,且账号要有有效订阅;license=NONE 会被 403。
11
+ // B. 本地桥接(推荐给 free tier):options.bridgeUrl 指向 bridge-server.mjs,
12
+ // 后端调 CLI headless 的 junie-lite 通道(见 bridge-server.mjs)。
13
+ //
14
+ // 注意:上游对中国 IP 直连返回 403,需宿主/Node 开启代理(NODE_USE_ENV_PROXY=1)。
15
+
16
+ import { PROVIDER, DISPLAY_NAME } from "./lib/constants.mjs"
17
+ import { MODELS, configModels } from "./lib/models.mjs"
18
+ import { readCliCredentials } from "./lib/credentials.mjs"
19
+ import { startPkceLogin, refreshAccessToken } from "./lib/auth.mjs"
20
+ import { makeFetch } from "./lib/fetch.mjs"
21
+ import { makeDirectFetch, DIRECT_MODEL } from "./lib/direct.mjs"
22
+ import { usageHook } from "./lib/usage.mjs"
23
+ import { proxyFetch } from "./lib/proxy.mjs"
24
+
25
+ const MAX_CONCURRENCY = 2
26
+
27
+ /** 把 CLI 凭据或 PKCE 结果规范化成 magpie 的 success 结果。 */
28
+ function success(auth) {
29
+ return { type: "success", ...auth }
30
+ }
31
+
32
+ export async function JuniePlugin(input, options = {}) {
33
+ // plugins.json 里该插件项的 options,闭包捕获,所有 hook 共用。
34
+ const pluginOptions = options ?? {}
35
+ return {
36
+ config: async (cfg = {}) => {
37
+ cfg.provider ??= {}
38
+ // 直连和桥接都只暴露 junie-lite(底层 gpt-6-luna,免费额度)。
39
+ // 直连用 Responses 协议;桥接转发给本地 CLI。
40
+ const opts = pluginOptions
41
+ const models = {
42
+ "junie-lite": { name: "Junie Lite (GPT-6 Luna)", limit: { context: 262144, output: 16384 }, tool_call: true },
43
+ }
44
+ cfg.provider[PROVIDER] ??= {
45
+ name: DISPLAY_NAME,
46
+ npm: "@ai-sdk/openai-compatible", // chat completions
47
+ api: opts.bridgeUrl ?? "https://ingrazzio-cloud-prod.labs.jb.gg/v1",
48
+ models,
49
+ }
50
+ },
51
+
52
+ auth: {
53
+ provider: PROVIDER,
54
+ maxConcurrency: MAX_CONCURRENCY,
55
+ refreshLead: 90_000,
56
+
57
+ methods: [
58
+ {
59
+ // 用 oauth 而非 api:api 方法在 magpie 里只存 {type,key,metadata},
60
+ // 丢掉 refresh/expires,导致无法自动续期、多账号里一个过期就卡住。
61
+ // oauth 走 plugin.Finish,完整保存 auth 对象。
62
+ type: "oauth",
63
+ label: "从本机 Junie CLI 导入登录态",
64
+ async authorize() {
65
+ // 本地读凭据,无需浏览器;callback 直接给出结果。
66
+ return {
67
+ url: "",
68
+ instructions: "从本机 Junie CLI 读取登录态。",
69
+ method: "auto",
70
+ callback: async () => {
71
+ const r = await readCliCredentials()
72
+ if (!r.ok) return { type: "failed", error: `未找到可用的 Junie CLI 登录态(${r.reason})。` }
73
+ return {
74
+ type: "success",
75
+ key: r.auth.access,
76
+ access: r.auth.access,
77
+ accessToken: r.auth.accessToken,
78
+ idToken: r.auth.idToken,
79
+ refresh: r.auth.refresh,
80
+ expires: r.auth.expires,
81
+ accountId: r.auth.accountId,
82
+ metadata: {
83
+ ...(r.auth.metadata ?? {}),
84
+ email: r.auth.email ?? r.auth.accountId,
85
+ cliAuth: r.auth,
86
+ },
87
+ }
88
+ },
89
+ }
90
+ },
91
+ },
92
+ {
93
+ type: "oauth",
94
+ label: "浏览器登录(JetBrains 账号)",
95
+ async authorize() {
96
+ try {
97
+ const r = await startPkceLogin()
98
+ return {
99
+ url: r.url,
100
+ instructions: r.instructions,
101
+ method: r.method,
102
+ callback: r.callback,
103
+ }
104
+ } catch (err) {
105
+ return { type: "failed", error: `无法开始登录:${String(err?.message ?? err).slice(0, 500)}` }
106
+ }
107
+ },
108
+ },
109
+ {
110
+ type: "api",
111
+ label: "Junie API key (perm-*)",
112
+ placeholder: "perm-…",
113
+ },
114
+ ],
115
+
116
+ async loader(getAuth, provider) {
117
+ const auth = await getAuth().catch(() => null)
118
+ // options 来自 plugins.json 的该项;magpie 也可能把它挂在 provider.options 上。
119
+ const options = { ...pluginOptions, ...(provider?.options ?? {}) }
120
+ if (options.bridgeUrl) {
121
+ // 本地桥接模式:后端是 CLI headless,它自己持有 Junie 登录态,
122
+ // 所以这里**不要求 magpie 侧登录**,任何账号状态都能转发。
123
+ const base = String(options.bridgeUrl).replace(/\/+$/, "")
124
+ return {
125
+ baseURL: base,
126
+ apiKey: "local",
127
+ fetch: (input, init) => {
128
+ const u = new URL(String(input))
129
+ const target = new URL(base)
130
+ u.protocol = target.protocol
131
+ u.host = target.host
132
+ return proxyFetch(u.toString(), init, { proxy: false })
133
+ },
134
+ }
135
+ }
136
+ // 直连模式:用逆向的 Responses 协议(免费额度可用,无需 CLI 本体)。
137
+ return {
138
+ baseURL: "https://ingrazzio-cloud-prod.labs.jb.gg/v1",
139
+ apiKey: auth.access ?? auth.key,
140
+ fetch: makeDirectFetch(auth, options),
141
+ }
142
+ },
143
+
144
+ async refresh(auth) {
145
+ return refreshAccessToken(auth)
146
+ },
147
+
148
+ async usage(getAuth) {
149
+ return usageHook(getAuth)
150
+ },
151
+ },
152
+
153
+ provider: {
154
+ id: PROVIDER,
155
+ async models(providerModels, { auth } = {}) {
156
+ if (pluginOptions.bridgeUrl) {
157
+ return { "junie-lite": { name: "Junie Lite (CLI)", limit: { context: 262144, output: 16384 }, tool_call: true } }
158
+ }
159
+ // 直连/桥接都只提供 junie-lite(底层 gpt-6-luna),与其他旧模型无关。
160
+ return {
161
+ "junie-lite": { name: "Junie Lite (GPT-6 Luna)", limit: { context: 262144, output: 16384 }, tool_call: true },
162
+ }
163
+ },
164
+ },
165
+ }
166
+ }
167
+
168
+ // 入口纪律:只导出插件函数 + default;辅助函数放 lib/ 和 _internal。
169
+ export const _internal = { MODELS, configModels, readCliCredentials, startPkceLogin, makeFetch, usageHook }
170
+
171
+ export default { id: PROVIDER, server: JuniePlugin }
package/junie-logo.png ADDED
Binary file