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,92 @@
|
|
|
1
|
+
import { JsonStore, randomId } from "./state-store.mjs"
|
|
2
|
+
|
|
3
|
+
const FIELD_RE = /^[a-z][a-z0-9_.-]{0,127}$/
|
|
4
|
+
|
|
5
|
+
function validConfig(value) {
|
|
6
|
+
if (!Array.isArray(value)) return { valid: false, reason: "wait_config", fields: [] }
|
|
7
|
+
const fields = []
|
|
8
|
+
for (const item of value) {
|
|
9
|
+
if (!item || typeof item !== "object") return { valid: false, reason: "invalid_config", fields: [] }
|
|
10
|
+
if (!FIELD_RE.test(String(item.field ?? ""))) return { valid: false, reason: "invalid_config", fields: [] }
|
|
11
|
+
if (item.value === undefined) return { valid: false, reason: "invalid_config", fields: [] }
|
|
12
|
+
fields.push({
|
|
13
|
+
id: String(item.id ?? `${item.platform || "global"}:${item.field}`),
|
|
14
|
+
platform: String(item.platform ?? "global"),
|
|
15
|
+
field: String(item.field),
|
|
16
|
+
value: item.value,
|
|
17
|
+
})
|
|
18
|
+
}
|
|
19
|
+
const ids = fields.map((field) => field.id)
|
|
20
|
+
if (new Set(ids).size !== ids.length) return { valid: false, reason: "duplicate_field", fields: [] }
|
|
21
|
+
return { valid: true, reason: fields.length ? "ready" : "wait_config", fields }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class InstallDefaultsRunner {
|
|
25
|
+
constructor({ adapter, markerStore, backupStore, config = null, now = () => new Date(), platform = process.platform }) {
|
|
26
|
+
this.adapter = adapter
|
|
27
|
+
this.marker = markerStore ?? new JsonStore("", {})
|
|
28
|
+
this.backups = backupStore ?? new JsonStore("", {})
|
|
29
|
+
this.config = config
|
|
30
|
+
this.now = now
|
|
31
|
+
this.platform = platform
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
status() {
|
|
35
|
+
const value = this.marker.read()
|
|
36
|
+
return {
|
|
37
|
+
status: value.status ?? "wait_config",
|
|
38
|
+
reason: value.reason ?? "wait_config",
|
|
39
|
+
instanceId: value.instanceId ?? "",
|
|
40
|
+
fields: Object.keys(value.fields ?? {}),
|
|
41
|
+
failures: Object.entries(value.fields ?? {}).filter(([, item]) => item.status !== "success").map(([id]) => id),
|
|
42
|
+
updatedAt: value.updatedAt ?? "",
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async run() {
|
|
47
|
+
const checked = validConfig(this.config?.fields ?? this.config)
|
|
48
|
+
const value = this.marker.read()
|
|
49
|
+
if (!value.instanceId) value.instanceId = randomId(18)
|
|
50
|
+
if (!checked.valid) {
|
|
51
|
+
value.status = "wait_config"
|
|
52
|
+
value.reason = checked.reason
|
|
53
|
+
value.updatedAt = this.now().toISOString()
|
|
54
|
+
this.marker.write(value)
|
|
55
|
+
return this.status()
|
|
56
|
+
}
|
|
57
|
+
value.fields ??= {}
|
|
58
|
+
value.status = "running"
|
|
59
|
+
value.reason = ""
|
|
60
|
+
for (const field of checked.fields) {
|
|
61
|
+
if (value.fields[field.id]?.status === "success") continue
|
|
62
|
+
try {
|
|
63
|
+
if (!Object.hasOwn(value.fields[field.id] ?? {}, "previous")) {
|
|
64
|
+
try {
|
|
65
|
+
value.fields[field.id] = { ...value.fields[field.id], previous: await this.adapter.read(field.platform, field.field) }
|
|
66
|
+
this.backups.write({ ...this.backups.read(), [field.id]: value.fields[field.id].previous })
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error.code !== "HOST_SETTINGS_UNSUPPORTED") throw error
|
|
69
|
+
value.fields[field.id] = { ...value.fields[field.id], previous: undefined }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
await this.adapter.write(field.platform, field.field, field.value)
|
|
73
|
+
const current = await this.adapter.read(field.platform, field.field)
|
|
74
|
+
if (JSON.stringify(current) !== JSON.stringify(field.value)) throw new Error("Default setting could not be read back")
|
|
75
|
+
value.fields[field.id] = { ...value.fields[field.id], status: "success", updatedAt: this.now().toISOString() }
|
|
76
|
+
} catch (error) {
|
|
77
|
+
value.fields[field.id] = {
|
|
78
|
+
...value.fields[field.id],
|
|
79
|
+
status: "failed",
|
|
80
|
+
reason: error?.code === "HOST_SETTINGS_UNSUPPORTED" ? "host_settings_unsupported" : "write_failed",
|
|
81
|
+
updatedAt: this.now().toISOString(),
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
this.marker.write(value)
|
|
85
|
+
}
|
|
86
|
+
const complete = checked.fields.every((field) => value.fields[field.id]?.status === "success")
|
|
87
|
+
value.status = complete ? "complete" : "partial_failure"
|
|
88
|
+
value.updatedAt = this.now().toISOString()
|
|
89
|
+
this.marker.write(value)
|
|
90
|
+
return this.status()
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs"
|
|
2
|
+
import { isAbsolute, join } from "node:path"
|
|
3
|
+
import { fileURLToPath } from "node:url"
|
|
4
|
+
|
|
5
|
+
const packageNames = new Set(["novaflow-magpie-plugins", "arkflow-magpie-plugins"])
|
|
6
|
+
|
|
7
|
+
function installedName(spec) {
|
|
8
|
+
if (/^(?:npm:)?(?:novaflow|arkflow)-magpie-plugins(?:@[^/]+)?$/.test(spec)) {
|
|
9
|
+
return spec.replace(/^npm:/, "").split("@")[0]
|
|
10
|
+
}
|
|
11
|
+
const repo = /^(?:github:|(?:git\+)?https:\/\/github\.com\/)azheyc\/((?:novaflow|arkflow)-magpie-plugins)(?:\.git)?(?:#.*)?$/i.exec(spec)
|
|
12
|
+
if (repo) return repo[1].toLowerCase()
|
|
13
|
+
try {
|
|
14
|
+
const target = spec.startsWith("file://") ? fileURLToPath(spec) : spec
|
|
15
|
+
if (!isAbsolute(target)) return ""
|
|
16
|
+
return JSON.parse(readFileSync(join(target, "package.json"), "utf8")).name
|
|
17
|
+
} catch { return "" }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function assertSingleInstallation(directory) {
|
|
21
|
+
let config
|
|
22
|
+
try { config = JSON.parse(readFileSync(join(directory, "plugins.json"), "utf8")) }
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error?.code === "ENOENT") return
|
|
25
|
+
throw error
|
|
26
|
+
}
|
|
27
|
+
const entries = Array.isArray(config.plugins) ? config.plugins : []
|
|
28
|
+
const registered = entries.filter(entry => typeof entry?.spec === "string" && packageNames.has(installedName(entry.spec)))
|
|
29
|
+
if (registered.length > 1) {
|
|
30
|
+
throw new Error("ArkFlow: 请在 Magpie 插件列表移除旧的或重复的 ArkFlow/NovaFlow 插件,再启用新版,无需退出账户。Remove duplicate plugin entries before using ArkFlow; your account data is kept.")
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { readFile, lstat, writeFile, rename, rm } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { randomId } from "./state-store.mjs"
|
|
4
|
+
|
|
5
|
+
async function readObject(path, optional = false) {
|
|
6
|
+
try {
|
|
7
|
+
const info = await lstat(path)
|
|
8
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error("初始化配置文件必须是普通文件")
|
|
9
|
+
const text = await readFile(path, "utf8")
|
|
10
|
+
let value
|
|
11
|
+
try { value = JSON.parse(text) } catch { throw new Error("Magpie 配置格式不正确,请修复后重试") }
|
|
12
|
+
if (!value || Array.isArray(value) || typeof value !== "object") throw new Error("初始化配置文件格式不正确")
|
|
13
|
+
return { text, value, links: info.nlink }
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (optional && error.code === "ENOENT") return { text: null, value: {} }
|
|
16
|
+
throw error
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const DEFAULT_IMAGE_MODEL = "gpt-image-2.6"
|
|
21
|
+
const UPDATE_SETTINGS = { updateChannel: "daily", noAutoDownload: false, autoRestart: true, noAutoUpdate: false }
|
|
22
|
+
|
|
23
|
+
export class ManualInitialization {
|
|
24
|
+
constructor({ host, accounts, markerStore, backupStore, directory }) {
|
|
25
|
+
Object.assign(this, { host, accounts, markerStore, backupStore, directory })
|
|
26
|
+
this.pending = null
|
|
27
|
+
}
|
|
28
|
+
status() {
|
|
29
|
+
const marker = this.markerStore.read()
|
|
30
|
+
const fields = { ...marker.fields }
|
|
31
|
+
delete fields.updateChannel
|
|
32
|
+
delete fields.agentModelNames
|
|
33
|
+
const needsImageCheck = fields.imageGen?.status === "success" && fields.imageGen.hostValidated !== true
|
|
34
|
+
const complete = fields.mcp?.status === "success" && ["success", "skipped"].includes(fields.imageGen?.status) && !needsImageCheck
|
|
35
|
+
&& Object.values(fields).every(item => ["success", "skipped"].includes(item.status))
|
|
36
|
+
return {
|
|
37
|
+
status: marker.status === "running" ? this.pending ? "running" : "partial_failure"
|
|
38
|
+
: complete ? "complete" : needsImageCheck ? "partial_failure" : marker.status === "wait_config" || !marker.status ? "pending" : marker.status,
|
|
39
|
+
fields: Object.keys(fields).filter(key => fields[key].status === "success" && !(key === "imageGen" && needsImageCheck)),
|
|
40
|
+
failures: Object.entries(fields).filter(([key, item]) => !["success", "skipped"].includes(item.status) || (key === "imageGen" && needsImageCheck)).map(([key]) => key),
|
|
41
|
+
results: Object.entries(fields).map(([id, item]) => ({ id, status: id === "imageGen" && needsImageCheck ? "pending" : item.status, message: id === "imageGen" && needsImageCheck ? "生图模型将在下次登录时重新确认" : item.message || "" })),
|
|
42
|
+
updatedAt: marker.updatedAt || "",
|
|
43
|
+
currentTask: this.pending ? marker.currentTask || "" : "",
|
|
44
|
+
manual: marker.automatic !== true,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
run(options = {}) {
|
|
48
|
+
if (!this.pending) this.pending = this.apply(options).finally(() => { this.pending = null })
|
|
49
|
+
return this.pending
|
|
50
|
+
}
|
|
51
|
+
async saveSettings(patch, assertCurrent) {
|
|
52
|
+
const path = join(this.directory, "settings.json")
|
|
53
|
+
const before = await readObject(path, true)
|
|
54
|
+
if (before.links > 1) throw new Error("设置文件使用了硬链接,请在 Magpie 设置中手动配置")
|
|
55
|
+
const fields = Object.entries(patch)
|
|
56
|
+
const backup = this.backupStore.read()
|
|
57
|
+
const original = fields.filter(([field]) => !Object.hasOwn(backup, field))
|
|
58
|
+
if (original.length) {
|
|
59
|
+
for (const [field] of original) backup[field] = { present: Object.hasOwn(before.value, field), value: before.value[field] ?? null }
|
|
60
|
+
this.backupStore.write(backup)
|
|
61
|
+
}
|
|
62
|
+
if (fields.every(([field, value]) => before.value[field] === value)) return
|
|
63
|
+
const temporary = path + ".novaflow-" + randomId(8)
|
|
64
|
+
try {
|
|
65
|
+
await writeFile(temporary, JSON.stringify({ ...before.value, ...patch }, null, 2) + "\n", { mode: 0o600, flag: "wx" })
|
|
66
|
+
// Never merge from an old settings snapshot over a concurrent user edit.
|
|
67
|
+
const current = await readObject(path, true)
|
|
68
|
+
if (current.text !== before.text) throw new Error("Magpie 设置正在被修改,请重试初始化")
|
|
69
|
+
assertCurrent()
|
|
70
|
+
await rename(temporary, path)
|
|
71
|
+
const saved = (await readObject(path)).value
|
|
72
|
+
if (fields.some(([field, value]) => saved[field] !== value)) throw new Error("设置保存后校验失败,请重试")
|
|
73
|
+
} finally { await rm(temporary, { force: true }) }
|
|
74
|
+
}
|
|
75
|
+
async imageMCP(assertCurrent) {
|
|
76
|
+
if (!this.host.available) throw new Error("暂时无法连接 Magpie,请重新打开插件页面后重试")
|
|
77
|
+
const applied = (await readObject(join(this.directory, "applied.json"), true)).value
|
|
78
|
+
const agents = []
|
|
79
|
+
for (const [id, entry] of Object.entries(applied)) {
|
|
80
|
+
const model = entry?.fields?.model
|
|
81
|
+
if (!/^[a-z0-9][a-z0-9_.-]{0,79}$/.test(id) || typeof model !== "string" || !model || /\s/.test(model)) continue
|
|
82
|
+
const current = await this.host.run([id, "model"])
|
|
83
|
+
const output = current.stdout.replace(/\x1b\[[0-9;]*m/g, "").trim()
|
|
84
|
+
if (output.endsWith(" " + model)) agents.push(id)
|
|
85
|
+
}
|
|
86
|
+
const path = join(this.directory, "library.json")
|
|
87
|
+
const library = (await readObject(path, true)).value
|
|
88
|
+
const existing = (library.mcp || []).find(item => item.name === "magpie-image")
|
|
89
|
+
if (existing && (existing.transport !== "stdio" || JSON.stringify(existing.args) !== JSON.stringify(["mcp", "image"]) || existing.command !== this.host.magpiePath)) {
|
|
90
|
+
throw new Error("资料库已有不同的 magpie-image 配置,请先在 Magpie 中核对")
|
|
91
|
+
}
|
|
92
|
+
const backups = this.backupStore.read()
|
|
93
|
+
if (!Object.hasOwn(backups, "mcp")) this.backupStore.write({ ...backups, mcp: existing || null })
|
|
94
|
+
const targets = [...new Set([...(existing?.agents || []), ...agents])].filter(id => /^[a-z0-9][a-z0-9_.-]{0,79}$/.test(id)).sort()
|
|
95
|
+
assertCurrent()
|
|
96
|
+
if (!existing) {
|
|
97
|
+
await this.host.run(["library", "mcp", "add", "magpie-image", this.host.magpiePath, "mcp", "image", "agents=" + (targets.join(",") || "none")], { timeout: 60_000 })
|
|
98
|
+
} else if (targets.some(id => !existing.agents?.includes(id))) {
|
|
99
|
+
await this.host.run(["library", "mcp", "agents", "magpie-image", targets.join(",")], { timeout: 60_000 })
|
|
100
|
+
}
|
|
101
|
+
let afterData = (await readObject(path)).value
|
|
102
|
+
const linked = id => afterData.applied?.[id]?.mcp?.includes("magpie-image") || (afterData.MCPHub === true && afterData.applied?.[id]?.mcp?.includes("magpie"))
|
|
103
|
+
if (agents.some(id => !linked(id))) {
|
|
104
|
+
assertCurrent()
|
|
105
|
+
await this.host.run(["library", "sync"], { timeout: 60_000 })
|
|
106
|
+
afterData = (await readObject(path)).value
|
|
107
|
+
}
|
|
108
|
+
const after = afterData.mcp?.find(item => item.name === "magpie-image")
|
|
109
|
+
if (!after || after.command !== this.host.magpiePath || JSON.stringify(after.args) !== JSON.stringify(["mcp", "image"]) || !targets.every(id => after.agents?.includes(id)) || agents.some(id => !linked(id))) throw new Error("MCP 安装或 Agent 关联尚未确认,请重试")
|
|
110
|
+
return targets.length ? `已安装并关联 ${targets.length} 个已接管 Agent` : "已安装,当前没有已接管的 Agent"
|
|
111
|
+
}
|
|
112
|
+
async options() {
|
|
113
|
+
const settings = (await readObject(join(this.directory, "settings.json"), true)).value
|
|
114
|
+
const providers = (await readObject(join(this.directory, "providers.json"), true)).value.providers || []
|
|
115
|
+
const managed = new Map((this.accounts.projection().native?.providers || []).filter(item => !item.off).map(item => [item.id, item]))
|
|
116
|
+
const current = typeof settings.imageGen === "string" ? settings.imageGen : ""
|
|
117
|
+
const images = [], videos = [], preferred = []
|
|
118
|
+
let catalogUnavailable = false
|
|
119
|
+
for (const provider of providers) {
|
|
120
|
+
if (provider.off || typeof provider.id !== "string") continue
|
|
121
|
+
const owned = managed.get(provider.id)
|
|
122
|
+
if (owned?.emptyCatalog) continue
|
|
123
|
+
if (!owned && !current.startsWith(provider.id + "/")) continue
|
|
124
|
+
let catalog
|
|
125
|
+
try { catalog = await this.host.readProviderCatalog(provider.id, { includeUnmanaged: !owned }) }
|
|
126
|
+
catch { catalogUnavailable = true; continue }
|
|
127
|
+
for (const model of catalog.models) {
|
|
128
|
+
const ref = provider.id + "/" + model.id
|
|
129
|
+
if (!owned && ref !== current) continue
|
|
130
|
+
const entry = { reference: ref, name: model.name || model.id, group: owned?.groupName || provider.name || provider.id }
|
|
131
|
+
const kind = settings.modelKinds?.[ref]
|
|
132
|
+
const automatic = !kind || kind === "auto"
|
|
133
|
+
if (kind === "image" || (automatic && model.draws === true && model.films !== true)) {
|
|
134
|
+
images.push(entry)
|
|
135
|
+
if (model.id === DEFAULT_IMAGE_MODEL) preferred.push(ref)
|
|
136
|
+
}
|
|
137
|
+
if (owned && (kind === "video" || (automatic && model.films === true))) videos.push(entry)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const currentAvailable = images.some(item => item.reference === current)
|
|
141
|
+
return {
|
|
142
|
+
imageModels: images,
|
|
143
|
+
catalogUnavailable,
|
|
144
|
+
selectedImageModel: preferred.includes(current) ? current : preferred[0] || (currentAvailable ? current : images.length === 1 ? images[0].reference : ""),
|
|
145
|
+
currentImageModelMissing: !!current && !currentAvailable,
|
|
146
|
+
videoModelsAvailable: videos.length,
|
|
147
|
+
videoConfigured: !!settings.videoGen,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async imageReference(imageModel = "", automatic = false) {
|
|
152
|
+
const options = await this.options()
|
|
153
|
+
const reference = imageModel || options.selectedImageModel
|
|
154
|
+
if (reference && options.imageModels.some(item => item.reference === reference)) return reference
|
|
155
|
+
if (automatic && !options.catalogUnavailable) return ""
|
|
156
|
+
if (options.imageModels.length > 1) throw new Error("请选择要使用的生图模型,再确认初始化")
|
|
157
|
+
throw new Error("尚未获取到可用生图模型,请先点击立即同步或在 Magpie 供应商页面获取模型")
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async configureAgentModels({ repairOnly = false, assertCurrent }) {
|
|
161
|
+
const providers = this.accounts.projection().native?.providers || []
|
|
162
|
+
if (!providers.length) return 0
|
|
163
|
+
const { value: disconnected } = await readObject(join(this.directory, "stash.json"), true)
|
|
164
|
+
return this.host.configureAgentModels(providers, { repairOnly, disconnected, assertCurrent })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async apply({ imageModel = "", automatic = false, assertCurrent = () => {} } = {}) {
|
|
168
|
+
const marker = this.markerStore.read()
|
|
169
|
+
marker.fields = {}
|
|
170
|
+
marker.automatic = automatic
|
|
171
|
+
const tasks = [
|
|
172
|
+
["mcp", () => this.imageMCP(assertCurrent)],
|
|
173
|
+
["imageGen", async () => {
|
|
174
|
+
const reference = await this.imageReference(imageModel, automatic)
|
|
175
|
+
if (!reference) return ""
|
|
176
|
+
assertCurrent()
|
|
177
|
+
await this.saveSettings({ imageGen: reference }, assertCurrent)
|
|
178
|
+
return "已选择 " + reference.slice(reference.indexOf("/") + 1)
|
|
179
|
+
}],
|
|
180
|
+
]
|
|
181
|
+
if (automatic) {
|
|
182
|
+
tasks.unshift(["agentModels", async () => {
|
|
183
|
+
const count = await this.configureAgentModels({ assertCurrent })
|
|
184
|
+
return count ? `已为 ${count} 个 Agent 设置 ArkFlow 模型` : "暂无需要自动设置模型的 Agent"
|
|
185
|
+
}])
|
|
186
|
+
tasks.push(
|
|
187
|
+
["agentEffort", async () => {
|
|
188
|
+
const count = await this.host.setNewSessionEffortHigh(assertCurrent)
|
|
189
|
+
return count ? `已将 ${count} 个 Agent 的新会话默认思考强度设为高` : "暂无支持高思考强度的 Agent"
|
|
190
|
+
}],
|
|
191
|
+
["automaticRoutingGroups", async () => {
|
|
192
|
+
await this.host.disableAutomaticRoutingGroups(assertCurrent)
|
|
193
|
+
return "已关闭自动创建路由组"
|
|
194
|
+
}],
|
|
195
|
+
["autostart", async () => {
|
|
196
|
+
await this.host.enableAutostart(assertCurrent)
|
|
197
|
+
return "已开启 Magpie 开机自启"
|
|
198
|
+
}],
|
|
199
|
+
["hostUpdates", async () => {
|
|
200
|
+
await this.saveSettings(UPDATE_SETTINGS, assertCurrent)
|
|
201
|
+
return "已选择每日版并开启自动更新、下载和重启"
|
|
202
|
+
}],
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
marker.status = "running"
|
|
206
|
+
for (const [id, task] of tasks) {
|
|
207
|
+
assertCurrent()
|
|
208
|
+
marker.currentTask = id
|
|
209
|
+
this.markerStore.write(marker)
|
|
210
|
+
try {
|
|
211
|
+
const message = await task()
|
|
212
|
+
marker.fields[id] = message ? { status: "success", message, ...(id === "imageGen" ? { hostValidated: true } : {}) }
|
|
213
|
+
: { status: "skipped", message: "暂无可自动选择的生图模型,可在 Magpie 设置中选择。" }
|
|
214
|
+
}
|
|
215
|
+
catch (error) { marker.fields[id] = { status: "failed", message: error.message } }
|
|
216
|
+
assertCurrent()
|
|
217
|
+
marker.updatedAt = new Date().toISOString()
|
|
218
|
+
this.markerStore.write(marker)
|
|
219
|
+
}
|
|
220
|
+
delete marker.currentTask
|
|
221
|
+
marker.status = tasks.some(([id]) => marker.fields[id]?.status === "failed") ? "partial_failure" : "complete"
|
|
222
|
+
this.markerStore.write(marker)
|
|
223
|
+
return this.status()
|
|
224
|
+
}
|
|
225
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto"
|
|
2
|
+
import { createServer } from "node:http"
|
|
3
|
+
|
|
4
|
+
export function browserLogin({ api, config, session, host }) {
|
|
5
|
+
let current, failure = ""
|
|
6
|
+
const state = () => ({ pending: !!current, url: current?.url || "", error: failure })
|
|
7
|
+
function cancel() {
|
|
8
|
+
const attempt = current
|
|
9
|
+
current = undefined
|
|
10
|
+
if (!attempt) return
|
|
11
|
+
clearTimeout(attempt.timer)
|
|
12
|
+
attempt.abort.abort()
|
|
13
|
+
attempt.server.close()
|
|
14
|
+
}
|
|
15
|
+
async function start() {
|
|
16
|
+
if (current) return state()
|
|
17
|
+
failure = ""
|
|
18
|
+
const nonce = () => randomBytes(32).toString("base64url")
|
|
19
|
+
const attempt = { verifier: nonce(), state: nonce(), owner: session.ownership(), abort: new AbortController() }
|
|
20
|
+
current = attempt
|
|
21
|
+
const signal = attempt.abort.signal
|
|
22
|
+
attempt.server = createServer(async (req, res) => {
|
|
23
|
+
res.setHeader("cache-control", "no-store")
|
|
24
|
+
res.setHeader("referrer-policy", "no-referrer")
|
|
25
|
+
res.setHeader("content-type", "text/plain; charset=utf-8")
|
|
26
|
+
let url
|
|
27
|
+
try { url = new URL(req.url, "http://127.0.0.1") } catch { res.writeHead(400).end(); return }
|
|
28
|
+
const params = url.searchParams
|
|
29
|
+
if (req.method !== "GET" || !attempt.uri || req.headers.host !== new URL(attempt.uri).host || url.pathname !== "/novaflow/callback" || current !== attempt || attempt.claimed || [...params].length !== 3 || params.get("iss") !== config.origin || params.get("state") !== attempt.state || !/^nfdc_[\w-]{43}$/.test(params.get("code") || "")) {
|
|
30
|
+
res.writeHead(400).end("授权回调无效,请返回 Magpie。")
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
attempt.claimed = true
|
|
34
|
+
let grant
|
|
35
|
+
try {
|
|
36
|
+
grant = await api.exchange({ code: params.get("code"), code_verifier: attempt.verifier, redirect_uri: attempt.uri }, signal)
|
|
37
|
+
signal.throwIfAborted()
|
|
38
|
+
if (!/^nfds_[\w-]{43}$/.test(grant.access_token) || !/^nfdr_[\w-]{43}$/.test(grant.refresh_token) || !/^nfdev_[\w-]{43}$/.test(grant.session_id)) throw new Error("Invalid grant")
|
|
39
|
+
await session.acceptLogin(grant, { owner: attempt.owner, signal })
|
|
40
|
+
res.end("ArkFlow 已连接。请返回 Magpie。")
|
|
41
|
+
} catch {
|
|
42
|
+
if (grant?.access_token) void api.revoke(grant.access_token).catch(() => {})
|
|
43
|
+
if (current === attempt) failure = "授权未完成,请重新登录。"
|
|
44
|
+
res.writeHead(400).end("授权未完成,请返回 Magpie 重试。")
|
|
45
|
+
} finally { if (current === attempt) cancel() }
|
|
46
|
+
})
|
|
47
|
+
try {
|
|
48
|
+
await new Promise((resolve, reject) => attempt.server.once("error", reject).listen(0, "127.0.0.1", resolve))
|
|
49
|
+
signal.throwIfAborted()
|
|
50
|
+
attempt.uri = `http://127.0.0.1:${attempt.server.address().port}/novaflow/callback`
|
|
51
|
+
const result = await api.startLogin({ redirect_uri: attempt.uri, state: attempt.state, device_name: "Magpie", code_challenge_method: "S256", code_challenge: createHash("sha256").update(attempt.verifier).digest("base64url") }, signal)
|
|
52
|
+
signal.throwIfAborted()
|
|
53
|
+
if (!/^nfda_[\w-]{43}$/.test(result.request_id) || result.authorize_url !== `${config.origin}/desktop/authorize?request=${result.request_id}`) throw new Error("平台授权地址无效")
|
|
54
|
+
attempt.url = result.authorize_url
|
|
55
|
+
attempt.timer = setTimeout(() => { failure = "授权已过期,请重新登录。"; cancel() }, 600_000)
|
|
56
|
+
attempt.timer.unref()
|
|
57
|
+
await host.openAuthorization(attempt.url).catch(() => {})
|
|
58
|
+
return state()
|
|
59
|
+
} catch (error) { if (current === attempt) cancel(); throw error }
|
|
60
|
+
}
|
|
61
|
+
return { start, state, cancel }
|
|
62
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { browserLogin } from "./native-auth.mjs"
|
|
2
|
+
import { bundledSkills, bundledPackage } from "./bundled-skills.mjs"
|
|
3
|
+
|
|
4
|
+
const OPERATIONS = new Set([
|
|
5
|
+
"login",
|
|
6
|
+
"cancel-login",
|
|
7
|
+
"finish-setup",
|
|
8
|
+
"retry-setup",
|
|
9
|
+
"status",
|
|
10
|
+
"sync",
|
|
11
|
+
"reset-provider",
|
|
12
|
+
"skill-store",
|
|
13
|
+
"skill-detail",
|
|
14
|
+
"install-store-skill",
|
|
15
|
+
"enterprise-guide",
|
|
16
|
+
"local-skills",
|
|
17
|
+
"agents",
|
|
18
|
+
"preview-skill",
|
|
19
|
+
"share-skill",
|
|
20
|
+
"remove-skill",
|
|
21
|
+
"logout",
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
function capability(session, name, message) {
|
|
25
|
+
authenticated(session, "请先连接 ArkFlow")
|
|
26
|
+
if (session.projection().accountMode === "enterprise" && session.projection().capabilities?.[name] === true) return
|
|
27
|
+
throw Object.assign(new Error(message), { code: "PLUGIN_CAPABILITY_DENIED", status: 403 })
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function authenticated(session, message) {
|
|
31
|
+
if (session.projection().status === "authenticated") return
|
|
32
|
+
throw Object.assign(new Error(message), { code: "PLUGIN_SESSION_REVOKED", status: 401 })
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createNativeControl({
|
|
36
|
+
config,
|
|
37
|
+
session,
|
|
38
|
+
sync,
|
|
39
|
+
accounts,
|
|
40
|
+
nativeProviders,
|
|
41
|
+
skills,
|
|
42
|
+
host,
|
|
43
|
+
api,
|
|
44
|
+
preferencesStore,
|
|
45
|
+
defaults,
|
|
46
|
+
forgetHostAuth,
|
|
47
|
+
diagnostics = {},
|
|
48
|
+
hostVersion = config.hostMinVersion,
|
|
49
|
+
}) {
|
|
50
|
+
const login = browserLogin({ api, config, session, host })
|
|
51
|
+
|
|
52
|
+
function state() {
|
|
53
|
+
const identity = session.projection()
|
|
54
|
+
const skillState = skills.projection()
|
|
55
|
+
if (identity.accountMode !== "enterprise" || !identity.capabilities?.company_skills) {
|
|
56
|
+
skillState.catalog = []
|
|
57
|
+
skillState.store = null
|
|
58
|
+
skillState.entries = (skillState.entries || []).filter(entry => entry.sourceKind === "builtin")
|
|
59
|
+
skillState.count = skillState.entries.length
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
schema_version: 1,
|
|
63
|
+
service: {
|
|
64
|
+
origin: config.origin,
|
|
65
|
+
pluginVersion: config.pluginVersion,
|
|
66
|
+
hostVersion,
|
|
67
|
+
hostMinVersion: config.hostMinVersion,
|
|
68
|
+
compatible: true,
|
|
69
|
+
diagnostics: { ...diagnostics },
|
|
70
|
+
},
|
|
71
|
+
session: session.projection(),
|
|
72
|
+
login: login.state(),
|
|
73
|
+
sync: { ...sync.projection(), skills: skillState },
|
|
74
|
+
accounts: accounts.projection(),
|
|
75
|
+
skills: skillState,
|
|
76
|
+
bundledSkills,
|
|
77
|
+
defaults: defaults.status(),
|
|
78
|
+
preferences: {},
|
|
79
|
+
hostLibrary: {
|
|
80
|
+
available: host.available === true,
|
|
81
|
+
version: host.version ?? "",
|
|
82
|
+
error: host.lastError ?? "",
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function command({ operation, payload = {}, auth = null } = {}) {
|
|
88
|
+
if (!OPERATIONS.has(operation)) {
|
|
89
|
+
throw Object.assign(new Error("Unknown ArkFlow native command"), {
|
|
90
|
+
code: "PLUGIN_COMMAND_UNKNOWN",
|
|
91
|
+
status: 400,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
if (auth) await session.activateAuth(auth)
|
|
95
|
+
switch (operation) {
|
|
96
|
+
case "login":
|
|
97
|
+
if (Object.keys(payload).length) throw Object.assign(new Error("请使用浏览器登录 ArkFlow"), { code: "PLUGIN_BROWSER_LOGIN_REQUIRED", status: 400 })
|
|
98
|
+
await login.start(); return state()
|
|
99
|
+
case "cancel-login": login.cancel(); return state()
|
|
100
|
+
case "status":
|
|
101
|
+
return state()
|
|
102
|
+
case "finish-setup":
|
|
103
|
+
case "retry-setup": {
|
|
104
|
+
authenticated(session, "请先登录 ArkFlow")
|
|
105
|
+
const setup = session.projection().setup
|
|
106
|
+
const retry = operation === "retry-setup"
|
|
107
|
+
const allowed = retry ? ["sync_error", "config_error"] : ["done", "sync_error", "config_error"]
|
|
108
|
+
if (!allowed.includes(setup?.stage) || !session.setSetupStage(payload.id, setup.stage, retry ? "sync" : null)) {
|
|
109
|
+
throw Object.assign(new Error("同步状态已变化,请刷新后重试"), { status: 409 })
|
|
110
|
+
}
|
|
111
|
+
if (retry) {
|
|
112
|
+
// A poll that began before this click may still be completing.
|
|
113
|
+
const id = setup.id
|
|
114
|
+
void Promise.resolve(sync.running).catch(() => {}).then(() => {
|
|
115
|
+
const current = session.projection().setup
|
|
116
|
+
if (current?.id === id && current.stage === "sync") return sync.syncNow("login")
|
|
117
|
+
}).catch(() => session.setSetupStage(id, "sync", "sync_error"))
|
|
118
|
+
}
|
|
119
|
+
return state()
|
|
120
|
+
}
|
|
121
|
+
case "sync": {
|
|
122
|
+
const before = session.projection()
|
|
123
|
+
const result = await sync.syncNow("native")
|
|
124
|
+
const current = session.projection()
|
|
125
|
+
if (result.status === "ready" && current.status === "authenticated" && !before.setup && !current.setup && before.generation === current.generation) {
|
|
126
|
+
const owner = session.ownership()
|
|
127
|
+
await defaults.configureAgentModels({ repairOnly: true, assertCurrent: () => session.assertOwnership(owner) })
|
|
128
|
+
}
|
|
129
|
+
return state()
|
|
130
|
+
}
|
|
131
|
+
case "reset-provider": {
|
|
132
|
+
authenticated(session, "请先登录 ArkFlow")
|
|
133
|
+
const { providerId: id, revision } = payload
|
|
134
|
+
if (typeof id !== "string" || !/^novaflow-key-[a-f0-9]{20}$/.test(id) || typeof revision !== "string" || !/^[a-f0-9]{64}$/.test(revision)) {
|
|
135
|
+
throw Object.assign(new Error("请从同步失败列表重新选择分组"), { status: 400 })
|
|
136
|
+
}
|
|
137
|
+
const result = await sync.syncNow("provider-reset", { id, revision })
|
|
138
|
+
if (!result.resetApplied) throw Object.assign(new Error(result.resetStale ? "分组配置或授权已变化,请重新同步后再确认重置" : "分组重置未完成,请检查连接后重试"), { status: 409 })
|
|
139
|
+
return { state: state(), result: { modelSyncFailed: result.accounts.native.failures.some(item => item.id === id) } }
|
|
140
|
+
}
|
|
141
|
+
case "skill-store":
|
|
142
|
+
authenticated(session, "Sign in to ArkFlow before opening the skill store")
|
|
143
|
+
capability(session, "company_skills", "The company store requires an active enterprise account")
|
|
144
|
+
await skills.refreshStore()
|
|
145
|
+
return state()
|
|
146
|
+
case "skill-detail":
|
|
147
|
+
if (payload.sourceKind === "builtin") {
|
|
148
|
+
const { skill, version } = await bundledPackage(payload.skillId)
|
|
149
|
+
return { skill, versions: [version] }
|
|
150
|
+
}
|
|
151
|
+
authenticated(session, "Sign in to ArkFlow before opening a skill")
|
|
152
|
+
capability(session, "company_skills", "The company store requires an active enterprise account")
|
|
153
|
+
if (String(payload.sourceKind ?? "") !== "company") throw Object.assign(new Error("Platform skill recommendations have been retired"), { code: "PLUGIN_CAPABILITY_DENIED", status: 403 })
|
|
154
|
+
return skills.storeDetail({
|
|
155
|
+
sourceKind: String(payload.sourceKind ?? ""),
|
|
156
|
+
skillId: String(payload.skillId ?? ""),
|
|
157
|
+
})
|
|
158
|
+
case "install-store-skill": {
|
|
159
|
+
if (payload.sourceKind === "builtin") {
|
|
160
|
+
const entry = await skills.install({ ...await bundledPackage(payload.skillId), sourceKind: "builtin" })
|
|
161
|
+
if (entry.registration !== "registered") throw new Error(entry.registrationError?.message || "技能登记失败")
|
|
162
|
+
return state()
|
|
163
|
+
}
|
|
164
|
+
authenticated(session, "Sign in to ArkFlow before installing a skill")
|
|
165
|
+
const sourceKind = String(payload.sourceKind ?? "")
|
|
166
|
+
capability(session, "company_skills", "Company skills require an active enterprise account")
|
|
167
|
+
if (sourceKind !== "company") throw Object.assign(new Error("Platform skill recommendations have been retired"), { code: "PLUGIN_CAPABILITY_DENIED", status: 403 })
|
|
168
|
+
const installed = await skills.installFromStore({
|
|
169
|
+
sourceKind,
|
|
170
|
+
skillId: String(payload.skillId ?? ""),
|
|
171
|
+
targetAgents: [],
|
|
172
|
+
})
|
|
173
|
+
if (installed?.registration !== "registered") {
|
|
174
|
+
throw Object.assign(new Error(installed?.registrationError?.message || "技能已下载,但尚未登记到 Magpie 资料库,请重试安装"), {
|
|
175
|
+
code: "PLUGIN_SKILL_REGISTRATION_FAILED", status: 409,
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
return state()
|
|
179
|
+
}
|
|
180
|
+
case "enterprise-guide":
|
|
181
|
+
authenticated(session, "请先连接 ArkFlow")
|
|
182
|
+
await host.openEnterpriseGuide()
|
|
183
|
+
return { opened: true }
|
|
184
|
+
case "local-skills":
|
|
185
|
+
return { skills: await host.listSkills() }
|
|
186
|
+
case "agents":
|
|
187
|
+
capability(session, "company_skills", "企业用户才可使用技能功能")
|
|
188
|
+
return { agents: await host.listAgents() }
|
|
189
|
+
case "preview-skill":
|
|
190
|
+
capability(session, "contribute_skills", "This account cannot contribute company skills")
|
|
191
|
+
return skills.previewShare({
|
|
192
|
+
sourceName: String(payload.sourceName ?? ""),
|
|
193
|
+
})
|
|
194
|
+
case "share-skill":
|
|
195
|
+
capability(session, "contribute_skills", "This account cannot contribute company skills")
|
|
196
|
+
return skills.share({
|
|
197
|
+
sourceName: String(payload.sourceName ?? ""),
|
|
198
|
+
display_name: String(payload.display_name ?? ""),
|
|
199
|
+
description: payload.description === undefined ? undefined : String(payload.description),
|
|
200
|
+
category_id: String(payload.category_id ?? ""),
|
|
201
|
+
updateSkillId: payload.updateSkillId ? String(payload.updateSkillId) : "",
|
|
202
|
+
expectedVersion: Number(payload.expectedVersion ?? 0),
|
|
203
|
+
idempotencyKey: String(payload.idempotencyKey ?? ""),
|
|
204
|
+
previewHash: String(payload.previewHash || ""),
|
|
205
|
+
})
|
|
206
|
+
case "remove-skill": {
|
|
207
|
+
capability(session, "company_skills", "企业用户才可使用技能功能")
|
|
208
|
+
const skillId = String(payload.skillId ?? "")
|
|
209
|
+
const entry = skills.registry[skillId]
|
|
210
|
+
if (!entry?.alias || !/^nf-[a-f0-9]{8}-[a-z0-9][a-z0-9_-]{0,60}$/.test(entry.alias)) {
|
|
211
|
+
throw Object.assign(new Error("Managed company skill was not found"), {
|
|
212
|
+
code: "PLUGIN_SKILL_NOT_FOUND",
|
|
213
|
+
status: 404,
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
const removed = await host.removeSkill(entry.alias)
|
|
217
|
+
entry.registration = removed.registered ? "failed" : "removed"
|
|
218
|
+
skills.persist()
|
|
219
|
+
return state()
|
|
220
|
+
}
|
|
221
|
+
case "logout": {
|
|
222
|
+
login.cancel()
|
|
223
|
+
const result = await session.logout()
|
|
224
|
+
await nativeProviders?.clear()
|
|
225
|
+
if (forgetHostAuth) await forgetHostAuth()
|
|
226
|
+
accounts.disposeOwnedOnly()
|
|
227
|
+
sync.stop("ArkFlow signed out")
|
|
228
|
+
return { result, state: state() }
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return { command, stop: login.cancel }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { OPERATIONS }
|