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,358 @@
1
+ import { createServer } from "node:http"
2
+ import { readFile } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { fileURLToPath } from "node:url"
5
+ import { randomId } from "./state-store.mjs"
6
+ import { ALIAS_RE } from "./host-adapter.mjs"
7
+
8
+ const ROOT = fileURLToPath(new URL("../page/", import.meta.url))
9
+ // Wails uses a custom scheme on macOS/Linux and an intercepted HTTP origin
10
+ // in Windows WebView2. Keep these exact: *.localhost is not a trusted host.
11
+ const MAGPIE_DESKTOP_ORIGINS = new Set([
12
+ "wails://localhost",
13
+ "http://wails.localhost",
14
+ ])
15
+ const BODY_LIMIT = 1 << 20
16
+ const STATIC = new Map([
17
+ ["/", ["service.html", "text/html; charset=utf-8"]],
18
+ ["/connection.js", ["connection.js", "text/javascript; charset=utf-8"]],
19
+ ["/request.js", ["request.js", "text/javascript; charset=utf-8"]],
20
+ ["/app.js", ["app.js", "text/javascript; charset=utf-8"]],
21
+ ["/theme.js", ["theme.js", "text/javascript; charset=utf-8"]],
22
+ ["/store-model.mjs", ["store-model.mjs", "text/javascript; charset=utf-8"]],
23
+ ["/app.css", ["app.css", "text/css; charset=utf-8"]],
24
+ ["/magpie-components.css", ["magpie-components.css", "text/css; charset=utf-8"]],
25
+ ["/logo.png", ["logo.png", "image/png"]],
26
+ ["/icon.svg", ["icon.svg", "image/svg+xml"]],
27
+ ])
28
+
29
+ function securityHeaders(response, port) {
30
+ // Stock Magpie proxies this page under its own loopback port. The
31
+ // opaque sandbox cannot use self as a source; allow loopback origins.
32
+ const serviceSource = "http://127.0.0.1:* http://localhost:*"
33
+ response.setHeader("content-security-policy", [
34
+ `default-src ${serviceSource}`,
35
+ `script-src ${serviceSource}`,
36
+ `style-src ${serviceSource}`,
37
+ `img-src ${serviceSource} data:`,
38
+ `connect-src ${serviceSource}`,
39
+ // The page replaces its sandboxed frame; its ancestor is the Magpie
40
+ // window. Name both desktop origins, including Windows WebView2.
41
+ `frame-ancestors 'self' ${[...MAGPIE_DESKTOP_ORIGINS].join(" ")} ${serviceSource}`,
42
+ "base-uri 'none'",
43
+ "form-action 'self'",
44
+ ].join("; "))
45
+ response.setHeader("referrer-policy", "no-referrer")
46
+ response.setHeader("x-content-type-options", "nosniff")
47
+ response.setHeader("cache-control", "no-store")
48
+ }
49
+
50
+ function json(response, status, body) {
51
+ response.statusCode = status
52
+ response.setHeader("content-type", "application/json; charset=utf-8")
53
+ response.end(JSON.stringify(body))
54
+ }
55
+
56
+ function sameHost(header, port) {
57
+ if (!header) return false
58
+ return header === `127.0.0.1:${port}` || header === `localhost:${port}`
59
+ }
60
+
61
+ async function readJson(request) {
62
+ if (!String(request.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
63
+ throw Object.assign(new Error("Content-Type must be application/json"), { status: 415 })
64
+ }
65
+ let size = 0
66
+ const chunks = []
67
+ for await (const chunk of request) {
68
+ size += chunk.byteLength
69
+ if (size > BODY_LIMIT) throw Object.assign(new Error("Request body is too large"), { status: 413 })
70
+ chunks.push(chunk)
71
+ }
72
+ try {
73
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}")
74
+ } catch {
75
+ throw Object.assign(new Error("Request body is not valid JSON"), { status: 400 })
76
+ }
77
+ }
78
+
79
+ function allowedOrigin(request, port) {
80
+ const origin = request.headers.origin
81
+ if (!origin) return true
82
+ if (origin === "null") return true
83
+ if (MAGPIE_DESKTOP_ORIGINS.has(origin)) return true
84
+ return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`
85
+ }
86
+
87
+ function noSecretProjection(value) {
88
+ return JSON.parse(JSON.stringify(value, (key, item) => {
89
+ if (/^(?:key|access|refresh|access_token|refresh_token|token|secret|password)$/i.test(key)) return undefined
90
+ return item
91
+ }))
92
+ }
93
+
94
+ export function createPageServer({
95
+ config,
96
+ control,
97
+ session,
98
+ sync,
99
+ accounts,
100
+ skills,
101
+ skillManager,
102
+ api,
103
+ host,
104
+ defaults,
105
+ preferencesStore,
106
+ hostVersion = config.hostMinVersion,
107
+ port = config.servicePort,
108
+ hostName = config.serviceHost,
109
+ }) {
110
+ const csrfToken = randomId(32)
111
+ let actualPort = port
112
+ const diagnostics = { lastError: "", commandCount: 0 }
113
+
114
+ const server = createServer(async (request, response) => {
115
+ securityHeaders(response, actualPort)
116
+ if (!sameHost(request.headers.host, actualPort)) {
117
+ json(response, 421, { error: "Invalid loopback Host" })
118
+ return
119
+ }
120
+ // Magpie serves plugin pages under `Content-Security-Policy: sandbox`, so
121
+ // every request from that page — the frame navigation, app.css/app.js and
122
+ // the typed API calls — arrives as an opaque origin with
123
+ // `Sec-Fetch-Site: cross-site`. Sec-Fetch-Site therefore cannot separate
124
+ // the Magpie page from a website. What still does: the Host is pinned to
125
+ // this loopback port (DNS rebinding), HTML never grants cross-origin read
126
+ // access, and every API request needs the per-process page token.
127
+ if (!allowedOrigin(request, actualPort)) {
128
+ console.error(
129
+ "ArkFlow for Magpie: rejected service request",
130
+ request.method,
131
+ request.url,
132
+ "origin=" + String(request.headers.origin || "-"),
133
+ )
134
+ json(response, 403, { error: "Loopback service accepts only its Magpie page" })
135
+ return
136
+ }
137
+ const url = new URL(request.url, `http://${hostName}:${actualPort}`)
138
+ // Only token-protected API responses need CORS in the opaque sandbox.
139
+ // Granting Origin:null access to HTML would let ANY website's sandbox
140
+ // fetch the embedded command token. Frame navigation and classic static
141
+ // scripts/styles do not need that grant.
142
+ if (url.pathname.startsWith("/api/") && (request.headers.origin === "null" || MAGPIE_DESKTOP_ORIGINS.has(request.headers.origin))) {
143
+ response.setHeader("access-control-allow-origin", request.headers.origin)
144
+ response.setHeader("vary", "Origin")
145
+ if (request.method === "OPTIONS") {
146
+ response.statusCode = 204
147
+ response.setHeader("access-control-allow-methods", "GET,POST,OPTIONS")
148
+ response.setHeader("access-control-allow-headers", "content-type,x-novaflow-page-token")
149
+ response.setHeader("access-control-max-age", "600")
150
+ response.end()
151
+ return
152
+ }
153
+ }
154
+ try {
155
+ if (request.method === "GET" && STATIC.has(url.pathname)) {
156
+ const [file, type] = STATIC.get(url.pathname)
157
+ let body = await readFile(join(ROOT, file))
158
+ if (file === "service.html") {
159
+ body = body.toString("utf8")
160
+ .replace("__CSRF_TOKEN__", csrfToken)
161
+ .replace("__NOVAFLOW_ORIGIN__", config.origin)
162
+ }
163
+ response.setHeader("content-type", type)
164
+ response.end(body)
165
+ return
166
+ }
167
+ if (url.pathname.startsWith("/api/")) {
168
+ if (request.headers["x-novaflow-page-token"] !== csrfToken) {
169
+ json(response, 403, { error: "Missing page command token", code: "PAGE_TOKEN_INVALID" })
170
+ return
171
+ }
172
+ diagnostics.commandCount++
173
+ const state = () => {
174
+ const identity = session.projection()
175
+ const skillState = skills.projection()
176
+ if (identity.accountMode !== "enterprise" || !identity.capabilities?.company_skills) {
177
+ skillState.catalog = []
178
+ skillState.store = null
179
+ skillState.entries = []
180
+ skillState.count = 0
181
+ }
182
+ return noSecretProjection({
183
+ service: {
184
+ origin: config.origin,
185
+ loopbackPort: actualPort,
186
+ pluginVersion: config.pluginVersion,
187
+ hostVersion,
188
+ hostMinVersion: config.hostMinVersion,
189
+ compatible: true,
190
+ },
191
+ session: session.projection(),
192
+ sync: { ...sync.projection(), skills: skillState },
193
+ accounts: accounts.projection(),
194
+ skills: skillState,
195
+ defaults: defaults.status(),
196
+ preferences: {},
197
+ hostLibrary: {
198
+ available: host.available,
199
+ version: host.version,
200
+ source: "magpie-cli",
201
+ error: host.lastError,
202
+ },
203
+ diagnostics: {
204
+ requestCode: sync.projection().errorCode,
205
+ requestId: sync.projection().requestId,
206
+ commands: diagnostics.commandCount,
207
+ },
208
+ })
209
+ }
210
+ if (request.method === "GET" && url.pathname === "/api/state") {
211
+ json(response, 200, control ? noSecretProjection(await control.command({ operation: "status" })) : state())
212
+ return
213
+ }
214
+ if (request.method === "POST" && url.pathname === "/api/command" && control) {
215
+ const body = await readJson(request)
216
+ const result = await control.command({ operation: String(body.operation || ""), payload: body.payload || {} })
217
+ json(response, 200, noSecretProjection(result))
218
+ return
219
+ }
220
+ if (request.method === "POST" && url.pathname === "/api/open-website") {
221
+ await readJson(request)
222
+ await host.openWebsite()
223
+ json(response, 200, { opened: true })
224
+ return
225
+ }
226
+ if (request.method === "GET" && url.pathname === "/api/local-skills") {
227
+ if (session.projection().accountMode !== "enterprise" || !session.projection().capabilities?.company_skills) {
228
+ json(response, 403, { error: "企业用户才可使用技能功能" })
229
+ return
230
+ }
231
+ json(response, 200, await host.listSkills())
232
+ return
233
+ }
234
+ if (request.method === "GET" && url.pathname === "/api/agents") {
235
+ if (session.projection().accountMode !== "enterprise" || !session.projection().capabilities?.company_skills) { json(response, 403, { error: "企业用户才可使用技能功能" }); return }
236
+ json(response, 200, { agents: await host.listAgents() })
237
+ return
238
+ }
239
+ if (request.method === "POST" && url.pathname === "/api/sync") {
240
+ await readJson(request)
241
+ await sync.syncNow("page")
242
+ json(response, 200, state())
243
+ return
244
+ }
245
+ if (request.method === "POST" && url.pathname === "/api/logout") {
246
+ await readJson(request)
247
+ json(response, 200, await control.command({ operation: "logout" }))
248
+ return
249
+ }
250
+ if (request.method === "POST" && url.pathname === "/api/preferences") {
251
+ await readJson(request)
252
+ json(response, 410, { error: "本机技能关联设置已移除", code: "PLUGIN_PREFERENCES_RETIRED" })
253
+ return
254
+ }
255
+ if (request.method === "POST" && url.pathname === "/api/config") {
256
+ await readJson(request)
257
+ json(response, 410, { error: "Company recommendation configuration has been retired", code: "PLUGIN_CONFIG_RETIRED" })
258
+ return
259
+ }
260
+ if (request.method === "POST" && url.pathname === "/api/skills/share") {
261
+ if (session.projection().accountMode !== "enterprise" || !session.projection().capabilities?.contribute_skills) {
262
+ json(response, 403, { error: "This account cannot contribute company skills" })
263
+ return
264
+ }
265
+ const body = await readJson(request)
266
+ const result = await skillManager.share({
267
+ sourceName: String(body.sourceName ?? ""),
268
+ display_name: String(body.display_name ?? body.displayName ?? ""),
269
+ description: body.description === undefined ? undefined : String(body.description),
270
+ category_id: String(body.category_id ?? ""),
271
+ updateSkillId: body.updateSkillId ? String(body.updateSkillId) : "",
272
+ expectedVersion: Number(body.expectedVersion ?? 0),
273
+ idempotencyKey: String(body.idempotencyKey ?? ""),
274
+ previewHash: String(body.previewHash || ""),
275
+ })
276
+ json(response, 200, { result, state: state() })
277
+ return
278
+ }
279
+ if (request.method === "POST" && url.pathname === "/api/skills/remove") {
280
+ if (session.projection().accountMode !== "enterprise" || !session.projection().capabilities?.company_skills) { json(response, 403, { error: "企业用户才可使用技能功能" }); return }
281
+ const body = await readJson(request)
282
+ const entry = skills.registry[String(body.skillId ?? "")]
283
+ if (!entry || !ALIAS_RE.test(entry.alias)) throw new Error("Managed skill was not found")
284
+ const removed = await host.removeSkill(entry.alias)
285
+ entry.registration = removed.registered ? "failed" : "removed"
286
+ skills.persist()
287
+ json(response, 200, state())
288
+ return
289
+ }
290
+ json(response, 404, { error: "Unknown typed command" })
291
+ return
292
+ }
293
+ json(response, 404, { error: "Not found" })
294
+ } catch (error) {
295
+ diagnostics.lastError = String(error?.code || "PAGE_COMMAND_FAILED")
296
+ json(response, Number(error?.status) || 400, {
297
+ error: String(error?.message ?? "Page command failed").slice(0, 300),
298
+ code: String(error?.code ?? "PAGE_COMMAND_FAILED"),
299
+ requestId: String(error?.requestId ?? ""),
300
+ })
301
+ }
302
+ })
303
+
304
+ server.on("listening", () => {
305
+ const address = server.address()
306
+ if (address && typeof address === "object") actualPort = address.port
307
+ })
308
+
309
+ let starting = null
310
+ return {
311
+ server,
312
+ get port() {
313
+ return actualPort
314
+ },
315
+ start() {
316
+ if (server.listening) return Promise.resolve()
317
+ if (starting) return starting
318
+ starting = this.listen().finally(() => { starting = null })
319
+ return starting
320
+ },
321
+ async listen() {
322
+ if (server.listening) return
323
+ // A restarted Magpie can still be draining the previous host for a
324
+ // moment; wait briefly for the fixed port instead of failing the whole
325
+ // page for the rest of the session.
326
+ const deadline = Date.now() + 15_000
327
+ for (;;) {
328
+ try {
329
+ await new Promise((resolve, reject) => {
330
+ const onError = (error) => {
331
+ server.off("listening", onListening)
332
+ reject(error)
333
+ }
334
+ const onListening = () => {
335
+ server.off("error", onError)
336
+ resolve()
337
+ }
338
+ server.once("error", onError)
339
+ server.once("listening", onListening)
340
+ server.listen(port, hostName)
341
+ })
342
+ return
343
+ } catch (error) {
344
+ const busy = error?.code === "EADDRINUSE" || /in use/i.test(String(error?.message || ""))
345
+ if (!busy || Date.now() >= deadline) throw error
346
+ await new Promise((resolve) => setTimeout(resolve, 500))
347
+ }
348
+ }
349
+ },
350
+ async stop() {
351
+ if (starting) await starting.catch(() => {})
352
+ if (!server.listening) return
353
+ await new Promise((resolve) => server.close(resolve))
354
+ },
355
+ }
356
+ }
357
+
358
+ export { noSecretProjection }
@@ -0,0 +1,44 @@
1
+ import { assertSupportedHost } from "./config.mjs"
2
+
3
+ function usageConversion(value) {
4
+ if (!value || typeof value !== "object") return { error: "ArkFlow usage is unavailable", windows: [] }
5
+ const mode = value.account_mode
6
+ if (mode !== "personal" && mode !== "enterprise") return { error: "ArkFlow identity mode is unavailable", windows: [] }
7
+ const unit = typeof value.unit === "string" && value.unit ? value.unit : ""
8
+ const amount = (number) => {
9
+ const text = number === null || number === undefined ? "unknown" : String(number)
10
+ return text === "unknown" ? text : `${text}${unit ? " " + unit : " (unit unknown)"}`
11
+ }
12
+ const windows = []
13
+ if (value.limits) {
14
+ for (const [name, period] of [["Daily", "daily"], ["Monthly", "monthly"]]) {
15
+ if (value.limits[`${period}_mode`] !== "limited") continue
16
+ const limit = Number(value.limits[`${period}_limit`])
17
+ const used = Number(value.limits[`${period}_used`])
18
+ if (Number.isFinite(limit) && limit > 0 && Number.isFinite(used)) {
19
+ windows.push({
20
+ name,
21
+ used: Math.max(0, (used / limit) * 100),
22
+ display: `${amount(value.limits[`${period}_used`])} / ${amount(value.limits[`${period}_limit`])}`,
23
+ aside: false,
24
+ })
25
+ }
26
+ }
27
+ }
28
+ const wallet = mode === "enterprise" ? value.company : value.personal
29
+ return {
30
+ plan: mode === "enterprise" ? "ArkFlow Enterprise" : "ArkFlow Personal",
31
+ user: value.display_name || "",
32
+ balance: amount(wallet?.available),
33
+ windows,
34
+ }
35
+ }
36
+
37
+ // The package runs a page service only; native per-Key providers own models.
38
+ // Do not register an account-only provider with an empty model catalog.
39
+ export function createNovaFlowProvider({ config, hostVersion = config.hostMinVersion }) {
40
+ assertSupportedHost(hostVersion)
41
+ return {}
42
+ }
43
+
44
+ export { usageConversion }