arkflow-magpie-plugins 0.0.0-stage → 2.0.19
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/LICENSE +21 -0
- package/NOTICE +17 -0
- package/README.en.md +29 -0
- package/README.md +28 -2
- package/bundled/meeting-actions/SKILL.md +11 -0
- package/docs/MAGPIE-LICENSE +21 -0
- package/index.mjs +9 -0
- package/package.json +79 -4
- package/page/app.css +275 -0
- package/page/app.js +784 -0
- package/page/bootstrap.js +59 -0
- package/page/connection.js +24 -0
- package/page/icon.svg +3 -0
- package/page/index.html +28 -0
- package/page/logo.png +0 -0
- package/page/magpie-components.css +131 -0
- package/page/request.js +101 -0
- package/page/service.html +3 -0
- package/page/store-model.mjs +107 -0
- package/page/theme.js +51 -0
- package/src/accounts.mjs +124 -0
- package/src/api-client.mjs +292 -0
- package/src/bundled-skills.mjs +13 -0
- package/src/config.mjs +71 -0
- package/src/credentials.mjs +90 -0
- package/src/host-adapter.mjs +707 -0
- package/src/install-defaults.mjs +92 -0
- package/src/install-identity.mjs +32 -0
- package/src/manual-initialization.mjs +225 -0
- package/src/native-auth.mjs +62 -0
- package/src/native-control.mjs +236 -0
- package/src/native-providers.mjs +422 -0
- package/src/page-service.mjs +358 -0
- package/src/provider.mjs +44 -0
- package/src/runtime.mjs +302 -0
- package/src/session.mjs +366 -0
- package/src/skill-metadata.mjs +32 -0
- package/src/skill-packages.mjs +226 -0
- package/src/skills.mjs +454 -0
- package/src/state-store.mjs +89 -0
- package/src/sync-engine.mjs +392 -0
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { closeSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"
|
|
3
|
+
import { join } from "node:path"
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises"
|
|
5
|
+
import { PRODUCTION_ORIGIN, PRODUCTION_ORIGIN_ALIASES } from "./config.mjs"
|
|
6
|
+
import { stableId, randomId } from "./state-store.mjs"
|
|
7
|
+
|
|
8
|
+
const CONNECTION_FIELDS = ["key", "chat", "responses", "anthropic", "gemini", "decide", "baseAPI"]
|
|
9
|
+
const fingerprint = value => stableId(...CONNECTION_FIELDS.map(field => value[field] || ""))
|
|
10
|
+
const BALANCE_FIELDS = ["balanceURL", "balancePath", "balanceMethod", "balanceToken"]
|
|
11
|
+
const balanceFingerprint = value => stableId(...BALANCE_FIELDS.map(field => value[field] || ""))
|
|
12
|
+
const RESET_KEEP_FIELDS = ["name", "off", "icon", "iconFrom", "was", "gave", "models", "noModels", "bestInFamily", "freeOnly", "pickedFrom", "delisted"]
|
|
13
|
+
const resetRevision = (owner, provider) => stableId("provider-reset", owner, provider)
|
|
14
|
+
const LEGACY_DEFAULT_ICON_HASHES = [
|
|
15
|
+
"e703a72d5d2b18f4c7c4158721d0f6e228cd3c5c8bb07986aefcfd5eca4f27b2", // NovaFlow
|
|
16
|
+
"9e91c6aa3321fe7e9c1e31ac1305877a6707f71ceb6c4df83f75d55a64c2e7e9", // ArkFlow 2.0.15
|
|
17
|
+
"a663423df91e3f3847885b72e825789a885951b08a25158b84b3432bee8d8819", // ArkFlow 2.0.16
|
|
18
|
+
"ebc3d944223f176950fda8395152dddadf5f7db2be74d837d64dc17d2e90cb90", // ArkFlow 2.0.17
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
// Magpie names imported SVG files using the first eight bytes of their hash.
|
|
22
|
+
function isLegacyDefaultIcon(icon) {
|
|
23
|
+
if (typeof icon !== "string") return false
|
|
24
|
+
if (LEGACY_DEFAULT_ICON_HASHES.some(hash => icon === `file:${hash.slice(0, 16)}.svg`)) return true
|
|
25
|
+
const prefix = "data:image/svg+xml;base64,"
|
|
26
|
+
if (!icon.startsWith(prefix)) return false
|
|
27
|
+
const hash = createHash("sha256").update(Buffer.from(icon.slice(prefix.length), "base64")).digest("hex")
|
|
28
|
+
return LEGACY_DEFAULT_ICON_HASHES.includes(hash)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function accountBalance(config, identity, session) {
|
|
32
|
+
const access = session.internalAuth?.()?.access
|
|
33
|
+
if (!access || access.startsWith("nfds_") || !["personal", "enterprise"].includes(identity.accountMode)) return null
|
|
34
|
+
return {
|
|
35
|
+
balanceURL: config.origin + config.apiPrefix + "/usage",
|
|
36
|
+
balancePath: "¥data." + (identity.accountMode === "enterprise" ? "company" : "personal") + ".available",
|
|
37
|
+
balanceMethod: "GET",
|
|
38
|
+
// Magpie's native account-balance query uses an explicit Authorization
|
|
39
|
+
// scheme for non-JWT tokens. It never uses this token for inference.
|
|
40
|
+
balanceToken: "Bearer " + access,
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const failure = (code, message) => Object.assign(new Error(message), { code })
|
|
44
|
+
|
|
45
|
+
function readConfig(path, optional = true) {
|
|
46
|
+
try {
|
|
47
|
+
const info = lstatSync(path)
|
|
48
|
+
if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) throw new Error()
|
|
49
|
+
const text = readFileSync(path, "utf8")
|
|
50
|
+
const value = JSON.parse(text)
|
|
51
|
+
if (!value || Array.isArray(value) || typeof value !== "object") throw new Error()
|
|
52
|
+
if (value.providers !== undefined && !Array.isArray(value.providers)) throw new Error()
|
|
53
|
+
return { text, value }
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (optional && error.code === "ENOENT") return { text: null, value: {} }
|
|
56
|
+
throw failure("PLUGIN_NATIVE_CONFIG_INVALID", "Magpie 供应商配置无法安全读取,请先检查配置文件")
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function writeConfig(path, before, value) {
|
|
61
|
+
const temporary = path + ".novaflow-" + randomId(8)
|
|
62
|
+
try {
|
|
63
|
+
writeFileSync(temporary, JSON.stringify(value, null, 2) + "\n", { mode: 0o600, flag: "wx" })
|
|
64
|
+
if (readConfig(path).text !== before.text) throw failure("PLUGIN_NATIVE_CONFIG_CONFLICT", "Magpie 供应商配置正在被修改,请重新同步")
|
|
65
|
+
renameSync(temporary, path)
|
|
66
|
+
} finally {
|
|
67
|
+
try { unlinkSync(temporary) } catch (error) { if (error.code !== "ENOENT") throw error }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function nativeProviderId(origin, userId, keyId) {
|
|
72
|
+
return "novaflow-key-" + stableId(origin, String(userId), String(keyId)).slice(0, 20)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function connectionFor(config, row) {
|
|
76
|
+
const declared = new URL(String(row.base_url || config.origin))
|
|
77
|
+
const allowed = config.origin === PRODUCTION_ORIGIN ? PRODUCTION_ORIGIN_ALIASES : [config.origin]
|
|
78
|
+
if (!allowed.includes(declared.origin) || declared.username || declared.password) {
|
|
79
|
+
throw failure("PLUGIN_NATIVE_ORIGIN_INVALID", "授权 Key 的地址不是当前 ArkFlow 服务地址")
|
|
80
|
+
}
|
|
81
|
+
const root = config.origin
|
|
82
|
+
const base = { key: row.key, chat: "", responses: "", anthropic: "", gemini: "", decide: "", baseAPI: "" }
|
|
83
|
+
// ArkFlow can report platform=openai for every family, including Claude.
|
|
84
|
+
// Use the server's group name, never the user's editable provider or Key name.
|
|
85
|
+
const group = String(row.group_name || "").normalize("NFKC").toLowerCase()
|
|
86
|
+
const claude = /(?:^|[^a-z])claude(?![a-z])/.test(group)
|
|
87
|
+
const gpt = /(?:^|[^a-z])(?:chat)?gpt(?![a-z])/.test(group)
|
|
88
|
+
if (claude && !gpt) return { ...base, anthropic: root, baseAPI: "anthropic" }
|
|
89
|
+
if (gpt && !claude) return { ...base, responses: root + "/v1", baseAPI: "responses" }
|
|
90
|
+
const gemini = String(row.platform || "").toLowerCase() === "gemini" || /(?:^|[^a-z])gemini(?![a-z])/.test(group)
|
|
91
|
+
if (gemini && !gpt && !claude) return { ...base, chat: root + "/v1", responses: root + "/v1", gemini: root + "/v1beta", baseAPI: "gemini" }
|
|
92
|
+
return { ...base, chat: root + "/v1", responses: root + "/v1", baseAPI: "responses" }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The ledger proves ownership by connection fingerprint, never by name alone.
|
|
96
|
+
// Native model caches are read only for the page and explicit initialization.
|
|
97
|
+
export class NativeProviderSync {
|
|
98
|
+
constructor({ directory, config, host, accounts, session, store, api, icon = "" }) {
|
|
99
|
+
Object.assign(this, { directory, config, host, accounts, session, store, api, icon })
|
|
100
|
+
this.path = join(directory, "providers.json")
|
|
101
|
+
this.lockPath = join(directory, ".novaflow-providers.lock")
|
|
102
|
+
this.tail = Promise.resolve()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async lock(signal) {
|
|
106
|
+
for (let i = 0; i < 100; i++) {
|
|
107
|
+
signal?.throwIfAborted()
|
|
108
|
+
try {
|
|
109
|
+
const fd = openSync(this.lockPath, "wx", 0o600)
|
|
110
|
+
writeFileSync(fd, String(process.pid))
|
|
111
|
+
return () => { closeSync(fd); unlinkSync(this.lockPath) }
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error.code !== "EEXIST") throw error
|
|
114
|
+
try {
|
|
115
|
+
const pid = Number(readFileSync(this.lockPath, "utf8"))
|
|
116
|
+
if (Number.isSafeInteger(pid) && pid > 0) {
|
|
117
|
+
try { process.kill(pid, 0) } catch (dead) { if (dead.code === "ESRCH") unlinkSync(this.lockPath) }
|
|
118
|
+
} else if (Date.now() - lstatSync(this.lockPath).mtimeMs > 30_000) unlinkSync(this.lockPath)
|
|
119
|
+
} catch (readError) { if (readError.code !== "ENOENT") throw readError }
|
|
120
|
+
await delay(25, undefined, { signal })
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
throw failure("PLUGIN_NATIVE_CONFIG_BUSY", "另一个 ArkFlow 同步正在保存供应商,请稍后重试")
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
reconcile(options = {}) {
|
|
127
|
+
const owner = this.session.ownership()
|
|
128
|
+
const pending = this.tail.catch(() => {}).then(() => {
|
|
129
|
+
this.session.assertOwnership(owner)
|
|
130
|
+
return this.apply(options)
|
|
131
|
+
})
|
|
132
|
+
this.tail = pending
|
|
133
|
+
return pending
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async apply({ signal, refresh = false, clear = false, foreignOnly = false, reset = null } = {}) {
|
|
137
|
+
const owner = this.session.ownership()
|
|
138
|
+
const release = await this.lock(signal)
|
|
139
|
+
let targets, pending, migrationRequired, describeFailure
|
|
140
|
+
try {
|
|
141
|
+
this.session.assertOwnership(owner)
|
|
142
|
+
signal?.throwIfAborted()
|
|
143
|
+
const identity = this.session.projection()
|
|
144
|
+
if (!clear && identity.status !== "authenticated") throw failure("PLUGIN_SESSION_CHANGED", "请先登录 ArkFlow")
|
|
145
|
+
const before = readConfig(this.path)
|
|
146
|
+
const ledger = this.store.read()
|
|
147
|
+
if (foreignOnly && ledger.userId === String(identity.userId) && ledger.origin === this.config.origin) return this.accounts.native
|
|
148
|
+
if (foreignOnly) clear = true
|
|
149
|
+
const entries = ledger.entries || {}
|
|
150
|
+
const ownedScope = ledger.userId === String(identity.userId) && ledger.origin === this.config.origin
|
|
151
|
+
let failureEntries = entries, failureScope = ownedScope
|
|
152
|
+
const desired = new Map()
|
|
153
|
+
const balance = clear ? null : accountBalance(this.config, identity, this.session)
|
|
154
|
+
const names = new Map()
|
|
155
|
+
const previousFailures = this.accounts.native.failures || []
|
|
156
|
+
const failures = reset ? previousFailures.filter(item => item.id !== reset.id) : []
|
|
157
|
+
const currentProviders = new Map((before.value.providers || []).map(item => [item.id, item]))
|
|
158
|
+
if (currentProviders.size !== (before.value.providers || []).length) throw failure("PLUGIN_NATIVE_CONFIG_INVALID", "Magpie 存在重复供应商标识,请先在供应商页面检查")
|
|
159
|
+
describeFailure = (id, code, message, current = currentProviders.get(id), revisionSource = current) => {
|
|
160
|
+
const owned = failureEntries[id], wanted = desired.get(id)
|
|
161
|
+
const groupName = wanted?.groupName || owned?.groupName || current?.name || ""
|
|
162
|
+
const canReset = failureScope && revisionSource && wanted && owned?.keyId === wanted.keyId
|
|
163
|
+
return { id, code, message, groupName, providerName: current?.name || wanted?.name || "", ...(canReset ? { resetRevision: resetRevision(owner, revisionSource) } : {}) }
|
|
164
|
+
}
|
|
165
|
+
for (const row of clear ? [] : this.accounts.rows.values()) {
|
|
166
|
+
const group = String(row.group_name || row.group_id || "未分组")
|
|
167
|
+
names.set(group, (names.get(group) || 0) + 1)
|
|
168
|
+
}
|
|
169
|
+
for (const row of clear ? [] : this.accounts.rows.values()) {
|
|
170
|
+
const id = nativeProviderId(this.config.origin, identity.userId, row.key_id)
|
|
171
|
+
const group = String(row.group_name || row.group_id || "未分组")
|
|
172
|
+
const name = group + "·ArkFlow" + (names.get(group) > 1 ? "·" + String(row.display_name || row.key_id) : "")
|
|
173
|
+
try {
|
|
174
|
+
desired.set(id, { id, name, ...connectionFor(this.config, row), balance, keyId: String(row.key_id), groupName: group })
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (!reset || reset.id === id) failures.push({ id, code: error.code, message: error.message, groupName: group, providerName: name })
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (reset) {
|
|
180
|
+
const current = currentProviders.get(reset.id), wanted = desired.get(reset.id), owned = entries[reset.id]
|
|
181
|
+
if (!ownedScope || !current || !wanted || owned?.keyId !== wanted.keyId || reset.revision !== resetRevision(owner, current)
|
|
182
|
+
|| !previousFailures.some(item => item.id === reset.id && item.resetRevision === reset.revision)) {
|
|
183
|
+
throw failure("PLUGIN_NATIVE_RESET_STALE", "分组配置或授权已变化,请重新同步后再确认重置")
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const nextEntries = {}, providers = [], queue = [], iconQueue = []
|
|
187
|
+
const remaining = new Map(desired)
|
|
188
|
+
let changed = false
|
|
189
|
+
for (const current of before.value.providers || []) {
|
|
190
|
+
const owned = entries[current.id], wanted = desired.get(current.id)
|
|
191
|
+
if (reset && current.id !== reset.id) {
|
|
192
|
+
providers.push(current)
|
|
193
|
+
if (owned) nextEntries[current.id] = owned
|
|
194
|
+
continue
|
|
195
|
+
}
|
|
196
|
+
if (!owned) {
|
|
197
|
+
providers.push(current)
|
|
198
|
+
if (wanted) {
|
|
199
|
+
failures.push(describeFailure(current.id, "PLUGIN_NATIVE_ID_CONFLICT", "供应商标识与本机配置冲突,请在 Magpie 中确认"))
|
|
200
|
+
remaining.delete(current.id)
|
|
201
|
+
}
|
|
202
|
+
continue
|
|
203
|
+
}
|
|
204
|
+
if (!reset && !(owned.fingerprints || []).includes(fingerprint(current))) {
|
|
205
|
+
let kept = current
|
|
206
|
+
if (!wanted && current.balanceToken && (owned.balanceTokenFingerprints || []).includes(stableId(current.balanceToken))) {
|
|
207
|
+
kept = { ...current }
|
|
208
|
+
// A manually changed model connection stays, but signing out must
|
|
209
|
+
// still forget the account credential we put beside it.
|
|
210
|
+
if ((owned.balanceFingerprints || []).includes(balanceFingerprint(current))) {
|
|
211
|
+
for (const field of BALANCE_FIELDS) delete kept[field]
|
|
212
|
+
} else delete kept.balanceToken
|
|
213
|
+
changed = true
|
|
214
|
+
}
|
|
215
|
+
providers.push(kept)
|
|
216
|
+
nextEntries[current.id] = owned
|
|
217
|
+
failures.push(describeFailure(current.id, "PLUGIN_NATIVE_OWNERSHIP_CONFLICT", "供应商连接已被手动修改"))
|
|
218
|
+
remaining.delete(current.id)
|
|
219
|
+
continue
|
|
220
|
+
}
|
|
221
|
+
if (!wanted) { changed = true; continue }
|
|
222
|
+
remaining.delete(current.id)
|
|
223
|
+
const { keyId, groupName, balance, ...connection } = wanted
|
|
224
|
+
// Magpie omits empty protocol fields when saving an icon. Keep absent
|
|
225
|
+
// empty fields absent so the next poll does not rewrite the config.
|
|
226
|
+
const updates = Object.fromEntries(Object.entries(connection).filter(([field, value]) => value !== "" || Object.hasOwn(current, field)))
|
|
227
|
+
const next = reset
|
|
228
|
+
? { ...connection, ...(balance || {}), website: this.config.origin + "/#" + current.id,
|
|
229
|
+
...Object.fromEntries(RESET_KEEP_FIELDS.filter(field => Object.hasOwn(current, field)).map(field => [field, current[field]])) }
|
|
230
|
+
: { ...current, ...updates, name: current.name === owned.name ? wanted.name : current.name }
|
|
231
|
+
if (!balance && owned.balanceFingerprints?.includes(balanceFingerprint(current))) {
|
|
232
|
+
for (const field of BALANCE_FIELDS) delete next[field]
|
|
233
|
+
}
|
|
234
|
+
// Add or update only untouched balance settings. Custom balance queries
|
|
235
|
+
// must never receive a newly synchronized connection credential.
|
|
236
|
+
const managesBalance = !reset && balance && (!BALANCE_FIELDS.some(field => current[field])
|
|
237
|
+
|| (owned.balanceFingerprints || []).includes(balanceFingerprint(current)))
|
|
238
|
+
if (managesBalance) Object.assign(next, balance)
|
|
239
|
+
// User choices, aliases, disabled state, routing and extra settings stay native.
|
|
240
|
+
providers.push(next)
|
|
241
|
+
const newFingerprint = fingerprint(next)
|
|
242
|
+
const connectionChanged = fingerprint(current) !== newFingerprint
|
|
243
|
+
const needsIcon = !!this.icon && (isLegacyDefaultIcon(current.icon)
|
|
244
|
+
|| !owned.iconInitialized && (!current.icon || current.icon === "generic" || current.icon === this.icon))
|
|
245
|
+
nextEntries[current.id] = {
|
|
246
|
+
...owned, keyId, groupName, name: wanted.name,
|
|
247
|
+
fingerprints: reset ? [newFingerprint] : [...new Set([fingerprint(current), newFingerprint])],
|
|
248
|
+
pendingRefresh: owned.pendingRefresh || connectionChanged,
|
|
249
|
+
iconInitialized: owned.iconInitialized || !needsIcon,
|
|
250
|
+
...(reset ? { emptyCatalogAt: 0, balanceFingerprints: balance ? [balanceFingerprint(balance)] : [], balanceTokenFingerprints: balance ? [stableId(balance.balanceToken)] : [] } : {}),
|
|
251
|
+
...(managesBalance ? {
|
|
252
|
+
balanceFingerprints: [...new Set([balanceFingerprint(current), balanceFingerprint(next)])],
|
|
253
|
+
balanceTokenFingerprints: [...new Set([stableId(current.balanceToken || ""), stableId(next.balanceToken)])],
|
|
254
|
+
} : {}),
|
|
255
|
+
}
|
|
256
|
+
if (needsIcon) iconQueue.push(current.id)
|
|
257
|
+
if (JSON.stringify(current) !== JSON.stringify(next)) changed = true
|
|
258
|
+
const emptyCheckDue = owned.emptyCatalogAt && Date.now() - owned.emptyCatalogAt >= this.config.retryMaxMs
|
|
259
|
+
if (!current.off && (reset || refresh || emptyCheckDue || nextEntries[current.id].pendingRefresh || owned.catalogMetadataVersion !== 1)) queue.push(current.id)
|
|
260
|
+
}
|
|
261
|
+
for (const [id, wanted] of reset ? [] : remaining) {
|
|
262
|
+
const { keyId, groupName, balance, ...connection } = wanted
|
|
263
|
+
// A stable website fragment keeps Magpie's automatic duplicate-provider
|
|
264
|
+
// folding from combining different group Keys with numbered names.
|
|
265
|
+
providers.push({ ...connection, ...(balance || {}), website: this.config.origin + "/#" + id })
|
|
266
|
+
nextEntries[id] = { keyId, groupName, name: wanted.name, fingerprints: [fingerprint(connection)], pendingRefresh: true, iconInitialized: !this.icon, ...(balance ? { balanceFingerprints: [balanceFingerprint(balance)], balanceTokenFingerprints: [stableId(balance.balanceToken)] } : {}) }
|
|
267
|
+
queue.push(id)
|
|
268
|
+
if (this.icon) iconQueue.push(id)
|
|
269
|
+
changed = true
|
|
270
|
+
}
|
|
271
|
+
// Record ownership before installing a connection, so a crash cannot orphan a Key.
|
|
272
|
+
const recoveryEntries = { ...entries }
|
|
273
|
+
for (const [id, entry] of Object.entries(nextEntries)) {
|
|
274
|
+
recoveryEntries[id] = { ...entry, fingerprints: [...new Set([...(entries[id]?.fingerprints || []), ...entry.fingerprints])] }
|
|
275
|
+
}
|
|
276
|
+
const scope = { userId: String(identity.userId || ""), origin: this.config.origin }
|
|
277
|
+
this.store.write({ ...ledger, ...scope, entries: recoveryEntries })
|
|
278
|
+
this.session.assertOwnership(owner)
|
|
279
|
+
if (changed) writeConfig(this.path, before, { ...before.value, providers })
|
|
280
|
+
migrationRequired = ledger.migrationRequired || this.accounts.native.migrationRequired
|
|
281
|
+
this.store.write({ ...ledger, ...scope, entries: nextEntries, migrationRequired })
|
|
282
|
+
failureEntries = nextEntries
|
|
283
|
+
failureScope = !clear
|
|
284
|
+
pending = { failures, migrationRequired, providers: [] }
|
|
285
|
+
const previousProviders = new Map(this.accounts.native.providers.map(provider => [provider.id, provider]))
|
|
286
|
+
this.accounts.setNativeState(pending)
|
|
287
|
+
targets = { entries: nextEntries, providers, queue, iconQueue, previousProviders }
|
|
288
|
+
} finally { release() }
|
|
289
|
+
|
|
290
|
+
const describeHostFailure = (id, code, message) => {
|
|
291
|
+
let current = null
|
|
292
|
+
try { current = readConfig(this.path).value.providers?.find(item => item.id === id) || null } catch {}
|
|
293
|
+
return describeFailure(id, code, message, current || targets.providers.find(item => item.id === id), current)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
for (const id of targets.iconQueue) {
|
|
297
|
+
this.session.assertOwnership(owner)
|
|
298
|
+
signal?.throwIfAborted()
|
|
299
|
+
try {
|
|
300
|
+
// Recheck after saving connections: another process may have removed
|
|
301
|
+
// the provider or the user may have chosen a different icon meanwhile.
|
|
302
|
+
const current = readConfig(this.path).value.providers?.find(item => item.id === id)
|
|
303
|
+
const entry = this.store.read().entries?.[id]
|
|
304
|
+
if (!current || !entry?.fingerprints?.includes(fingerprint(current))) continue
|
|
305
|
+
if (!current.icon || current.icon === "generic" || current.icon === this.icon || isLegacyDefaultIcon(current.icon)) {
|
|
306
|
+
await this.host.syncProviderIcon(id, signal)
|
|
307
|
+
}
|
|
308
|
+
this.session.assertOwnership(owner)
|
|
309
|
+
const unlock = await this.lock(signal)
|
|
310
|
+
try {
|
|
311
|
+
this.session.assertOwnership(owner)
|
|
312
|
+
const ledger = this.store.read()
|
|
313
|
+
if (ledger.entries?.[id]) {
|
|
314
|
+
ledger.entries[id].iconInitialized = true
|
|
315
|
+
this.store.write(ledger)
|
|
316
|
+
}
|
|
317
|
+
} finally { unlock() }
|
|
318
|
+
} catch (error) {
|
|
319
|
+
this.session.assertOwnership(owner)
|
|
320
|
+
signal?.throwIfAborted()
|
|
321
|
+
pending.failures.push(describeHostFailure(id, "PLUGIN_NATIVE_ICON_FAILED", "供应商图标同步未完成"))
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
for (const id of targets.queue) {
|
|
326
|
+
this.session.assertOwnership(owner)
|
|
327
|
+
signal?.throwIfAborted()
|
|
328
|
+
const provider = targets.providers.find(item => item.id === id)
|
|
329
|
+
let refreshed = false, emptyCatalogAt = 0
|
|
330
|
+
try {
|
|
331
|
+
try {
|
|
332
|
+
await this.host.refreshProvider(id, signal)
|
|
333
|
+
} catch (error) {
|
|
334
|
+
this.session.assertOwnership(owner)
|
|
335
|
+
signal?.throwIfAborted()
|
|
336
|
+
const emptyListURL = error.listURL === this.config.origin + "/v1/models"
|
|
337
|
+
|| (!!provider.gemini && error.listURL === provider.gemini + "/models")
|
|
338
|
+
if (error.code !== "PLUGIN_NATIVE_EMPTY_LIST" || !emptyListURL
|
|
339
|
+
|| !await this.api.confirmEmptyModelList(provider.key, signal)) throw error
|
|
340
|
+
emptyCatalogAt = Date.now()
|
|
341
|
+
}
|
|
342
|
+
refreshed = true
|
|
343
|
+
} catch {
|
|
344
|
+
this.session.assertOwnership(owner)
|
|
345
|
+
signal?.throwIfAborted()
|
|
346
|
+
pending.failures.push(describeHostFailure(id, "PLUGIN_NATIVE_REFRESH_FAILED", "模型获取未完成,请重试同步"))
|
|
347
|
+
}
|
|
348
|
+
const unlock = await this.lock(signal)
|
|
349
|
+
try {
|
|
350
|
+
this.session.assertOwnership(owner)
|
|
351
|
+
const ledger = this.store.read(), entry = ledger.entries?.[id]
|
|
352
|
+
if (entry && entry.fingerprints.includes(fingerprint(provider))) {
|
|
353
|
+
entry.pendingRefresh = !refreshed
|
|
354
|
+
if (refreshed) {
|
|
355
|
+
entry.catalogMetadataVersion = 1
|
|
356
|
+
entry.emptyCatalogAt = emptyCatalogAt
|
|
357
|
+
targets.entries[id].emptyCatalogAt = emptyCatalogAt
|
|
358
|
+
}
|
|
359
|
+
this.store.write(ledger)
|
|
360
|
+
}
|
|
361
|
+
} finally { unlock() }
|
|
362
|
+
}
|
|
363
|
+
this.session.assertOwnership(owner)
|
|
364
|
+
for (const [id, entry] of Object.entries(targets.entries)) {
|
|
365
|
+
if (!desiredForCurrent(entry, this.accounts, clear)) continue
|
|
366
|
+
if (reset && reset.id !== id) {
|
|
367
|
+
const previous = targets.previousProviders.get(id)
|
|
368
|
+
if (previous) pending.providers.push(previous)
|
|
369
|
+
continue
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
const catalog = entry.emptyCatalogAt ? { models: [] } : await this.host.readProviderCatalog(id)
|
|
373
|
+
this.session.assertOwnership(owner)
|
|
374
|
+
const provider = targets.providers.find(item => item.id === id)
|
|
375
|
+
pending.providers.push({ id, keyId: entry.keyId, groupName: entry.groupName, name: provider?.name || entry.name, off: provider?.off === true, modelCount: catalog.models.length, models: catalog.models, ...(entry.emptyCatalogAt ? { emptyCatalog: true } : {}) })
|
|
376
|
+
} catch {
|
|
377
|
+
pending.failures.push(describeHostFailure(id, "PLUGIN_NATIVE_CATALOG_UNAVAILABLE", "暂时无法读取模型列表,请重试同步"))
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
this.session.assertOwnership(owner)
|
|
381
|
+
const representative = pending.providers.find(item => !item.off && targets.providers.some(provider => provider.id === item.id
|
|
382
|
+
&& provider.balanceURL === this.config.origin + this.config.apiPrefix + "/usage"))
|
|
383
|
+
if (!reset && representative) {
|
|
384
|
+
try { this.migrateTraySelection(representative.id) }
|
|
385
|
+
catch { pending.failures.push({ code: "PLUGIN_TRAY_MIGRATION_FAILED", message: "菜单栏额度选项更新未完成,请在 Magpie 设置中重新选择 ArkFlow 分组" }) }
|
|
386
|
+
}
|
|
387
|
+
this.accounts.setNativeState(pending)
|
|
388
|
+
return reset ? { ...pending, resetApplied: true } : pending
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
migrateTraySelection(id) {
|
|
392
|
+
const path = join(this.directory, "settings.json")
|
|
393
|
+
const before = readConfig(path)
|
|
394
|
+
const selected = Array.isArray(before.value.trayUsages) ? before.value.trayUsages
|
|
395
|
+
: typeof before.value.trayUsage === "string" && before.value.trayUsage ? [before.value.trayUsage] : []
|
|
396
|
+
const legacy = value => typeof value === "string" && (value === "novaflow" || value.startsWith("novaflow|"))
|
|
397
|
+
if (!selected.some(legacy)) return
|
|
398
|
+
const trayUsages = [...new Set(selected.map(value => legacy(value) ? id : value))]
|
|
399
|
+
writeConfig(path, before, { ...before.value, trayUsages, trayUsage: trayUsages[0] || "" })
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async retireLegacyEntry() {
|
|
403
|
+
const release = await this.lock()
|
|
404
|
+
try {
|
|
405
|
+
const before = readConfig(this.path)
|
|
406
|
+
const providers = (before.value.providers || []).filter(item => item.id !== "novaflow"
|
|
407
|
+
|| CONNECTION_FIELDS.some(field => item[field]) || item.keys?.length)
|
|
408
|
+
if (providers.length !== (before.value.providers || []).length) {
|
|
409
|
+
writeConfig(this.path, before, { ...before.value, providers })
|
|
410
|
+
return true
|
|
411
|
+
}
|
|
412
|
+
return false
|
|
413
|
+
} finally { release() }
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
clear() { return this.reconcile({ clear: true }) }
|
|
417
|
+
clearForeign() { return this.reconcile({ foreignOnly: true }) }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function desiredForCurrent(entry, accounts, clear) {
|
|
421
|
+
return !clear && accounts.rows.has(entry.keyId)
|
|
422
|
+
}
|