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,226 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { unzipSync, deflateRawSync, inflateRawSync } from "node:zlib"
|
|
3
|
+
|
|
4
|
+
const MAX_FILES = 2_000
|
|
5
|
+
const MAX_EXPANDED = 64 << 20
|
|
6
|
+
const MAX_COMPRESSION_RATIO = 100
|
|
7
|
+
|
|
8
|
+
const CRC_TABLE = (() => {
|
|
9
|
+
const table = new Uint32Array(256)
|
|
10
|
+
for (let i = 0; i < 256; i++) {
|
|
11
|
+
let x = i
|
|
12
|
+
for (let k = 0; k < 8; k++) x = x & 1 ? 0xedb88320 ^ (x >>> 1) : x >>> 1
|
|
13
|
+
table[i] = x >>> 0
|
|
14
|
+
}
|
|
15
|
+
return table
|
|
16
|
+
})()
|
|
17
|
+
|
|
18
|
+
function crc32(bytes) {
|
|
19
|
+
let crc = 0xffffffff
|
|
20
|
+
for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)
|
|
21
|
+
return (crc ^ 0xffffffff) >>> 0
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function normalizeZipPath(raw) {
|
|
25
|
+
const path = String(raw ?? "")
|
|
26
|
+
if (!path || path.includes("\0") || path.includes("\\") || path.startsWith("/") || /^[A-Za-z]:/.test(path)) {
|
|
27
|
+
throw new Error("Skill package path is invalid")
|
|
28
|
+
}
|
|
29
|
+
const parts = path.split("/")
|
|
30
|
+
if (parts.some((part) => part === "" || part === "." || part === "..")) throw new Error("Skill package path is invalid")
|
|
31
|
+
return path
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function parseZip(bytes) {
|
|
35
|
+
const buffer = bytes instanceof Uint8Array ? Buffer.from(bytes) : Buffer.from(String(bytes))
|
|
36
|
+
if (buffer.length < 22) throw new Error("Invalid skill package")
|
|
37
|
+
let end = -1
|
|
38
|
+
const start = Math.max(0, buffer.length - 66_000)
|
|
39
|
+
for (let i = buffer.length - 22; i >= start; i--) {
|
|
40
|
+
if (buffer.readUInt32LE(i) === 0x06054b50) {
|
|
41
|
+
end = i
|
|
42
|
+
break
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (end < 0) throw new Error("Invalid skill package")
|
|
46
|
+
const count = buffer.readUInt16LE(end + 10)
|
|
47
|
+
let offset = buffer.readUInt32LE(end + 16)
|
|
48
|
+
if (count === 0xffff || offset === 0xffffffff) throw new Error("Zip64 skill packages are not supported")
|
|
49
|
+
const entries = []
|
|
50
|
+
let expanded = 0
|
|
51
|
+
for (let index = 0; index < count; index++) {
|
|
52
|
+
if (offset + 46 > buffer.length || buffer.readUInt32LE(offset) !== 0x02014b50) throw new Error("Invalid skill package")
|
|
53
|
+
const centralOffset = offset
|
|
54
|
+
const versionMade = buffer.readUInt16LE(offset + 8)
|
|
55
|
+
const flags = buffer.readUInt16LE(offset + 6)
|
|
56
|
+
const method = buffer.readUInt16LE(offset + 10)
|
|
57
|
+
const compressedSize = buffer.readUInt32LE(offset + 20)
|
|
58
|
+
const uncompressedSize = buffer.readUInt32LE(offset + 24)
|
|
59
|
+
const nameLength = buffer.readUInt16LE(offset + 28)
|
|
60
|
+
const extraLength = buffer.readUInt16LE(offset + 30)
|
|
61
|
+
const commentLength = buffer.readUInt16LE(offset + 32)
|
|
62
|
+
const external = buffer.readUInt32LE(offset + 38)
|
|
63
|
+
const localOffset = buffer.readUInt32LE(offset + 42)
|
|
64
|
+
const nameEnd = offset + 46 + nameLength
|
|
65
|
+
const name = buffer.subarray(offset + 46, nameEnd).toString("utf8")
|
|
66
|
+
offset = nameEnd + extraLength + commentLength
|
|
67
|
+
if ((versionMade >>> 8) === 3 && ((external >>> 16) & 0o170000) === 0o120000) throw new Error("Skill package contains a symbolic link")
|
|
68
|
+
if (flags & 0x0001) throw new Error("Encrypted skill packages are not supported")
|
|
69
|
+
if (method !== 0 && method !== 8) throw new Error("Skill package uses an unsupported compression method")
|
|
70
|
+
expanded += uncompressedSize
|
|
71
|
+
if (entries.length >= MAX_FILES || expanded > MAX_EXPANDED) throw new Error("Skill package expands beyond its limits")
|
|
72
|
+
if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== 0x04034b50) throw new Error("Invalid skill package")
|
|
73
|
+
const localNameLength = buffer.readUInt16LE(localOffset + 26)
|
|
74
|
+
const localExtraLength = buffer.readUInt16LE(localOffset + 28)
|
|
75
|
+
const dataStart = localOffset + 30 + localNameLength + localExtraLength
|
|
76
|
+
const dataEnd = dataStart + compressedSize
|
|
77
|
+
if (dataEnd > buffer.length) throw new Error("Invalid skill package")
|
|
78
|
+
const raw = buffer.subarray(dataStart, dataEnd)
|
|
79
|
+
let content
|
|
80
|
+
try {
|
|
81
|
+
content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(1, uncompressedSize) })
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
throw new Error("Invalid skill package", { cause })
|
|
84
|
+
}
|
|
85
|
+
if (content.length !== uncompressedSize) throw new Error("Skill package manifest mismatch")
|
|
86
|
+
if (compressedSize > 0 && uncompressedSize / compressedSize > MAX_COMPRESSION_RATIO) {
|
|
87
|
+
throw new Error("Skill package exceeds the compression ratio limit")
|
|
88
|
+
}
|
|
89
|
+
if (crc32(content) !== buffer.readUInt32LE(centralOffset + 16)) {
|
|
90
|
+
throw new Error("Skill package CRC mismatch")
|
|
91
|
+
}
|
|
92
|
+
if (name.endsWith("/")) continue
|
|
93
|
+
entries.push({ path: normalizeZipPath(name), bytes: content })
|
|
94
|
+
}
|
|
95
|
+
const seen = new Map()
|
|
96
|
+
for (const entry of entries) {
|
|
97
|
+
const lowered = entry.path.toLowerCase()
|
|
98
|
+
if (seen.has(lowered)) throw new Error("Skill package contains a case-insensitive path collision")
|
|
99
|
+
seen.set(lowered, entry.path)
|
|
100
|
+
}
|
|
101
|
+
return entries.sort((a, b) => a.path.localeCompare(b.path))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function createZip(files) {
|
|
105
|
+
const normalized = [...files]
|
|
106
|
+
.map((file) => ({ path: normalizeZipPath(file.path), bytes: Buffer.from(file.bytes ?? "") }))
|
|
107
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
108
|
+
const localParts = []
|
|
109
|
+
const centralParts = []
|
|
110
|
+
let offset = 0
|
|
111
|
+
for (const file of normalized) {
|
|
112
|
+
const name = Buffer.from(file.path, "utf8")
|
|
113
|
+
const compressed = deflateRawSync(file.bytes, { level: 9 })
|
|
114
|
+
const method = compressed.length < file.bytes.length ? 8 : 0
|
|
115
|
+
const stored = method === 8 ? compressed : file.bytes
|
|
116
|
+
const crc = crc32(file.bytes)
|
|
117
|
+
const local = Buffer.alloc(30)
|
|
118
|
+
local.writeUInt32LE(0x04034b50, 0)
|
|
119
|
+
local.writeUInt16LE(20, 4)
|
|
120
|
+
local.writeUInt16LE(0x0800, 6)
|
|
121
|
+
local.writeUInt16LE(method, 8)
|
|
122
|
+
local.writeUInt16LE(0x0021, 12)
|
|
123
|
+
local.writeUInt32LE(crc, 14)
|
|
124
|
+
local.writeUInt32LE(stored.length, 18)
|
|
125
|
+
local.writeUInt32LE(file.bytes.length, 22)
|
|
126
|
+
local.writeUInt16LE(name.length, 26)
|
|
127
|
+
local.writeUInt16LE(0, 28)
|
|
128
|
+
localParts.push(local, name, stored)
|
|
129
|
+
const central = Buffer.alloc(46)
|
|
130
|
+
central.writeUInt32LE(0x02014b50, 0)
|
|
131
|
+
central.writeUInt16LE(0x031e, 4)
|
|
132
|
+
local.copy(central, 6, 4)
|
|
133
|
+
central.writeUInt32LE((0o100644 << 16) >>> 0, 38)
|
|
134
|
+
central.writeUInt32LE(offset, 42)
|
|
135
|
+
centralParts.push(central, name)
|
|
136
|
+
offset += local.length + name.length + stored.length
|
|
137
|
+
}
|
|
138
|
+
const central = Buffer.concat(centralParts)
|
|
139
|
+
const end = Buffer.alloc(22)
|
|
140
|
+
end.writeUInt32LE(0x06054b50, 0)
|
|
141
|
+
end.writeUInt16LE(normalized.length, 8)
|
|
142
|
+
end.writeUInt16LE(normalized.length, 10)
|
|
143
|
+
end.writeUInt32LE(central.length, 12)
|
|
144
|
+
end.writeUInt32LE(offset, 16)
|
|
145
|
+
return Buffer.concat([...localParts, central, end])
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function effectivePath(path, entries) {
|
|
149
|
+
const first = String(path ?? "").split("/")[0]
|
|
150
|
+
const allUnderOne = entries.length > 0 && entries.every((entry) => entry.path.startsWith(first + "/"))
|
|
151
|
+
if (!allUnderOne) return path
|
|
152
|
+
const hasRootSkill = entries.some((entry) => entry.path === "SKILL.md")
|
|
153
|
+
return hasRootSkill ? path : path.slice(first.length + 1)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function validatePackageEntries(entries) {
|
|
157
|
+
if (!entries.length) throw new Error("Skill package is empty")
|
|
158
|
+
const normalized = entries.map((entry) => ({ ...entry, path: effectivePath(entry.path, entries) }))
|
|
159
|
+
const rootSkills = normalized.filter((entry) => entry.path === "SKILL.md")
|
|
160
|
+
if (rootSkills.length !== 1) throw new Error("Skill package needs exactly one root SKILL.md")
|
|
161
|
+
const seen = new Set()
|
|
162
|
+
for (const entry of normalized) {
|
|
163
|
+
if (seen.has(entry.path.toLowerCase())) throw new Error("Skill package contains a case-insensitive path collision")
|
|
164
|
+
seen.add(entry.path.toLowerCase())
|
|
165
|
+
}
|
|
166
|
+
return normalized.sort((a, b) => {
|
|
167
|
+
if (a.path === "SKILL.md") return -1
|
|
168
|
+
if (b.path === "SKILL.md") return 1
|
|
169
|
+
return a.path.localeCompare(b.path)
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function manifestFor(entries) {
|
|
174
|
+
return validatePackageEntries(entries).map((entry) => ({
|
|
175
|
+
path: entry.path,
|
|
176
|
+
size: entry.bytes.length,
|
|
177
|
+
sha256: createHash("sha256").update(entry.bytes).digest("hex"),
|
|
178
|
+
}))
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function hashSkillManifest(manifest) {
|
|
182
|
+
const rows = manifest.map(file => [file.path, file.sha256]).sort((a, b) => {
|
|
183
|
+
if (a[0] === b[0]) return 0
|
|
184
|
+
if (a[0] === "SKILL.md") return -1
|
|
185
|
+
if (b[0] === "SKILL.md") return 1
|
|
186
|
+
return a[0].localeCompare(b[0])
|
|
187
|
+
})
|
|
188
|
+
return "sha256:" + createHash("sha256").update(JSON.stringify(rows)).digest("hex")
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function verifyDownloadedPackage(bytes, { packageHash, manifest }) {
|
|
192
|
+
const actual = "sha256:" + createHash("sha256").update(bytes).digest("hex")
|
|
193
|
+
if (packageHash && packageHash !== actual) throw new Error("Skill package hash does not match")
|
|
194
|
+
const entries = parseZip(bytes)
|
|
195
|
+
const normalized = validatePackageEntries(entries)
|
|
196
|
+
const generated = manifestFor(normalized)
|
|
197
|
+
if (!Array.isArray(manifest) || manifest.length !== generated.length) throw new Error("Skill package manifest mismatch")
|
|
198
|
+
const expectedByPath = new Map()
|
|
199
|
+
const seen = new Set()
|
|
200
|
+
for (const file of manifest) {
|
|
201
|
+
const path = normalizeZipPath(file?.path)
|
|
202
|
+
const lowered = path.toLowerCase()
|
|
203
|
+
if (seen.has(lowered)) throw new Error("Skill package manifest mismatch")
|
|
204
|
+
seen.add(lowered)
|
|
205
|
+
expectedByPath.set(path, file)
|
|
206
|
+
}
|
|
207
|
+
for (const file of generated) {
|
|
208
|
+
const expected = expectedByPath.get(file.path)
|
|
209
|
+
if (!expected || file.size !== expected.size || file.sha256 !== expected.sha256) {
|
|
210
|
+
throw new Error("Skill package manifest mismatch")
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { hash: actual, entries: normalized, manifest: generated }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export async function buildShareablePackage(sourceDirectory, fileReader) {
|
|
217
|
+
const files = typeof fileReader === "function" ? await fileReader(sourceDirectory) : sourceDirectory
|
|
218
|
+
const normalized = validatePackageEntries(files.files ?? files)
|
|
219
|
+
return {
|
|
220
|
+
bytes: createZip(normalized),
|
|
221
|
+
manifest: manifestFor(normalized),
|
|
222
|
+
excluded: files.excluded ?? [],
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export { unzipSync }
|
package/src/skills.mjs
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
import { buildShareablePackage, verifyDownloadedPackage, hashSkillManifest as manifestHash } from "./skill-packages.mjs"
|
|
5
|
+
import { JsonStore, randomId } from "./state-store.mjs"
|
|
6
|
+
import { LIBRARY_SKILL_RE } from "./host-adapter.mjs"
|
|
7
|
+
import { skillDescription } from "./skill-metadata.mjs"
|
|
8
|
+
import { PLUGIN_VERSION } from "./config.mjs"
|
|
9
|
+
|
|
10
|
+
function aliasFor(companyId, slug) {
|
|
11
|
+
const name = String(slug ?? "")
|
|
12
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(name)) throw new Error("Skill slug is invalid")
|
|
13
|
+
return name
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function directoryHash(root) {
|
|
17
|
+
const rows = []
|
|
18
|
+
async function walk(directory, prefix) {
|
|
19
|
+
const entries = await readdir(directory, { withFileTypes: true })
|
|
20
|
+
entries.sort((a, b) => a.name.localeCompare(b.name))
|
|
21
|
+
for (const entry of entries) {
|
|
22
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name
|
|
23
|
+
const absolute = join(directory, entry.name)
|
|
24
|
+
if (entry.isDirectory()) await walk(absolute, path)
|
|
25
|
+
else if (entry.isFile()) rows.push([path, createHash("sha256").update(await readFile(absolute)).digest("hex")])
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
await walk(root, "")
|
|
29
|
+
return manifestHash(rows.map(([path, sha256]) => ({ path, sha256 })))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class SkillManager {
|
|
33
|
+
constructor({ dataDir, host, api, session, store, now = () => new Date() }) {
|
|
34
|
+
this.host = host
|
|
35
|
+
this.api = api
|
|
36
|
+
this.session = session
|
|
37
|
+
this.now = now
|
|
38
|
+
this.root = join(dataDir, "company-skills")
|
|
39
|
+
this.backups = join(dataDir, "skill-backups")
|
|
40
|
+
this.store = store ?? new JsonStore(join(dataDir, "skill-registry.json"), { entries: {} })
|
|
41
|
+
this.data = this.store.read()
|
|
42
|
+
this.registry = this.data.entries ?? {}
|
|
43
|
+
this.storeCatalog = this.data.store ?? null
|
|
44
|
+
this.storeScope = this.data.storeScope ?? ""
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
projection() {
|
|
48
|
+
return {
|
|
49
|
+
entries: Object.entries(this.registry).filter(([, entry]) => ["builtin", "platform"].includes(entry.sourceKind) || String(entry.companyId) === String(this.session.projection?.().company?.id ?? "__none")).map(([skillId, entry]) => ({
|
|
50
|
+
skillId,
|
|
51
|
+
sourceKind: entry.sourceKind || "company",
|
|
52
|
+
slug: entry.slug,
|
|
53
|
+
alias: entry.alias,
|
|
54
|
+
version: entry.version,
|
|
55
|
+
download: entry.download,
|
|
56
|
+
registration: entry.registration,
|
|
57
|
+
registrationError: entry.registrationError,
|
|
58
|
+
availability: entry.availability,
|
|
59
|
+
remoteAvailability: entry.remoteAvailability,
|
|
60
|
+
displayName: entry.displayName,
|
|
61
|
+
description: entry.description,
|
|
62
|
+
publisher: entry.publisher,
|
|
63
|
+
categoryId: entry.categoryId,
|
|
64
|
+
categoryName: entry.categoryName,
|
|
65
|
+
companyId: entry.companyId,
|
|
66
|
+
updatedAt: entry.updatedAt,
|
|
67
|
+
})),
|
|
68
|
+
count: Object.keys(this.registry).length,
|
|
69
|
+
catalog: this.storeScope === this.scope() ? this.catalogProjection ?? [] : [],
|
|
70
|
+
store: this.storeScope === this.scope() ? this.storeCatalog : null,
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
scope() {
|
|
75
|
+
const identity = this.session.projection?.() ?? {}
|
|
76
|
+
return [identity.userId, identity.accountMode, identity.company?.id].map((value) => String(value ?? "")).join(":")
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
persist() {
|
|
80
|
+
this.data = { ...this.data, entries: this.registry, store: this.storeCatalog, storeScope: this.storeScope }
|
|
81
|
+
this.store.write(this.data)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
restoreCatalog(catalog) {
|
|
85
|
+
this.catalogProjection = Array.isArray(catalog) ? catalog : []
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
restoreStore(store) {
|
|
89
|
+
if (store && typeof store === "object") this.storeCatalog = store
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async refreshStore(signal) {
|
|
93
|
+
if (this.api.catalog) {
|
|
94
|
+
if (this.refreshing) return this.refreshing
|
|
95
|
+
this.refreshing = this.refreshCompany(signal).finally(() => { this.refreshing = null })
|
|
96
|
+
return this.refreshing
|
|
97
|
+
}
|
|
98
|
+
const generation = this.session.generation
|
|
99
|
+
const scope = this.scope()
|
|
100
|
+
if (scope !== this.storeScope) {
|
|
101
|
+
this.storeCatalog = null
|
|
102
|
+
this.catalogProjection = []
|
|
103
|
+
}
|
|
104
|
+
const store = await this.session.withAccess((access) => this.api.skillStore(access, signal), { signal })
|
|
105
|
+
if (!store || store.schema_version !== 1 || !Array.isArray(store.recommended) || !Array.isArray(store.company)) {
|
|
106
|
+
throw Object.assign(new Error("ArkFlow skill store response is invalid"), { code: "SKILL_STORE_INVALID" })
|
|
107
|
+
}
|
|
108
|
+
if (generation !== this.session.generation || scope !== this.scope()) throw new Error("Account changed while loading skills")
|
|
109
|
+
this.storeScope = scope
|
|
110
|
+
this.storeCatalog = { ...store, recommended: [], categories: Array.isArray(store.categories) ? store.categories : [] }
|
|
111
|
+
await this.applyCatalog({ skills: store.company })
|
|
112
|
+
return this.storeCatalog
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async refreshCompany(signal) {
|
|
116
|
+
const owner = this.session.ownership(), scope = this.scope()
|
|
117
|
+
const check = () => { signal?.throwIfAborted(); this.session.assertOwnership(owner); if (this.scope() !== scope) throw new Error("公司身份已变更") }
|
|
118
|
+
const cache = this.data.companyCache
|
|
119
|
+
const hit = cache?.scope === scope && cache.owner === owner && cache.catalog?.skills
|
|
120
|
+
const fetched = await this.session.withAccess(access => this.api.catalog(access, hit ? cache.etag : "", signal))
|
|
121
|
+
const catalog = fetched.notModified && hit ? cache.catalog : fetched.catalog
|
|
122
|
+
const delivery = fetched.response.headers.get("x-novaflow-delivery")
|
|
123
|
+
check()
|
|
124
|
+
if (!delivery || catalog?.scope !== `company:${this.session.projection().company?.id}` || catalog.schema_version !== 1 || !Array.isArray(catalog.skills) || !Array.isArray(catalog.categories) || !/^sha256:[a-f0-9]{64}$/.test(catalog.revision)) throw new Error("公司技能目录无效")
|
|
125
|
+
const ids = new Set()
|
|
126
|
+
for (const item of catalog.skills) {
|
|
127
|
+
if (!/^skl_[a-f0-9]{16}$/.test(item?.skill_id) || ids.has(item.skill_id) || !/^sha256:[a-f0-9]{64}$/.test(item.package_hash) || !Number.isSafeInteger(item.current_version) || item.current_version < 1 || !Number.isSafeInteger(item.size_bytes) || item.size_bytes < 1) throw new Error("公司技能条目无效")
|
|
128
|
+
ids.add(item.skill_id)
|
|
129
|
+
}
|
|
130
|
+
let metadata = hit && fetched.notModified ? cache.metadata : null
|
|
131
|
+
if (!metadata) {
|
|
132
|
+
metadata = {}
|
|
133
|
+
const seen = new Set()
|
|
134
|
+
let cursor = ""
|
|
135
|
+
do {
|
|
136
|
+
const page = await this.session.withAccess(access => this.api.skills(access, cursor, signal))
|
|
137
|
+
for (const item of page.items) metadata[this.validSkillID(item.skill_id)] = { publisher: item.owner_display_name, is_mine: item.is_mine, category_name: item.category_name }
|
|
138
|
+
cursor = page.next || ""
|
|
139
|
+
if (seen.has(cursor)) throw new Error("公司技能分页无效")
|
|
140
|
+
seen.add(cursor)
|
|
141
|
+
} while (cursor)
|
|
142
|
+
}
|
|
143
|
+
check()
|
|
144
|
+
const company = catalog.skills.map(skill => ({ ...metadata[skill.skill_id], ...skill, source_kind: "company" }))
|
|
145
|
+
this.storeScope = scope
|
|
146
|
+
this.storeCatalog = { schema_version: 1, categories: catalog.categories, company, recommended: [] }
|
|
147
|
+
this.data.companyCache = { scope, owner, etag: fetched.response.headers.get("etag"), catalog, metadata }
|
|
148
|
+
await this.applyCatalog({ skills: company, revision: catalog.revision })
|
|
149
|
+
let reason = ""
|
|
150
|
+
for (const skill of company) {
|
|
151
|
+
check()
|
|
152
|
+
if (skill.sync_mode === "on_demand") continue
|
|
153
|
+
if (skill.sync_mode !== "automatic") { reason ||= "unsupported"; continue }
|
|
154
|
+
try {
|
|
155
|
+
const previous = this.registry[skill.skill_id]
|
|
156
|
+
if (previous?.registration === "registered" && previous.packageHash === skill.package_hash && previous.version === skill.current_version && await this.host.registeredHash(previous.alias) === previous.manifestHash) continue
|
|
157
|
+
const installed = await this.installFromStore({ sourceKind: "company", skillId: skill.skill_id, signal, target: skill })
|
|
158
|
+
if (installed.registration !== "registered") throw Object.assign(new Error(), { reason: installed.registrationError?.code?.includes("CONFLICT") ? "name_conflict" : "install_failed" })
|
|
159
|
+
} catch (error) {
|
|
160
|
+
check()
|
|
161
|
+
reason ||= error.reason || (error.code === "SKILL_NAME_CONFLICT" ? "name_conflict" : "download_failed")
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
check()
|
|
165
|
+
const previous = this.data.companyReceipt, status = reason ? "failed" : "success"
|
|
166
|
+
const sequence = previous?.delivery_id === delivery ? previous.sequence + Number(previous.status !== status || (previous.reason || "") !== reason || previous.client_version !== PLUGIN_VERSION) : 1
|
|
167
|
+
const receipt = { delivery_id: delivery, revision: catalog.revision, client_version: PLUGIN_VERSION, sequence, status, ...(reason ? { reason } : {}) }
|
|
168
|
+
this.data.companyReceipt = receipt
|
|
169
|
+
this.persist()
|
|
170
|
+
await this.session.withAccess(access => this.api.skillReceipt(access, receipt, signal))
|
|
171
|
+
if (reason) throw Object.assign(new Error("部分公司技能未完成安装"), { code: reason })
|
|
172
|
+
return this.storeCatalog
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async storeDetail({ sourceKind, skillId, signal } = {}) {
|
|
176
|
+
const source = this.validSourceKind(sourceKind)
|
|
177
|
+
const id = this.validSkillID(skillId)
|
|
178
|
+
if (this.api.catalog) {
|
|
179
|
+
const data = await this.session.withAccess(access => this.api.skill(access, id, signal))
|
|
180
|
+
if (data?.skill_id !== id || !Array.isArray(data.versions)) throw new Error("公司技能详情无效")
|
|
181
|
+
return { skill: { ...data, publisher: data.owner_display_name }, versions: data.versions }
|
|
182
|
+
}
|
|
183
|
+
const detail = await this.session.withAccess(
|
|
184
|
+
(access) => this.api.skillStoreDetail(access, source, id, signal),
|
|
185
|
+
{ signal },
|
|
186
|
+
)
|
|
187
|
+
if (!detail || detail.skill?.skill_id !== id || !Array.isArray(detail.versions)) {
|
|
188
|
+
throw Object.assign(new Error("ArkFlow skill detail response is invalid"), { code: "SKILL_STORE_INVALID" })
|
|
189
|
+
}
|
|
190
|
+
return detail
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async installFromStore({ sourceKind, skillId, targetAgents = [], signal, target } = {}) {
|
|
194
|
+
const source = this.validSourceKind(sourceKind)
|
|
195
|
+
const id = this.validSkillID(skillId)
|
|
196
|
+
const generation = this.session.generation
|
|
197
|
+
const detail = await this.storeDetail({ sourceKind: source, skillId: id, signal })
|
|
198
|
+
const version = detail.versions.find((item) => Number(item.version) === Number(detail.skill.current_version))
|
|
199
|
+
if (!version) throw Object.assign(new Error("The current skill version is unavailable"), { code: "SKILL_VERSION_NOT_FOUND" })
|
|
200
|
+
if (target && (version.version !== target.current_version || version.package_hash !== target.package_hash || version.size_bytes !== target.size_bytes)) throw Object.assign(new Error("目录版本已变化"), { reason: "hash_mismatch" })
|
|
201
|
+
const downloaded = await this.session.withAccess(
|
|
202
|
+
(access) => this.api.catalog ? this.api.downloadSkill(access, id, version.version, signal) : this.api.downloadSkillStoreVersion(access, source, id, version.version, signal),
|
|
203
|
+
{ signal },
|
|
204
|
+
)
|
|
205
|
+
if (generation !== this.session.generation) throw new Error("Account changed while downloading skill")
|
|
206
|
+
if (this.api.catalog && (downloaded.bytes.length !== version.size_bytes || downloaded.response.headers.get("x-novaflow-package-hash") !== version.package_hash)) throw Object.assign(new Error("技能包校验失败"), { reason: "hash_mismatch" })
|
|
207
|
+
const aliasOwner = source === "platform" ? "platform" : this.session.projection().company?.id
|
|
208
|
+
if (!aliasOwner) throw new Error("Company identity is unavailable")
|
|
209
|
+
return this.install({
|
|
210
|
+
skill: {
|
|
211
|
+
...detail.skill,
|
|
212
|
+
company_id: aliasOwner,
|
|
213
|
+
},
|
|
214
|
+
version,
|
|
215
|
+
packageBytes: downloaded.bytes,
|
|
216
|
+
manifest: version.files,
|
|
217
|
+
targetAgents, signal, scope: this.scope(),
|
|
218
|
+
sourceKind: source,
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
validSourceKind(value) {
|
|
223
|
+
const source = String(value ?? "").trim().toLowerCase()
|
|
224
|
+
if (source !== "platform" && source !== "company") throw new Error("Invalid skill store source")
|
|
225
|
+
return source
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
validSkillID(value) {
|
|
229
|
+
const id = String(value ?? "").trim()
|
|
230
|
+
if (!/^skl_[A-Za-z0-9_-]{8,80}$/.test(id)) throw new Error("Invalid skill id")
|
|
231
|
+
return id
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async ensureDirectories() {
|
|
235
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 })
|
|
236
|
+
await mkdir(this.backups, { recursive: true, mode: 0o700 })
|
|
237
|
+
await chmod(this.root, 0o700)
|
|
238
|
+
await chmod(this.backups, 0o700)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async install(input) {
|
|
242
|
+
const pending = (this.installing || Promise.resolve()).catch(() => {}).then(() => this.installOne(input))
|
|
243
|
+
this.installing = pending
|
|
244
|
+
return pending
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async installOne({ skill, version, packageBytes, manifest, targetAgents = [], sourceKind = "company", signal, scope }) {
|
|
248
|
+
const check = () => { signal?.throwIfAborted(); if (scope && scope !== this.scope()) throw new Error("公司身份已变更") }
|
|
249
|
+
check()
|
|
250
|
+
await this.ensureDirectories()
|
|
251
|
+
const companyId = String(skill.company_id ?? skill.companyId ?? "")
|
|
252
|
+
const previous = this.registry[skill.skill_id]
|
|
253
|
+
// Existing registrations retain their Agent references until explicitly
|
|
254
|
+
// removed. Only fresh/reinstalled registrations adopt the unprefixed name.
|
|
255
|
+
const owned = previous && (previous.sourceKind || "company") === sourceKind && (!previous.companyId || previous.companyId === companyId)
|
|
256
|
+
const plainName = aliasFor(companyId, skill.slug)
|
|
257
|
+
let alias = owned && previous.registration === "registered" ? previous.alias : plainName
|
|
258
|
+
if (alias !== plainName && this.host.listSkills) {
|
|
259
|
+
const listed = await this.host.listSkills()
|
|
260
|
+
if (!Array.isArray(listed.skills) || listed.libraryAvailable === false) throw new Error("Magpie 资料库暂不可用,请稍后重试")
|
|
261
|
+
if (!listed.skills.some(item => item.name === alias)) alias = plainName
|
|
262
|
+
}
|
|
263
|
+
if (Object.entries(this.registry).some(([id, entry]) => id !== skill.skill_id && entry.alias === alias && entry.registration === "registered")) {
|
|
264
|
+
const listed = this.host.listSkills ? await this.host.listSkills() : null
|
|
265
|
+
if (!listed || !Array.isArray(listed.skills) || listed.libraryAvailable === false || listed.skills.some(item => item.name.toLowerCase() === alias.toLowerCase())) {
|
|
266
|
+
throw Object.assign(new Error("本机已有同名技能,请先在 Magpie 资料库处理同名项后重试"), { code: "SKILL_NAME_CONFLICT" })
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
// Tenant/skill identity belongs in the private cache, never the Library name.
|
|
270
|
+
const cacheName = owned ? previous.cacheName || previous.alias : `pkg-${createHash("sha256").update(JSON.stringify([sourceKind, companyId, skill.skill_id])).digest("hex")}`
|
|
271
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(cacheName)) throw new Error("Invalid skill cache name")
|
|
272
|
+
const ownsLibraryName = !!owned && previous.alias === alias && previous.registration !== "removed" && (previous.registration === "registered" || previous.libraryNameOwned === true)
|
|
273
|
+
if (ownsLibraryName && this.host.registeredHash) {
|
|
274
|
+
const hash = await this.host.registeredHash(alias)
|
|
275
|
+
if (hash && hash !== previous.manifestHash) throw Object.assign(new Error("技能有本地修改,已保留"), { reason: "local_changes" })
|
|
276
|
+
}
|
|
277
|
+
const final = join(this.root, cacheName)
|
|
278
|
+
const temporary = join(this.root, `.download-${alias}-${randomId(8)}`)
|
|
279
|
+
const verified = await verifyDownloadedPackage(packageBytes, { packageHash: version.package_hash, manifest }).catch(error => { throw Object.assign(error, { reason: "hash_mismatch" }) })
|
|
280
|
+
await mkdir(temporary, { recursive: true, mode: 0o700 })
|
|
281
|
+
await chmod(temporary, 0o700)
|
|
282
|
+
try {
|
|
283
|
+
for (const file of verified.entries) {
|
|
284
|
+
const target = join(temporary, file.path)
|
|
285
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 })
|
|
286
|
+
await chmod(dirname(target), 0o700)
|
|
287
|
+
await writeFile(target, file.bytes, { mode: 0o600 })
|
|
288
|
+
}
|
|
289
|
+
let rollback = null
|
|
290
|
+
let localCopyPreserved = false
|
|
291
|
+
try {
|
|
292
|
+
await stat(final)
|
|
293
|
+
const oldHash = await directoryHash(final)
|
|
294
|
+
const expected = this.registry[skill.skill_id]?.manifestHash
|
|
295
|
+
localCopyPreserved = !!expected && oldHash !== expected
|
|
296
|
+
rollback = join(this.root, `.previous-${alias}-${randomId(8)}`)
|
|
297
|
+
await rename(final, rollback)
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (error?.code !== "ENOENT") throw error
|
|
300
|
+
}
|
|
301
|
+
try {
|
|
302
|
+
await rename(temporary, final)
|
|
303
|
+
if (rollback) {
|
|
304
|
+
if (localCopyPreserved) {
|
|
305
|
+
const backup = join(this.backups, `${alias}-${this.now().toISOString().replace(/[:.]/g, "-")}`)
|
|
306
|
+
await rename(rollback, backup)
|
|
307
|
+
} else {
|
|
308
|
+
await rm(rollback, { recursive: true, force: true })
|
|
309
|
+
}
|
|
310
|
+
rollback = null
|
|
311
|
+
}
|
|
312
|
+
} catch (error) {
|
|
313
|
+
if (rollback) {
|
|
314
|
+
await rm(final, { recursive: true, force: true }).catch(() => {})
|
|
315
|
+
await rename(rollback, final).catch(() => {})
|
|
316
|
+
}
|
|
317
|
+
throw error
|
|
318
|
+
}
|
|
319
|
+
if (localCopyPreserved) this.registry[skill.skill_id] = { ...this.registry[skill.skill_id], localCopyPreserved: true }
|
|
320
|
+
let registration = { registered: false }
|
|
321
|
+
check()
|
|
322
|
+
try {
|
|
323
|
+
registration = await this.host.registerSkill({
|
|
324
|
+
name: alias,
|
|
325
|
+
sourceDir: final,
|
|
326
|
+
agents: targetAgents,
|
|
327
|
+
packageFiles: verified.entries,
|
|
328
|
+
manifestHash: manifestHash(verified.manifest),
|
|
329
|
+
replaceExisting: ownsLibraryName,
|
|
330
|
+
previousHash: previous?.manifestHash, check,
|
|
331
|
+
})
|
|
332
|
+
} catch (error) {
|
|
333
|
+
// Host adapters expose bounded, stage-specific messages. Never project
|
|
334
|
+
// a child process's stdout/stderr or arbitrary filesystem exception.
|
|
335
|
+
const code = String(error?.code ?? "")
|
|
336
|
+
registration.libraryNameOwned = error?.libraryNameOwned === true
|
|
337
|
+
registration.error = /^HOST_SKILL_[A-Z_]+_FAILED$/.test(code)
|
|
338
|
+
? { code, message: error.message }
|
|
339
|
+
: { code: "HOST_SKILL_REGISTRATION_FAILED", message: "Magpie 资料库登记失败,请检查资料库是否可用后重试" }
|
|
340
|
+
}
|
|
341
|
+
if (!registration.registered && owned && previous.registration === "registered") {
|
|
342
|
+
throw Object.assign(new Error(registration.error?.message || "资料库更新失败,已保留原版本"), { reason: "install_failed" })
|
|
343
|
+
}
|
|
344
|
+
this.registry[skill.skill_id] = {
|
|
345
|
+
...this.registry[skill.skill_id],
|
|
346
|
+
slug: skill.slug,
|
|
347
|
+
displayName: skill.display_name,
|
|
348
|
+
description: skill.description,
|
|
349
|
+
publisher: skill.publisher,
|
|
350
|
+
categoryId: skill.category_id,
|
|
351
|
+
categoryName: skill.category_name,
|
|
352
|
+
companyId: sourceKind === "company" ? String(skill.company_id ?? "") : "",
|
|
353
|
+
remoteAvailability: "available",
|
|
354
|
+
alias,
|
|
355
|
+
cacheName,
|
|
356
|
+
libraryNameOwned: registration.registered || ownsLibraryName || registration.libraryNameOwned === true,
|
|
357
|
+
version: Number(version.version),
|
|
358
|
+
manifest: verified.manifest,
|
|
359
|
+
manifestHash: manifestHash(verified.manifest),
|
|
360
|
+
packageHash: verified.hash,
|
|
361
|
+
download: "installed",
|
|
362
|
+
registration: registration.registered ? "registered" : "downloaded",
|
|
363
|
+
registrationError: registration.registered ? null : registration.error || { code: "HOST_SKILL_CONFIRM_FAILED", message: "Magpie 资料库尚未返回该技能的登记记录" },
|
|
364
|
+
availability: "unverified",
|
|
365
|
+
sourceKind,
|
|
366
|
+
targetAgents,
|
|
367
|
+
updatedAt: this.now().toISOString(),
|
|
368
|
+
}
|
|
369
|
+
this.persist()
|
|
370
|
+
return this.registry[skill.skill_id]
|
|
371
|
+
} finally {
|
|
372
|
+
await rm(temporary, { recursive: true, force: true }).catch(() => {})
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async applyCatalog({ skills = [], revision = "" } = {}) {
|
|
377
|
+
this.catalogProjection = skills.map((skill) => ({
|
|
378
|
+
skillId: skill.skill_id,
|
|
379
|
+
slug: skill.slug,
|
|
380
|
+
displayName: skill.display_name,
|
|
381
|
+
description: skill.description,
|
|
382
|
+
status: skill.status,
|
|
383
|
+
currentVersion: skill.current_version,
|
|
384
|
+
categoryId: skill.category_id,
|
|
385
|
+
categoryName: skill.category_name,
|
|
386
|
+
publisher: skill.publisher,
|
|
387
|
+
}))
|
|
388
|
+
// Catalog refresh never downloads packages or changes Magpie registrations.
|
|
389
|
+
const companyId = String(this.session.projection?.().company?.id ?? "")
|
|
390
|
+
for (const [skillId, entry] of Object.entries(this.registry)) {
|
|
391
|
+
const platform = entry.sourceKind === "platform"
|
|
392
|
+
const belongs = !entry.companyId || entry.companyId === companyId
|
|
393
|
+
const remote = !platform && belongs ? skills.find((skill) => skill.skill_id === skillId) : null
|
|
394
|
+
entry.remoteAvailability = remote && (!remote.status || remote.status === "published") ? "available" : "unavailable"
|
|
395
|
+
}
|
|
396
|
+
this.registryRevision = revision
|
|
397
|
+
this.persist()
|
|
398
|
+
return { installed: 0, unchanged: Object.keys(this.registry).length, removed: 0, failed: [] }
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async share({ sourceName, display_name, description, category_id = "", updateSkillId, expectedVersion, idempotencyKey, previewHash }) {
|
|
402
|
+
const scope = this.scope()
|
|
403
|
+
const owner = this.session.ownership?.()
|
|
404
|
+
if (updateSkillId && !/^skl_[A-Za-z0-9_-]+$/.test(updateSkillId)) throw new Error("Invalid skill id")
|
|
405
|
+
if (!LIBRARY_SKILL_RE.test(String(sourceName ?? ""))) throw new Error("Invalid skill name")
|
|
406
|
+
const source = await this.host.readSkillFiles(sourceName)
|
|
407
|
+
const packaged = await buildShareablePackage(source)
|
|
408
|
+
if (this.api.catalog && previewHash !== "sha256:" + createHash("sha256").update(packaged.bytes).digest("hex")) throw new Error("技能文件已变化,请重新预览")
|
|
409
|
+
if (scope !== this.scope()) throw new Error("公司身份已变更")
|
|
410
|
+
this.session.assertOwnership?.(owner)
|
|
411
|
+
const form = new FormData()
|
|
412
|
+
form.set("category_id", String(category_id ?? ""))
|
|
413
|
+
form.set("package", new Blob([packaged.bytes], { type: "application/zip" }), `${sourceName}.zip`)
|
|
414
|
+
form.set("idempotency_key", String(idempotencyKey || randomId(18)))
|
|
415
|
+
if (updateSkillId) {
|
|
416
|
+
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 1) throw new Error("expected_version is required")
|
|
417
|
+
form.set("expected_version", String(expectedVersion))
|
|
418
|
+
}
|
|
419
|
+
const metadataDescription = skillDescription((source.files ?? source).find(file => file.path === "SKILL.md")?.bytes)
|
|
420
|
+
// Identity is generated by ArkFlow, independently of Library folder names.
|
|
421
|
+
for (const [name, value] of Object.entries({ display_name, description: description ?? metadataDescription })) {
|
|
422
|
+
if (value !== undefined && value !== "") form.set(name, String(value))
|
|
423
|
+
}
|
|
424
|
+
if (updateSkillId && this.api.catalog) {
|
|
425
|
+
const { skill } = await this.storeDetail({ sourceKind: "company", skillId: updateSkillId })
|
|
426
|
+
for (const field of ["source", "source_url", "license"]) if (skill[field]) form.set(field, skill[field])
|
|
427
|
+
for (const tag of skill.tags || []) form.append("tags", tag)
|
|
428
|
+
this.session.assertOwnership?.(owner)
|
|
429
|
+
}
|
|
430
|
+
const result = await this.session.withAccess((access) => (
|
|
431
|
+
updateSkillId
|
|
432
|
+
? this.api.updateSkill(access, updateSkillId, form)
|
|
433
|
+
: this.api.contributeSkill(access, form)
|
|
434
|
+
))
|
|
435
|
+
return { ...result, excluded: packaged.excluded, manifest: packaged.manifest }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async previewShare({ sourceName }) {
|
|
439
|
+
if (!LIBRARY_SKILL_RE.test(String(sourceName ?? ""))) throw new Error("Invalid skill name")
|
|
440
|
+
const source = await this.host.readSkillFiles(sourceName)
|
|
441
|
+
const packaged = await buildShareablePackage(source)
|
|
442
|
+
return {
|
|
443
|
+
sourceName,
|
|
444
|
+
description: skillDescription((source.files ?? source).find(file => file.path === "SKILL.md")?.bytes),
|
|
445
|
+
packageHash: "sha256:" + createHash("sha256").update(packaged.bytes).digest("hex"),
|
|
446
|
+
packageBytes: packaged.bytes.byteLength,
|
|
447
|
+
expandedBytes: packaged.manifest.reduce((sum, file) => sum + Number(file.size || 0), 0),
|
|
448
|
+
files: packaged.manifest,
|
|
449
|
+
excluded: packaged.excluded,
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export { aliasFor }
|