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.
@@ -0,0 +1,89 @@
1
+ import { createHash, randomBytes } from "node:crypto"
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ fsyncSync,
6
+ mkdirSync,
7
+ openSync,
8
+ readFileSync,
9
+ renameSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from "node:fs"
13
+ import { basename, dirname, join, resolve } from "node:path"
14
+
15
+ export function defaultDataDir(magpieDirectory) {
16
+ if (typeof magpieDirectory !== "string" || !magpieDirectory) {
17
+ throw new Error("Magpie did not provide input.directory for private plugin state")
18
+ }
19
+ return join(magpieDirectory, "plugin-data", "novaflow-magpie-plugin")
20
+ }
21
+
22
+ export function secureMkdir(path) {
23
+ mkdirSync(path, { recursive: true, mode: 0o700 })
24
+ try {
25
+ chmodSync(path, 0o700)
26
+ } catch {}
27
+ }
28
+
29
+ export function atomicWriteFile(path, data, mode = 0o600) {
30
+ const target = resolve(path)
31
+ secureMkdir(dirname(target))
32
+ const temporary = join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`)
33
+ let fd
34
+ try {
35
+ fd = openSync(temporary, "w", mode)
36
+ writeFileSync(fd, data, { encoding: typeof data === "string" ? "utf8" : undefined })
37
+ fsyncSync(fd)
38
+ closeSync(fd)
39
+ fd = undefined
40
+ renameSync(temporary, target)
41
+ try {
42
+ const directory = openSync(dirname(target), "r")
43
+ fsyncSync(directory)
44
+ closeSync(directory)
45
+ } catch {}
46
+ } finally {
47
+ if (fd !== undefined) closeSync(fd)
48
+ }
49
+ }
50
+
51
+ export class JsonStore {
52
+ constructor(path, defaults = {}) {
53
+ this.path = path
54
+ this.defaults = defaults
55
+ }
56
+
57
+ read() {
58
+ try {
59
+ return { ...structuredClone(this.defaults), ...JSON.parse(readFileSync(this.path, "utf8")) }
60
+ } catch (error) {
61
+ if (error?.code === "ENOENT") return structuredClone(this.defaults)
62
+ throw error
63
+ }
64
+ }
65
+
66
+ write(value) {
67
+ atomicWriteFile(this.path, JSON.stringify(value, null, 2) + "\n", 0o600)
68
+ try {
69
+ chmodSync(this.path, 0o600)
70
+ } catch {}
71
+ return value
72
+ }
73
+
74
+ exists() {
75
+ try {
76
+ return statSync(this.path).isFile()
77
+ } catch {
78
+ return false
79
+ }
80
+ }
81
+ }
82
+
83
+ export function randomId(bytes = 18) {
84
+ return randomBytes(bytes).toString("base64url")
85
+ }
86
+
87
+ export function stableId(...parts) {
88
+ return createHash("sha256").update(JSON.stringify(parts)).digest("hex")
89
+ }
@@ -0,0 +1,392 @@
1
+ import { JsonStore } from "./state-store.mjs"
2
+
3
+ const FATAL_CODES = new Set([
4
+ "PLUGIN_SESSION_REVOKED",
5
+ "PLUGIN_IDENTITY_UNAVAILABLE",
6
+ "PLUGIN_COMPANY_INACTIVE",
7
+ "PLUGIN_MEMBERSHIP_INACTIVE",
8
+ ])
9
+
10
+ function configError(payload) {
11
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return "Config payload is invalid"
12
+ if (payload.schema_version !== 1) return "Config schema is unsupported"
13
+ const forbidden = ["key_id", "default_key_id", "recommended_key_id"]
14
+ if (forbidden.some((name) => Object.hasOwn(payload, name))) return "Company config must not name a key"
15
+ for (const field of ["recommended_group_id", "recommended_model_id"]) {
16
+ if (payload[field] !== null && payload[field] !== undefined && (typeof payload[field] !== "string" || payload[field].length > 200)) {
17
+ return `${field} is invalid`
18
+ }
19
+ }
20
+ return ""
21
+ }
22
+
23
+ export class SyncEngine {
24
+ constructor({
25
+ config,
26
+ api,
27
+ session,
28
+ credentials,
29
+ accounts,
30
+ nativeProviders,
31
+ skills,
32
+ defaults,
33
+ preferences,
34
+ hostVersion = config.hostMinVersion,
35
+ instanceId,
36
+ snapshotStore,
37
+ now = () => Date.now(),
38
+ report = () => {},
39
+ }) {
40
+ this.config = config
41
+ this.api = api
42
+ this.session = session
43
+ this.credentials = credentials
44
+ this.accounts = accounts
45
+ this.nativeProviders = nativeProviders
46
+ this.skills = skills
47
+ this.defaults = defaults
48
+ this.preferences = preferences
49
+ this.hostVersion = hostVersion
50
+ this.instanceId = instanceId
51
+ this.snapshotStore = snapshotStore ?? new JsonStore("", {})
52
+ this.now = now
53
+ this.report = report
54
+ this.running = null
55
+ this.timer = null
56
+ this.controller = null
57
+ this.stopped = true
58
+ this.failures = 0
59
+ this.state = {
60
+ status: "wait_connection",
61
+ revision: "",
62
+ lastAttemptAt: "",
63
+ lastSuccessAt: "",
64
+ nextAttemptAt: "",
65
+ errorCode: "",
66
+ requestId: "",
67
+ components: {
68
+ keys: "pending",
69
+ settings: "pending",
70
+ skills: "pending",
71
+ },
72
+ stale: false,
73
+ appliedRevision: "",
74
+ }
75
+ const cached = this.snapshotStore.read()
76
+ if (cached?.state) {
77
+ this.state = { ...this.state, ...cached.state, status: cached.state.lastSuccessAt ? "stale" : cached.state.status, stale: !!cached.state.lastSuccessAt }
78
+ }
79
+ this.configPayload = cached?.config ?? null
80
+ this.usage = cached?.usage ?? null
81
+ }
82
+
83
+ projection() {
84
+ return {
85
+ ...structuredClone(this.state),
86
+ config: this.configPayload?.payload ?? null,
87
+ configRevision: this.configPayload?.revision ?? this.configPayload?.payload?.revision ?? "",
88
+ usage: this.usage,
89
+ defaults: this.defaults.status(),
90
+ accounts: this.accounts.projection(),
91
+ skills: this.skills.projection(),
92
+ }
93
+ }
94
+
95
+ isFatal(error) {
96
+ return error?.status === 401
97
+ || error?.status === 403
98
+ || FATAL_CODES.has(error?.code)
99
+ || error?.code === "PLUGIN_SCHEMA_UNSUPPORTED"
100
+ }
101
+
102
+ saveState() {
103
+ this.snapshotStore.write({
104
+ state: { ...this.state, stale: false },
105
+ config: this.configPayload,
106
+ usage: this.usage,
107
+ skillsCatalog: this.skills.projection().catalog,
108
+ })
109
+ }
110
+
111
+ start() {
112
+ if (!this.stopped) return
113
+ this.stopped = false
114
+ if (this.running) {
115
+ this.restartPending = true
116
+ return
117
+ }
118
+ void this.syncNow("startup")
119
+ }
120
+
121
+ resetSession() {
122
+ this.stop("ArkFlow session changed")
123
+ this.configPayload = null
124
+ this.usage = null
125
+ this.failures = 0
126
+ this.state = {
127
+ ...this.state,
128
+ status: "wait_connection",
129
+ revision: "",
130
+ appliedRevision: "",
131
+ lastAttemptAt: "",
132
+ lastSuccessAt: "",
133
+ nextAttemptAt: "",
134
+ errorCode: "",
135
+ requestId: "",
136
+ stale: false,
137
+ components: { keys: "pending", settings: "pending", skills: "pending" },
138
+ }
139
+ this.saveState()
140
+ }
141
+
142
+ stop(reason = "Sync stopped") {
143
+ this.stopped = true
144
+ clearTimeout(this.timer)
145
+ this.timer = null
146
+ this.controller?.abort(new Error(reason))
147
+ this.controller = null
148
+ }
149
+
150
+ nextDelay() {
151
+ if (this.failures) return Math.min(this.config.retryMaxMs, 1000 * 2 ** Math.min(8, this.failures - 1))
152
+ const jitter = 1 + (Math.random() * 2 - 1) * this.config.pollingJitter
153
+ return Math.max(1000, Math.round(this.config.pollingMs * jitter))
154
+ }
155
+
156
+ schedule(delay = this.nextDelay()) {
157
+ clearTimeout(this.timer)
158
+ if (this.stopped) return
159
+ const at = this.now() + delay
160
+ this.state.nextAttemptAt = new Date(at).toISOString()
161
+ this.timer = setTimeout(() => {
162
+ void this.syncNow("poll")
163
+ }, delay)
164
+ this.timer.unref?.()
165
+ }
166
+
167
+ async syncNow(reason = "manual", reset = null) {
168
+ if (reset && this.running) throw Object.assign(new Error("正在同步,请稍后重置分组"), { status: 409 })
169
+ if (this.running) return this.running
170
+ if (this.stopped && reason === "poll") return this.state
171
+ const setup = this.session.projection().setup
172
+ this.running = this.runOnce(reason, reset).then(async result => {
173
+ if (setup && (["sync", "config"].includes(setup.stage) || (setup.stage === "sync_error" && result.resetApplied && result.status === "ready"))) {
174
+ await this.finishLoginSetup(setup, result)
175
+ }
176
+ return result
177
+ }).finally(() => {
178
+ this.running = null
179
+ if (this.restartPending && !this.stopped) {
180
+ this.restartPending = false
181
+ clearTimeout(this.timer)
182
+ void this.syncNow("session")
183
+ } else if (!this.stopped) this.schedule()
184
+ })
185
+ return this.running
186
+ }
187
+
188
+ async finishLoginSetup(setup, sync) {
189
+ const signal = this.controller?.signal
190
+ if (!signal || signal.aborted) return
191
+ const transition = (from, to) => this.session.setSetupStage(setup.id, from, to, { worker: true })
192
+ if (sync.status !== "ready") {
193
+ transition(setup.stage, "sync_error")
194
+ return
195
+ }
196
+ if (!transition(setup.stage, "config")) return
197
+ const assertCurrent = () => {
198
+ signal.throwIfAborted()
199
+ const current = this.session.projection().setup
200
+ if (current?.id !== setup.id || current.stage !== "config") throw new Error("登录状态已变化")
201
+ }
202
+ try {
203
+ const result = await this.defaults.run({ automatic: true, assertCurrent })
204
+ assertCurrent()
205
+ transition("config", result.status === "complete" ? "done" : "config_error")
206
+ } catch {
207
+ if (!signal.aborted) transition("config", "config_error")
208
+ }
209
+ }
210
+
211
+ async runOnce(reason, reset) {
212
+ if (this.session.projection().status !== "authenticated") {
213
+ this.state.status = "wait_connection"
214
+ this.state.errorCode = ""
215
+ return this.projection()
216
+ }
217
+ this.controller?.abort(new Error("Superseded by a new sync"))
218
+ this.controller = new AbortController()
219
+ const signal = this.controller.signal
220
+ const generation = this.session.generation
221
+ const retryComponents = this.state.status === "partial" || Object.values(this.state.components).includes("failed")
222
+ this.state.lastAttemptAt = new Date(this.now()).toISOString()
223
+ this.state.status = this.state.lastSuccessAt ? "refreshing" : "syncing"
224
+ this.state.errorCode = ""
225
+ this.state.requestId = ""
226
+ try {
227
+ let snapshot = await this.session.withAccess((access) => this.api.sync(access, reset ? "" : this.state.revision, signal), { signal })
228
+ let unchanged = !reset && (snapshot?.not_modified === true || snapshot?.not_modified === undefined && snapshot?.revision === this.state.revision)
229
+ if (unchanged && retryComponents) {
230
+ // Request a complete snapshot when a prior component needs recovery.
231
+ snapshot = await this.session.withAccess((access) => this.api.sync(access, "", signal), { signal })
232
+ unchanged = false
233
+ }
234
+ if (!unchanged && (!snapshot || snapshot.not_modified || snapshot.schema_version !== 1 || !snapshot.revision)) {
235
+ throw Object.assign(new Error("ArkFlow sync schema is unsupported"), { code: "PLUGIN_SCHEMA_UNSUPPORTED" })
236
+ }
237
+ if (generation !== this.session.generation || signal.aborted) throw Object.assign(new Error("Stale sync response"), { code: "SYNC_STALE_RESPONSE" })
238
+ await this.session.withAccess(async (access) => {
239
+ const owner = this.session.ownership?.()
240
+ const bootstrap = await this.api.bootstrap(access, signal)
241
+ if (bootstrap?.schema_version !== 1) throw Object.assign(new Error("ArkFlow bootstrap schema is unsupported"), { code: "PLUGIN_SCHEMA_UNSUPPORTED" })
242
+ await this.session.updateBootstrap(bootstrap, { owner })
243
+ }, { signal })
244
+ try {
245
+ this.usage = await this.session.withAccess((access) => this.api.usage(access, signal), { signal })
246
+ } catch (error) {
247
+ if (this.isFatal(error)) throw error
248
+ }
249
+ if (generation !== this.session.generation || signal.aborted) throw Object.assign(new Error("Stale sync response"), { code: "SYNC_STALE_RESPONSE" })
250
+ let storeFailure = null
251
+ const companySkills = this.session.projection().accountMode === "enterprise"
252
+ try {
253
+ if (companySkills) await this.skills.refreshStore(signal)
254
+ } catch (error) {
255
+ if (this.isFatal(error) && error.status !== 403) throw error
256
+ storeFailure = error
257
+ this.state.errorCode = error.code || "SKILLS_FAILED"
258
+ }
259
+ if (generation !== this.session.generation || signal.aborted) throw Object.assign(new Error("Stale sync response"), { code: "SYNC_STALE_RESPONSE" })
260
+ if (unchanged) {
261
+ const native = await this.nativeProviders?.reconcile({ signal, refresh: ["native", "page", "manual", "models", "login"].includes(reason) })
262
+ const nativeFailure = native?.failures?.length > 0
263
+ if (this.nativeProviders) this.state.components.keys = nativeFailure ? "failed" : "success"
264
+ this.state.components.skills = !companySkills ? "unknown" : storeFailure ? "failed" : "success"
265
+ this.state.status = storeFailure || nativeFailure ? "partial" : "ready"
266
+ this.state.stale = false
267
+ this.failures = 0
268
+ this.saveState()
269
+ return this.projection()
270
+ }
271
+
272
+ const components = { keys: "pending", settings: "pending", skills: "pending" }
273
+ const failures = []
274
+ let credentialProjection
275
+ let resetApplied = false
276
+ let resetStale = false
277
+ try {
278
+ credentialProjection = await this.credentials.load({ snapshot, signal })
279
+ const native = await this.nativeProviders?.reconcile({ signal, refresh: ["native", "page", "manual", "models", "login"].includes(reason), ...(reset ? { reset } : {}) })
280
+ resetApplied = native?.resetApplied === true
281
+ if (native?.failures?.length) throw Object.assign(new Error(native.failures[0].message), { code: native.failures[0].code })
282
+ components.keys = "success"
283
+ } catch (error) {
284
+ resetStale = error.code === "PLUGIN_NATIVE_RESET_STALE"
285
+ if (error.code === "PLUGIN_KEY_REVISION_CONFLICT") {
286
+ this.state.revision = ""
287
+ throw error
288
+ }
289
+ components.keys = "failed"
290
+ failures.push({ name: "keys", status: "failed", code: error.code || "KEYS_FAILED" })
291
+ if (this.isFatal(error)) throw error
292
+ }
293
+ if (generation !== this.session.generation || signal.aborted) throw Object.assign(new Error("Stale sync response"), { code: "SYNC_STALE_RESPONSE" })
294
+
295
+ const configPayload = snapshot.config ?? (snapshot.config_payload ? { payload: snapshot.config_payload, revision: snapshot.config_revision } : null)
296
+ let config = null
297
+ try {
298
+ if (configPayload) {
299
+ const invalid = configError(configPayload.payload ?? configPayload)
300
+ if (invalid) throw Object.assign(new Error(invalid), { code: "PLUGIN_CONFIG_INVALID" })
301
+ config = configPayload
302
+ }
303
+ components.settings = "success"
304
+ } catch (error) {
305
+ components.settings = "failed"
306
+ failures.push({ name: "settings", status: "failed", code: error.code || "CONFIG_FAILED" })
307
+ if (this.isFatal(error)) throw error
308
+ }
309
+
310
+ const skillResult = { installed: 0, unchanged: 0, removed: 0, failed: [] }
311
+ components.skills = !companySkills ? "unknown" : storeFailure ? "failed" : "success"
312
+ if (storeFailure) failures.push({ name: "skills", status: "failed", code: storeFailure.code || "SKILLS_FAILED" })
313
+
314
+ this.configPayload = config ? { payload: config.payload ?? config, revision: String(config.revision ?? config.payload?.revision ?? "") } : null
315
+ this.state.revision = String(snapshot.revision)
316
+ this.state.appliedRevision = String(snapshot.revision)
317
+ this.state.components = components
318
+ this.state.lastSuccessAt = new Date(this.now()).toISOString()
319
+ this.state.stale = false
320
+ this.state.status = failures.length ? "partial" : "ready"
321
+ this.failures = 0
322
+ this.saveState()
323
+ this.report("sync.applied", {
324
+ revision: this.state.revision,
325
+ keys: credentialProjection?.keyCount ?? 0,
326
+ skillsInstalled: skillResult.installed,
327
+ partial: failures.length,
328
+ reason,
329
+ })
330
+ await this.sendReceipt(failures, signal)
331
+ return { ...this.projection(), ...(reset ? { resetApplied, resetStale } : {}) }
332
+ } catch (error) {
333
+ if (generation !== this.session.generation || signal.aborted || error.code === "PLUGIN_SESSION_CHANGED") return this.projection()
334
+ this.failures++
335
+ this.state.status = this.isFatal(error) ? "blocked" : "offline"
336
+ this.state.errorCode = String(error.code || (error.status ? `HTTP_${error.status}` : "SYNC_FAILED"))
337
+ this.state.requestId = String(error.requestId ?? "")
338
+ this.state.stale = !!this.state.lastSuccessAt
339
+ if (this.isFatal(error)) {
340
+ this.session.revoke(error.message)
341
+ this.accounts.disposeOwnedOnly()
342
+ await this.nativeProviders?.clear()
343
+ }
344
+ this.saveState()
345
+ this.report("sync.failed", { code: this.state.errorCode, status: error.status ?? 0, stale: this.state.stale, reason, message: String(error?.message ?? "") })
346
+ return this.projection()
347
+ }
348
+ }
349
+
350
+ async sendReceipt(failures, signal) {
351
+ const components = [
352
+ { name: "keys", status: this.state.components.keys, ...(failures.find((item) => item.name === "keys")?.code ? { code: failures.find((item) => item.name === "keys").code } : {}) },
353
+ { name: "skills", status: this.state.components.skills, ...(failures.find((item) => item.name === "skills")?.code ? { code: failures.find((item) => item.name === "skills").code } : {}) },
354
+ { name: "settings", status: this.state.components.settings, ...(failures.find((item) => item.name === "settings")?.code ? { code: failures.find((item) => item.name === "settings").code } : {}) },
355
+ ]
356
+ const receipt = {
357
+ instance_id: this.instanceId,
358
+ revision: this.state.revision,
359
+ client_version: this.config.pluginVersion,
360
+ host_version: this.hostVersion,
361
+ components,
362
+ reported_at: new Date(this.now()).toISOString(),
363
+ }
364
+ try {
365
+ await this.session.withAccess((access) => this.api.receipt(access, receipt, signal), { signal })
366
+ this.state.receipt = "success"
367
+ } catch (error) {
368
+ this.state.receipt = "failed"
369
+ this.state.receiptCode = String(error.code || "RECEIPT_FAILED")
370
+ this.saveState()
371
+ }
372
+ }
373
+
374
+ async loadAllSkills(signal) {
375
+ const items = []
376
+ const seen = new Set()
377
+ let cursor = ""
378
+ for (let page = 0; page < 1000; page++) {
379
+ const response = await this.session.withAccess((access) => this.api.skills(access, cursor, signal), { signal })
380
+ if (!response || !Array.isArray(response.items)) throw Object.assign(new Error("ArkFlow skill cursor response is invalid"), { code: "SKILL_CURSOR_INVALID" })
381
+ items.push(...response.items)
382
+ const next = response.next_cursor ?? response.next ?? ""
383
+ if (!next) return items
384
+ if (typeof next !== "string" || seen.has(next)) throw Object.assign(new Error("ArkFlow skill cursor repeated"), { code: "SKILL_CURSOR_INVALID" })
385
+ seen.add(next)
386
+ cursor = next
387
+ }
388
+ throw Object.assign(new Error("ArkFlow skill cursor exceeded its limit"), { code: "SKILL_CURSOR_INVALID" })
389
+ }
390
+ }
391
+
392
+ export { FATAL_CODES, configError }