magpie-plugin-loomy-auth 0.1.26 → 0.1.36
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/AGENTS.md +11 -1
- package/CHANGELOG.md +75 -0
- package/CHECKLIST.md +11 -5
- package/README.md +61 -97
- package/docs/internals.md +140 -374
- package/docs/security.md +67 -0
- package/index.mjs +31 -78
- package/package.json +2 -2
- package/src/api.mjs +44 -0
- package/src/chat.mjs +43 -8
- package/src/constants.mjs +18 -2
- package/src/hardening.mjs +59 -0
- package/src/invite-store.mjs +141 -0
- package/src/models.mjs +63 -19
- package/src/prompt.mjs +69 -0
- package/src/team-mode.mjs +70 -0
- package/src/team.mjs +74 -0
- package/src/tracing.mjs +113 -0
- package/src/usage.mjs +15 -3
- package/src/desktop.mjs +0 -173
package/src/models.mjs
CHANGED
|
@@ -1,19 +1,44 @@
|
|
|
1
1
|
// Loomy · 模型目录(静态兜底表 + 实测拉取)
|
|
2
2
|
//
|
|
3
|
-
// ⚠
|
|
3
|
+
// ⚠ 静态表里的数字**全部来自实测**(`GET /api/v1/models`,2026-10-26;
|
|
4
|
+
// DeepSeek dated 条目复核于 2026-11-15;倍率与「哪些还在目录里」复核于 2026-11-20),
|
|
4
5
|
// 不是照抄文档,也不是「看起来差不多」:
|
|
5
6
|
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
7
|
+
// ⚠ 2026-11-20 上游目录变化(实测):Spark-X2.6 从「限时免费 x0.0」变成 **x2.5 收费**,
|
|
8
|
+
// 并且成了上游的默认模型(`is_default_model` / `is_default_small_model`);
|
|
9
|
+
// 目录里不再列出 `spark-x` / `MiniMax-M3` / `Kimi-k2.6` / `qwen-3.8-max` / `mimo-v2.5`
|
|
10
|
+
// —— 但它们**仍可调用**(同一天实测逐个 200),所以静态表继续保留,只在兜底时出现。
|
|
11
|
+
// 目录当前列出的对话模型只有 5 个:spark-x2.6 / DeepSeek 两条 / GLM-5.3-Flash /
|
|
12
|
+
// qwen3.8-flash / auto(其中 DeepSeek 只保留 dated 一条,见下)。
|
|
13
|
+
//
|
|
14
|
+
// id context output efforts reason vision tools
|
|
15
|
+
// spark-x2.6 1048576 131072 none|low|medium|high|xhigh ✓ ✗ ✓
|
|
16
|
+
// spark-x 1048576 65536 同上 ✓ ✗ ✓
|
|
17
|
+
// deepseek-v4-flash-1017 1048576 384000 同上 ✓ ✓ ✓
|
|
18
|
+
// MiniMax-M3 1048576 512000 同上 ✓ ✓ ✓
|
|
19
|
+
// Kimi-k2.6 262144 65536 同上 ✓ ✓ ✓
|
|
20
|
+
// qwen-3.8-max 1000000 65536 同上 ✓ ✗ ✓
|
|
21
|
+
// GLM-5.3-Flash 1048576 131072 同上 ✓ ✓ ✓
|
|
22
|
+
// qwen3.8-flash 1000000 131072 同上 ✓ ✓ ✓
|
|
23
|
+
// mimo-v2.5 1048576 131072 同上 ✓ ✓ ✓
|
|
24
|
+
// auto — — 无 thinking_config ✗ ✗ ✗
|
|
25
|
+
//
|
|
26
|
+
// ⚠ DeepSeek 的 id 是 **dated** 的 `deepseek-v4-flash-1017`,不是裸名。
|
|
27
|
+
// 2026-11-15 实测 `GET /api/v1/models` 同时下发两条 DeepSeek 对话条目(其余字段一致):
|
|
28
|
+
//
|
|
29
|
+
// id name created
|
|
30
|
+
// DeepSeek-V4.1-Flash DeepSeek V4.1 Flash(x2.0) 2026-09-14T09:49:05Z ← 裸名/未固定 ID
|
|
31
|
+
// deepseek-v4-flash-1017 DeepSeek V4.1 Flash 1017(x2.0) 2026-10-20T09:19:19Z ← dated 固定版
|
|
32
|
+
//
|
|
33
|
+
// 两条的 context/output/视觉/工具/倍率完全一样(1,048,576 / 384,000 / ✓ / ✓ / x2.0),
|
|
34
|
+
// 差异在于 ID 是否带快照日期。**选 dated 的原因**:裸名不含快照日期,上游可以重新
|
|
35
|
+
// 指向其它快照,不适合用来承诺固定版本;dated ID 明确请求 1017,而本插件把 `api.id`
|
|
36
|
+
// 原样出站、不改写 `body.model`,因此静态与实时目录都只提供这一条 DeepSeek。
|
|
37
|
+
//
|
|
38
|
+
// ⇒ **未固定裸名可能落到旧快照,不作为选项**:静态表只留 dated,
|
|
39
|
+
// `liveModels` 遍历实时目录时显式跳过裸名(实时目录仍在同时下发它,不挡掉菜单里
|
|
40
|
+
// 就会多出一个会漂移的选项)。`parseModels` 保持通用解析,不在此层过滤 ——
|
|
41
|
+
// 历史单测直接喂裸名行,仍按原样解析。
|
|
17
42
|
//
|
|
18
43
|
// ⚠ `context` 必须原样上报,不要「保守填小」:magpie 把它转给 agent 决定何时
|
|
19
44
|
// 压缩对话,而**路由组按组内最大算窗口** —— 一个填小的成员会把整组拉低。
|
|
@@ -33,11 +58,24 @@ const { splitRateSuffix, isFreeModel, modelShape, parseModels } = _pure
|
|
|
33
58
|
|
|
34
59
|
const API_URL = `${INTEGRATION_BASE}/api/v1`
|
|
35
60
|
|
|
61
|
+
/**
|
|
62
|
+
* 上游 DeepSeek 的**裸名(未固定 ID)**:不固定快照,同一个 id 随时可能被上游指到
|
|
63
|
+
* 其它 dated 快照。**未固定裸名可能落到旧快照,不作为选项** ——
|
|
64
|
+
* 静态表只收录 dated(见 `DEEPSEEK_DATED_ID`),`liveModels` 遍历实时目录时跳过它。
|
|
65
|
+
*/
|
|
66
|
+
const DEEPSEEK_ALIAS_ID = "DeepSeek-V4.1-Flash"
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 要固定给用户的 DeepSeek 选项:上游的 dated id,快照写在名字里。
|
|
70
|
+
* 除 id/展示名外与裸名条目完全一致(1M 上下文 / 384,000 输出 / 视觉 / 工具 / x2.0)。
|
|
71
|
+
*/
|
|
72
|
+
const DEEPSEEK_DATED_ID = "deepseek-v4-flash-1017"
|
|
73
|
+
|
|
36
74
|
/** 实测快照:[id, 展示名, context, output, 有无视觉, 有无工具],efforts 统一为上游那 5 档 */
|
|
37
75
|
const SNAPSHOT = [
|
|
38
|
-
["spark-x2.6", "Spark-X2.6 正式版
|
|
76
|
+
["spark-x2.6", "Spark-X2.6 正式版", 1_048_576, 131_072, false, true],
|
|
39
77
|
["spark-x", "Spark-X2.5(限时免费)", 1_048_576, 65_536, false, true],
|
|
40
|
-
[
|
|
78
|
+
[DEEPSEEK_DATED_ID, "DeepSeek V4.1 Flash 1017", 1_048_576, 384_000, true, true],
|
|
41
79
|
["MiniMax-M3", "MiniMax M3", 1_048_576, 512_000, true, true],
|
|
42
80
|
["Kimi-k2.6", "Kimi k2.6", 262_144, 65_536, true, true],
|
|
43
81
|
["qwen-3.8-max", "Qwen 3.8 Max", 1_000_000, 65_536, false, true],
|
|
@@ -49,16 +87,19 @@ const SNAPSHOT = [
|
|
|
49
87
|
const EFFORTS = ["none", "low", "medium", "high", "xhigh"]
|
|
50
88
|
|
|
51
89
|
/**
|
|
52
|
-
*
|
|
90
|
+
* 实测倍率(取自上游展示名尾部;2026-10-26 首测,2026-11-20 复核)。
|
|
53
91
|
*
|
|
54
92
|
* ⚠ 这个表**只用于静态兜底**;活目录走 `parseModels`,倍率从上游直接解析。
|
|
55
|
-
*
|
|
56
|
-
* `
|
|
93
|
+
*
|
|
94
|
+
* ⚠ **2026-11-20 起 Spark-X2.6 不再免费**:展示名从 `(限时免费)(x0.0)` 变成 `(x2.5)`,
|
|
95
|
+
* 而且它成了上游的默认模型。这里必须跟着改 —— 静态表若还标 `free: true`,
|
|
96
|
+
* magpie 的 Free-first 路由会把它当成零成本优先派发,用户以为免费却在烧积分。
|
|
97
|
+
* 现在只有 `spark-x` 仍是 `x0.0`。
|
|
57
98
|
*/
|
|
58
99
|
const RATE_HINT = {
|
|
59
|
-
"spark-x2.6": "(
|
|
100
|
+
"spark-x2.6": "(x2.5)",
|
|
60
101
|
"spark-x": "(x0.0)",
|
|
61
|
-
|
|
102
|
+
[DEEPSEEK_DATED_ID]: "(x2.0)",
|
|
62
103
|
"MiniMax-M3": "(x4.0)",
|
|
63
104
|
"Kimi-k2.6": "(x6.5)",
|
|
64
105
|
"qwen-3.8-max": "(x12.0)",
|
|
@@ -109,6 +150,9 @@ export async function liveModels(session, fallback, fetcher = fetch) {
|
|
|
109
150
|
if (!rows.length) return fallback
|
|
110
151
|
const out = {}
|
|
111
152
|
for (const row of rows) {
|
|
153
|
+
// 实时目录仍在同时下发裸名 `DeepSeek-V4.1-Flash`。**未固定裸名可能落到旧快照,
|
|
154
|
+
// 不作为选项** —— 只留 dated(它自己会作为一行被收进来),别让菜单里多出一个会漂移的 id。
|
|
155
|
+
if (row.id === DEEPSEEK_ALIAS_ID) continue
|
|
112
156
|
const base = fallback[row.id]
|
|
113
157
|
out[row.id] = modelShape(row, {
|
|
114
158
|
api: { url: API_URL, npm: NPM },
|
package/src/prompt.mjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// 官方「灵魂提示词」剥离。
|
|
2
|
+
//
|
|
3
|
+
// 事实(见 docs/internals.md §3):官方那套人格提示词写在客户端的
|
|
4
|
+
// `opencode-home-template/opencode.json` 的 `agent.<id>.prompt` 里,**由客户端本地注入**;
|
|
5
|
+
// 服务端不注入(实测带 SENTINEL 的 system 被尊重,裸请求自我认同为讯飞星火)。
|
|
6
|
+
// 所以本插件默认**什么都不加**。
|
|
7
|
+
//
|
|
8
|
+
// 这个模块只防一种情况:有人把客户端那整段 soul prompt 抄进请求里发过来。
|
|
9
|
+
// 那时模型会变成「Loomy 办公助手」口吻,破坏「原生 API Key 体验」。
|
|
10
|
+
//
|
|
11
|
+
// ⚠ 性能:聊天体积可以到几 MB,所以**先用一次 IndexOf 快速判否**,
|
|
12
|
+
// 命中才 JSON 解析。绝大多数请求只多一次子串查找。
|
|
13
|
+
|
|
14
|
+
/** 官方 soul prompt 的特征串(逐字取自 opencode-home-template/opencode.json)。 */
|
|
15
|
+
const MARKERS = [
|
|
16
|
+
"你是 Loomy,一位温柔细心、靠谱稳重的智能办公助手",
|
|
17
|
+
"Loomy 办公助手 - 帮助用户完成各种办公任务",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
/** 至少命中两个特征才认定为「官方 soul prompt」,避免用户聊到这句话时被误删。 */
|
|
21
|
+
const MIN_HITS = 2
|
|
22
|
+
|
|
23
|
+
function hits(text) {
|
|
24
|
+
let n = 0
|
|
25
|
+
for (const marker of MARKERS) if (text.includes(marker)) n += 1
|
|
26
|
+
return n
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function contentText(content) {
|
|
30
|
+
if (typeof content === "string") return content
|
|
31
|
+
if (Array.isArray(content)) {
|
|
32
|
+
return content
|
|
33
|
+
.map((block) => (block && block.type === "text" && typeof block.text === "string" ? block.text : ""))
|
|
34
|
+
.join("\n")
|
|
35
|
+
}
|
|
36
|
+
return ""
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 从请求体里剥掉官方 soul prompt。
|
|
41
|
+
*
|
|
42
|
+
* @param {string} bodyText 原始请求体(JSON 文本)
|
|
43
|
+
* @returns {{ body: string, removed: number } | null} 没命中返回 `null`(调用方原样转发)
|
|
44
|
+
*/
|
|
45
|
+
export function stripOfficialSoulPrompt(bodyText) {
|
|
46
|
+
if (typeof bodyText !== "string" || !bodyText) return null
|
|
47
|
+
// 快路径:一次子串查找就能判否
|
|
48
|
+
if (!MARKERS.some((marker) => bodyText.includes(marker))) return null
|
|
49
|
+
|
|
50
|
+
let payload
|
|
51
|
+
try {
|
|
52
|
+
payload = JSON.parse(bodyText)
|
|
53
|
+
} catch {
|
|
54
|
+
return null // 不是 JSON 就不是我们能安全改的东西
|
|
55
|
+
}
|
|
56
|
+
const messages = payload?.messages
|
|
57
|
+
if (!Array.isArray(messages)) return null
|
|
58
|
+
|
|
59
|
+
const kept = messages.filter((message) => {
|
|
60
|
+
const role = message?.role
|
|
61
|
+
if (role !== "system" && role !== "developer") return true
|
|
62
|
+
return hits(contentText(message?.content)) < MIN_HITS
|
|
63
|
+
})
|
|
64
|
+
const removed = messages.length - kept.length
|
|
65
|
+
if (!removed) return null
|
|
66
|
+
return { body: JSON.stringify({ ...payload, messages: kept }), removed }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export const _internal = { MARKERS, MIN_HITS }
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// 布尔值仅是宿主的存储形式;用户选择的是个人 / 团队。
|
|
2
|
+
import { createHash } from "node:crypto"
|
|
3
|
+
import { fetchTeamContext, setCurrentTeam } from "./api.mjs"
|
|
4
|
+
|
|
5
|
+
const currentId = (data) => typeof data?.currentTeamId === "string" ? data.currentTeamId.trim() : ""
|
|
6
|
+
const joined = (data) => Array.isArray(data?.teams)
|
|
7
|
+
? data.teams.filter(t => t?.status === "active" && typeof t.teamId === "string" && t.teamId.trim())
|
|
8
|
+
: []
|
|
9
|
+
|
|
10
|
+
export function createTeamModeController({ readOption }) {
|
|
11
|
+
const accounts = new Map(), inFlight = new Map()
|
|
12
|
+
function options() {
|
|
13
|
+
const account = [...accounts.values()].find(a => a.teams.length)
|
|
14
|
+
if (!account) return []
|
|
15
|
+
return [{
|
|
16
|
+
key: "team_mode", label: "积分账户", offLabel: "个人", onLabel: "团队",
|
|
17
|
+
labels: { en: "Credit account", "zh-TW": "積分帳戶", ja: "ポイントアカウント", de: "Guthabenkonto" },
|
|
18
|
+
offLabels: { en: "Personal", "zh-TW": "個人", ja: "個人", de: "Persönlich" },
|
|
19
|
+
onLabels: { en: "Team", "zh-TW": "團隊", ja: "チーム", de: "Team" },
|
|
20
|
+
default: !!account.current, placement: "accounts", immediate: true,
|
|
21
|
+
}]
|
|
22
|
+
}
|
|
23
|
+
async function apply(credential, key, fetcher) {
|
|
24
|
+
const previous = accounts.get(key)
|
|
25
|
+
const data = await fetchTeamContext(credential.session, fetcher)
|
|
26
|
+
const teams = joined(data), current = currentId(data)
|
|
27
|
+
const target = teams.find(t => t.teamId === current)?.teamId
|
|
28
|
+
?? teams.find(t => t.teamId === previous?.target)?.teamId
|
|
29
|
+
?? teams[0]?.teamId
|
|
30
|
+
let changed = !!previous && previous.current !== current
|
|
31
|
+
if (!teams.length) {
|
|
32
|
+
accounts.set(key, { teams, current, target, optionOn: !!current })
|
|
33
|
+
return changed
|
|
34
|
+
}
|
|
35
|
+
// ⚠ 第一次观察只记录、绝不下发切换。
|
|
36
|
+
// 宿主是「先声明开关、再重拉模型」的顺序,而 `options()` 在第一次 sync 之前是空的:
|
|
37
|
+
// 此刻向宿主读这个键,拿到的只会是「未声明 ⇒ 缺省 false」。
|
|
38
|
+
// 拿它当用户意图,就会把本来在团队里的账号静默切到个人(实测调用序:
|
|
39
|
+
// GET identity → POST current-team {} → GET identity)。
|
|
40
|
+
// 首次只把「开关 = 服务端当前身份」记下来,和 `options()` 里 default 的定义保持一致;
|
|
41
|
+
// 之后只有在宿主读数与上次记录不同(= 用户真的拨了开关)时才写服务端。
|
|
42
|
+
const optionOn = previous ? readOption() === true : !!current
|
|
43
|
+
if (!previous || previous.optionOn === optionOn) {
|
|
44
|
+
accounts.set(key, { teams, current, target, optionOn })
|
|
45
|
+
return changed
|
|
46
|
+
}
|
|
47
|
+
const desired = optionOn ? target : ""
|
|
48
|
+
if (current === desired) {
|
|
49
|
+
accounts.set(key, { teams, current, target, optionOn })
|
|
50
|
+
return changed
|
|
51
|
+
}
|
|
52
|
+
await setCurrentTeam(credential.session, desired, fetcher)
|
|
53
|
+
const verified = await fetchTeamContext(credential.session, fetcher)
|
|
54
|
+
// 失败时不落 optionOn:宿主读数仍是新值,下一次 sync 会重试。
|
|
55
|
+
if (currentId(verified) !== desired) throw new Error("积分账户切换未生效,请重试")
|
|
56
|
+
accounts.set(key, { teams: joined(verified), current: desired, target, optionOn })
|
|
57
|
+
return true
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
options,
|
|
61
|
+
async sync(credential, fetcher = fetch) {
|
|
62
|
+
const key = createHash("sha256").update(credential.uid || credential.session).digest("hex")
|
|
63
|
+
const pending = (inFlight.get(key) ?? Promise.resolve()).catch(() => {}).then(() => apply(credential, key, fetcher))
|
|
64
|
+
inFlight.set(key, pending)
|
|
65
|
+
try { return await pending } finally {
|
|
66
|
+
if (inFlight.get(key) === pending) inFlight.delete(key)
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
}
|
package/src/team.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// 团队积分:共享余额和当前成员的每日限额是两项独立约束。
|
|
2
|
+
// 个人钱包即使有分,也不能当作当前团队的可用额度。
|
|
3
|
+
|
|
4
|
+
import { fetchTeamIdentity, fetchTeamBalances } from "./api.mjs"
|
|
5
|
+
import { _pure } from "./pure.mjs"
|
|
6
|
+
|
|
7
|
+
const { beijingCycleDate, beijingResetAt } = _pure
|
|
8
|
+
|
|
9
|
+
/** 缺字段不是 0;尤其不能把 null / 空串当成「团队已耗尽」。 */
|
|
10
|
+
function points(value) {
|
|
11
|
+
if (typeof value !== "number" && (typeof value !== "string" || !value.trim())) return undefined
|
|
12
|
+
const n = Number(value)
|
|
13
|
+
return Number.isFinite(n) && n >= 0 ? n : undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function dailyTextWindow(display) {
|
|
17
|
+
return { name: "团队每日额度", used: 0, aside: true, display, unit: "积分" }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 返回 null 才表示服务端当前处于个人模式;查询失败交给 usage 如实报错。 */
|
|
21
|
+
export async function readTeamUsage(credential, now, fetcher) {
|
|
22
|
+
const identity = await fetchTeamIdentity(credential.session, fetcher)
|
|
23
|
+
if (!identity) return null
|
|
24
|
+
const data = await fetchTeamBalances(credential.session, fetcher)
|
|
25
|
+
// 两次 GET 之间用户可能在客户端切了团队,不把另一团队的余额贴到旧名字上。
|
|
26
|
+
if (data.teamId !== identity.id) throw new Error("团队已切换或读数不一致,请刷新积分")
|
|
27
|
+
const balance = points(data.currentBalance)
|
|
28
|
+
if (balance === undefined) throw new Error("团队积分读数异常(上游没有返回有效的 currentBalance)")
|
|
29
|
+
if (typeof data.dailyLimitEnabled !== "boolean") throw new Error("团队每日额度读数异常(缺少 dailyLimitEnabled)")
|
|
30
|
+
|
|
31
|
+
const limit = points(data.dailyLimitPoints)
|
|
32
|
+
const consumed = points(data.dailyConsumedPoints)
|
|
33
|
+
const remaining = points(data.dailyRemainingPoints)
|
|
34
|
+
const currentCycle = data.dailyLimitTimezone === "Asia/Shanghai" && data.dailyLimitCycleDate === beijingCycleDate(now)
|
|
35
|
+
const known = currentCycle && limit !== undefined && consumed !== undefined && remaining !== undefined
|
|
36
|
+
const windows = []
|
|
37
|
+
|
|
38
|
+
if (!data.dailyLimitEnabled) {
|
|
39
|
+
windows.push(dailyTextWindow("未设置每日上限"))
|
|
40
|
+
} else if (known) {
|
|
41
|
+
windows.push({
|
|
42
|
+
name: "团队每日额度",
|
|
43
|
+
used: limit > 0 ? Math.min(100, Math.round((10000 * consumed) / limit) / 100) : 100,
|
|
44
|
+
amount: consumed,
|
|
45
|
+
limit,
|
|
46
|
+
display: `${remaining} / ${limit} 积分`,
|
|
47
|
+
unit: "积分",
|
|
48
|
+
resetsAt: beijingResetAt(data.dailyLimitCycleDate, now),
|
|
49
|
+
})
|
|
50
|
+
} else {
|
|
51
|
+
// 旧业务日 / 缺字段不能沿用,更不能写成 0 或满额。
|
|
52
|
+
windows.push(dailyTextWindow("今日额度未知,请刷新"))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
windows.push({
|
|
56
|
+
name: "团队剩余积分",
|
|
57
|
+
used: balance === 0 ? 100 : 0,
|
|
58
|
+
// 共享池没有每日重置;正余额只展示,不用累计充值伪造占比。
|
|
59
|
+
// 池已空时必须有参与路由的 spent 窗口;无每日上限时此窗口表达可用状态。
|
|
60
|
+
...(balance > 0 && data.dailyLimitEnabled ? { aside: true } : {}),
|
|
61
|
+
display: balance === 0 ? "团队积分已耗尽" : `${balance} 积分(团队共享)`,
|
|
62
|
+
unit: "积分",
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
...(credential.accountId || credential.phone ? { user: credential.accountId || credential.phone } : {}),
|
|
67
|
+
plan: identity.name ? `团队 · ${identity.name}` : "团队",
|
|
68
|
+
balance: `${balance} 积分(团队共享)`,
|
|
69
|
+
windows,
|
|
70
|
+
signIn: "kept",
|
|
71
|
+
// 内部字段供本地额度闸使用;不把团队每日上限写进个人签到凭据。
|
|
72
|
+
_team: { balance, ...(data.dailyLimitEnabled && known ? { remaining } : {}) },
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/tracing.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Loomy 上游 `/chat/completions` 的追踪头 —— 逆向自**官方客户端 0.9.39**。
|
|
2
|
+
//
|
|
3
|
+
// 取证方式:官方安装包(`Loomy-Setup-0.9.39.exe`,2026-10-10)→ `resources/app.asar`
|
|
4
|
+
// → `electron/utils/request-headers.js` 的 `buildRequestHeaders()` /
|
|
5
|
+
// `buildLoomyChatRequestHeaders()`,以及 `electron/llm/llm-completion.js` 里真正发出
|
|
6
|
+
// 请求的那一段。**不是猜的,也不是照第三方文档抄的**:第三方文档少列了
|
|
7
|
+
// `TurnId` 与 `X-Loomy-Request-Purpose`,且把 ChatId/MsgId 的大小写写成了全小写。
|
|
8
|
+
//
|
|
9
|
+
// 官方客户端 0.9.39 的聊天请求头(`llm-completion.js`):
|
|
10
|
+
//
|
|
11
|
+
// Accept: application/json
|
|
12
|
+
// Content-Type: application/json
|
|
13
|
+
// Authorization: Bearer <session>
|
|
14
|
+
// token: <session> ← useSessionAuth 为真时额外带这一条
|
|
15
|
+
// traceparent: 00-<32hex>-<16hex>-01 ← **必带**;官方源码注释:
|
|
16
|
+
// 「实测 Loomy iModel 缺 traceparent 时
|
|
17
|
+
// chat/completions 会挂死直到超时」
|
|
18
|
+
// ChatId: chat-<uuid> ← 会话标识,同一会话的多次请求相同
|
|
19
|
+
// MsgId: msg-<uuid> ← 消息标识,同一条助手消息的请求/收尾复用
|
|
20
|
+
// TurnId: msg-<uuid> ← 可选(官方在可用时带)
|
|
21
|
+
// X-Loomy-Request-Purpose: chat.message ← 服务端裁决层按用途判定,缺了它就没有用途声明
|
|
22
|
+
// InvokeOrigin: user ← 用户主动调用;后台子调用才是 system
|
|
23
|
+
// loomy-version: 0.9.39 ← 客户端版本(`withLoomyVersionHeader` 注入)
|
|
24
|
+
//
|
|
25
|
+
// ⚠ HTTP 头名大小写不敏感,但**值**有形态要求:`traceparent` 必须是
|
|
26
|
+
// `00-<32hex>-<16hex>-<2hex>`,上游按 W3C Trace Context 解析。
|
|
27
|
+
//
|
|
28
|
+
// ⚠ 本插件此前只发 `token` + `Authorization` + 一个桌面客户端 UA,上面这些追踪头
|
|
29
|
+
// 一个都没有 —— 这是与官方客户端最实质的差异,也是 2026-11-18 那批
|
|
30
|
+
// 「请求挂住 / 首字 100 秒+ / 504 延迟未开始」最可疑的协议层原因。
|
|
31
|
+
|
|
32
|
+
import crypto from "node:crypto"
|
|
33
|
+
|
|
34
|
+
import { LOOMY_CHAT_VERSION } from "./constants.mjs"
|
|
35
|
+
|
|
36
|
+
/** `00-<32hex trace-id>-<16hex span-id>-<2hex flags>` */
|
|
37
|
+
const TRACEPARENT_RE = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/
|
|
38
|
+
|
|
39
|
+
/** W3C Trace Context:版本固定 `00`,flags `01` = sampled。 */
|
|
40
|
+
export function newTraceparent() {
|
|
41
|
+
return `00-${crypto.randomBytes(16).toString("hex")}-${crypto.randomBytes(8).toString("hex")}-01`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isTraceparent(value) {
|
|
45
|
+
return TRACEPARENT_RE.test(String(value ?? "").trim())
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 由 magpie 的会话 id 推出稳定的 `chat-<uuid>`。
|
|
50
|
+
*
|
|
51
|
+
* 官方客户端这里用的是它自己的对话 id;magpie 没有同名字段,但 `chat.headers`
|
|
52
|
+
* 钩子会把 magpie 的 `sessionID` 放进 `x-loomy-session`(见 index.mjs ⑧)。
|
|
53
|
+
* 用它的 sha256 拼成 UUID 形态:**同一会话永远同一个 ChatId**,重启后也稳定。
|
|
54
|
+
*/
|
|
55
|
+
export function chatIdFor(sessionId) {
|
|
56
|
+
const seed = String(sessionId ?? "").trim()
|
|
57
|
+
if (!seed) return `chat-${crypto.randomUUID()}`
|
|
58
|
+
const hex = crypto.createHash("sha256").update(seed).digest("hex")
|
|
59
|
+
return `chat-${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* `x-session-affinity`:**官方 opencode 运行时自己发的头**,Electron 那条路径没有。
|
|
64
|
+
*
|
|
65
|
+
* 取证(2026-11-23,本机抓包):用客户端自带的 `opencode.exe 1.14.22` + 模板里的
|
|
66
|
+
* `imodel` provider,把 baseURL 指到本机抓包口,抓到它真实发出的头:
|
|
67
|
+
*
|
|
68
|
+
* user-agent: opencode/1.14.22 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.13
|
|
69
|
+
* authorization: Bearer <session> · token: <session>
|
|
70
|
+
* x-session-affinity: ses_<openCode 会话 id>
|
|
71
|
+
* accept: *\/* · connection: keep-alive
|
|
72
|
+
* (**没有** traceparent / ChatId / MsgId / InvokeOrigin / loomy-version)
|
|
73
|
+
*
|
|
74
|
+
* 它用来把同一会话的请求粘到同一个后端实例,直接影响**前缀缓存命中**:
|
|
75
|
+
* 不带的请求缓存命中率是 0%,每次都要整段 prefill(3.3 万 token 的 prompt 实测首字 19 秒),
|
|
76
|
+
* 而带上同一 affinity 的会话在 magpie 日志里能看到 88~99% 的缓存命中。
|
|
77
|
+
*
|
|
78
|
+
* 官方值是 opencode 自己的 `ses_...`;magpie 没有同名字段,用会话 id 的 sha256 前 24 位
|
|
79
|
+
* 拼成同形态 `ses_<24hex>`:同一会话稳定,重启后也稳定。
|
|
80
|
+
*/
|
|
81
|
+
export function sessionAffinityFor(sessionId) {
|
|
82
|
+
const seed = String(sessionId ?? "").trim()
|
|
83
|
+
if (!seed) return ""
|
|
84
|
+
return `ses_${crypto.createHash("sha256").update(seed).digest("hex").slice(0, 24)}`
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function newMsgId() {
|
|
88
|
+
return `msg-${crypto.randomUUID()}`
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 一次聊天请求要补的追踪头。**不含鉴权头**(那两条由调用方按凭据设置)。
|
|
93
|
+
*
|
|
94
|
+
* @param {{ sessionId?: string, msgId?: string, purpose?: string, invokeOrigin?: string }} [input]
|
|
95
|
+
* @returns {Record<string,string>}
|
|
96
|
+
*/
|
|
97
|
+
export function chatTracingHeaders(input = {}) {
|
|
98
|
+
const msgId = String(input.msgId ?? "").trim() || newMsgId()
|
|
99
|
+
const purpose = String(input.purpose ?? "").trim() || "chat.message"
|
|
100
|
+
const invokeOrigin = String(input.invokeOrigin ?? "").trim() || "user"
|
|
101
|
+
const affinity = sessionAffinityFor(input.sessionId)
|
|
102
|
+
return {
|
|
103
|
+
traceparent: newTraceparent(),
|
|
104
|
+
ChatId: chatIdFor(input.sessionId),
|
|
105
|
+
MsgId: msgId,
|
|
106
|
+
TurnId: msgId,
|
|
107
|
+
"X-Loomy-Request-Purpose": purpose,
|
|
108
|
+
InvokeOrigin: invokeOrigin,
|
|
109
|
+
"loomy-version": LOOMY_CHAT_VERSION,
|
|
110
|
+
// 会话亲和(官方 opencode 路径必带)—— 直接决定前缀缓存能否命中
|
|
111
|
+
...(affinity ? { "x-session-affinity": affinity } : {}),
|
|
112
|
+
}
|
|
113
|
+
}
|
package/src/usage.mjs
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// 一次 usage() 做什么
|
|
5
5
|
// ════════════════════════════════════════════════════════════════════
|
|
6
6
|
//
|
|
7
|
-
// 1.
|
|
7
|
+
// 1. 读服务端当前团队:团队模式只查 team-points/balance(共享池 + 成员每日额度)。
|
|
8
|
+
// 个人模式仍只读 `/api/v1/points/balance`,沿用下列个人上限推导。
|
|
8
9
|
// 2. 上限(dailyQuota)按优先序取:
|
|
9
10
|
// a. 凭据里记的(登录/签到时拿到)—— **0 额外请求**
|
|
10
11
|
// b. 流水推导:dailyBalance + Σ(本业务日 consumeSource=daily 扣分)
|
|
@@ -27,6 +28,7 @@
|
|
|
27
28
|
import { _pure } from "./pure.mjs"
|
|
28
29
|
import { USAGE_CACHE_TTL_MS, USAGE_FAIL_TTL_MS, USAGE_LEAD_POINTS } from "./constants.mjs"
|
|
29
30
|
import { fetchBalances, fetchDailyLedger } from "./api.mjs"
|
|
31
|
+
import { readTeamUsage } from "./team.mjs"
|
|
30
32
|
|
|
31
33
|
const { beijingCycleDate, balanceLine, windowsOf } = _pure
|
|
32
34
|
|
|
@@ -41,7 +43,8 @@ const cache = new Map() // session -> { at, value }
|
|
|
41
43
|
export async function readUsage(credential, { now = Date.now(), fetcher = fetch } = {}) {
|
|
42
44
|
const key = credential.session
|
|
43
45
|
const hit = cache.get(key)
|
|
44
|
-
|
|
46
|
+
const ttl = hit?.value?.error ? USAGE_FAIL_TTL_MS : USAGE_CACHE_TTL_MS
|
|
47
|
+
if (hit && beijingCycleDate(hit.at) === beijingCycleDate(now) && now - hit.at < ttl) {
|
|
45
48
|
return hit.value
|
|
46
49
|
}
|
|
47
50
|
|
|
@@ -60,6 +63,9 @@ export async function readUsage(credential, { now = Date.now(), fetcher = fetch
|
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
async function compute(credential, now, fetcher) {
|
|
66
|
+
const team = await readTeamUsage(credential, now, fetcher)
|
|
67
|
+
if (team) return team
|
|
68
|
+
|
|
63
69
|
const pools = await fetchBalances(credential.session, fetcher)
|
|
64
70
|
if (!pools) {
|
|
65
71
|
return { error: "积分读数异常(上游没有返回 balance)", windows: [], signIn: "kept" }
|
|
@@ -94,6 +100,7 @@ async function compute(credential, now, fetcher) {
|
|
|
94
100
|
? { user: credential.accountId || credential.phone }
|
|
95
101
|
: {}),
|
|
96
102
|
balance: balanceLine(pools.total),
|
|
103
|
+
plan: "个人",
|
|
97
104
|
windows,
|
|
98
105
|
signIn: "kept",
|
|
99
106
|
// 内部字段,交给 index.mjs 决定要不要写回凭据
|
|
@@ -119,7 +126,7 @@ export function quotaToRemember(value, credential, now = Date.now()) {
|
|
|
119
126
|
/** 去掉内部字段,交给 magpie 的对象必须是纯净的 usage 形状。 */
|
|
120
127
|
export function publicUsage(value) {
|
|
121
128
|
if (!value) return { error: "查询失败", windows: [] }
|
|
122
|
-
const { _quota, ...rest } = value
|
|
129
|
+
const { _quota, _team, ...rest } = value
|
|
123
130
|
return rest
|
|
124
131
|
}
|
|
125
132
|
|
|
@@ -132,6 +139,11 @@ export function publicUsage(value) {
|
|
|
132
139
|
*/
|
|
133
140
|
export function exhausted(value) {
|
|
134
141
|
if (!value || value.error) return false
|
|
142
|
+
if (value._team) {
|
|
143
|
+
const { balance, remaining } = value._team
|
|
144
|
+
return (Number.isFinite(balance) && balance <= USAGE_LEAD_POINTS)
|
|
145
|
+
|| (Number.isFinite(remaining) && remaining <= USAGE_LEAD_POINTS)
|
|
146
|
+
}
|
|
135
147
|
const windows = Array.isArray(value.windows) ? value.windows : []
|
|
136
148
|
if (!windows.length) return false
|
|
137
149
|
const total = Number(String(value.balance ?? "").replace(/[^\d.-]/g, ""))
|