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
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { ApiClient } from "./api-client.mjs"
|
|
2
|
+
import { AccountManager } from "./accounts.mjs"
|
|
3
|
+
import { PRODUCTION_CONFIG, servicePort, assertSupportedHost, compareVersions } from "./config.mjs"
|
|
4
|
+
import { CredentialLoader } from "./credentials.mjs"
|
|
5
|
+
import { MagpieHostAdapter } from "./host-adapter.mjs"
|
|
6
|
+
import { ManualInitialization } from "./manual-initialization.mjs"
|
|
7
|
+
import { createPageServer } from "./page-service.mjs"
|
|
8
|
+
import { createNovaFlowProvider } from "./provider.mjs"
|
|
9
|
+
import { SessionManager } from "./session.mjs"
|
|
10
|
+
import { SkillManager } from "./skills.mjs"
|
|
11
|
+
import { JsonStore, defaultDataDir, randomId, secureMkdir } from "./state-store.mjs"
|
|
12
|
+
import { SyncEngine } from "./sync-engine.mjs"
|
|
13
|
+
import { createNativeControl } from "./native-control.mjs"
|
|
14
|
+
import { NativeProviderSync } from "./native-providers.mjs"
|
|
15
|
+
import { readFile } from "node:fs/promises"
|
|
16
|
+
import { assertSingleInstallation } from "./install-identity.mjs"
|
|
17
|
+
|
|
18
|
+
let singleton = null
|
|
19
|
+
let initializing = null
|
|
20
|
+
|
|
21
|
+
function hostDirectory(input) {
|
|
22
|
+
const directory = input?.directory
|
|
23
|
+
if (typeof directory !== "string" || !directory) {
|
|
24
|
+
throw new Error("Magpie did not provide input.directory; refusing to write private ArkFlow state")
|
|
25
|
+
}
|
|
26
|
+
return directory
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function getRuntime(input, options = {}) {
|
|
30
|
+
if (initializing) {
|
|
31
|
+
const runtime = await initializing
|
|
32
|
+
runtime.attachInput(input)
|
|
33
|
+
return runtime
|
|
34
|
+
}
|
|
35
|
+
if (singleton) {
|
|
36
|
+
singleton.attachInput(input)
|
|
37
|
+
if (process.env.NOVAFLOW_PLUGIN_DISABLE_SERVICE !== "1") void singleton.start()
|
|
38
|
+
return singleton
|
|
39
|
+
}
|
|
40
|
+
initializing = initializeRuntime(input, options)
|
|
41
|
+
try { return await initializing }
|
|
42
|
+
catch (error) {
|
|
43
|
+
const failed = singleton
|
|
44
|
+
singleton = null
|
|
45
|
+
if (failed) await failed.stop()
|
|
46
|
+
throw error
|
|
47
|
+
} finally { initializing = null }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function initializeRuntime(input, options = {}) {
|
|
51
|
+
if (process.env.NOVAFLOW_PLUGIN_CLI_CHILD === "1") throw new Error("ArkFlow runtime is disabled in CLI children")
|
|
52
|
+
if (singleton) {
|
|
53
|
+
singleton.attachInput(input)
|
|
54
|
+
return singleton
|
|
55
|
+
}
|
|
56
|
+
const port = servicePort(options.servicePort)
|
|
57
|
+
const temporaryService = port !== PRODUCTION_CONFIG.servicePort
|
|
58
|
+
const config = Object.freeze({ ...PRODUCTION_CONFIG, servicePort: port })
|
|
59
|
+
const directory = hostDirectory(input)
|
|
60
|
+
assertSingleInstallation(directory)
|
|
61
|
+
const dataDir = defaultDataDir(directory)
|
|
62
|
+
secureMkdir(dataDir)
|
|
63
|
+
|
|
64
|
+
const api = new ApiClient(config)
|
|
65
|
+
const accounts = new AccountManager({
|
|
66
|
+
store: new JsonStore(`${dataDir}/keys.json`, { revision: "", ownedKeyIds: [], rows: [], updatedAt: "" }),
|
|
67
|
+
})
|
|
68
|
+
const session = new SessionManager({
|
|
69
|
+
api,
|
|
70
|
+
store: new JsonStore(`${dataDir}/session.json`, {
|
|
71
|
+
status: "signed_out",
|
|
72
|
+
accountId: "",
|
|
73
|
+
access: "",
|
|
74
|
+
refresh: "",
|
|
75
|
+
expiresAt: 0,
|
|
76
|
+
generation: 0,
|
|
77
|
+
}),
|
|
78
|
+
})
|
|
79
|
+
const credentials = new CredentialLoader({ api, session, accounts, config })
|
|
80
|
+
const host = new MagpieHostAdapter({
|
|
81
|
+
magpiePath: options.magpiePath || process.env.MAGPIE_CLI_PATH || process.env.MAGPIE_BIN || "",
|
|
82
|
+
directory: input.directory,
|
|
83
|
+
})
|
|
84
|
+
const hostAvailable = await host.initialize()
|
|
85
|
+
const hostVersion = host.version || config.hostMinVersion
|
|
86
|
+
if (hostAvailable && compareVersions(hostVersion, config.hostMinVersion) < 0) {
|
|
87
|
+
assertSupportedHost(hostVersion)
|
|
88
|
+
}
|
|
89
|
+
const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"))
|
|
90
|
+
const nativeProviders = new NativeProviderSync({
|
|
91
|
+
directory: input.directory, config, host, accounts, session, api,
|
|
92
|
+
icon: pkg.magpie?.icon || "",
|
|
93
|
+
store: new JsonStore(`${dataDir}/native-providers.json`, { entries: {} }),
|
|
94
|
+
})
|
|
95
|
+
const preferencesStore = new JsonStore(`${dataDir}/preferences.json`, {
|
|
96
|
+
targetAgents: [],
|
|
97
|
+
autoSyncSkills: false,
|
|
98
|
+
})
|
|
99
|
+
const preferences = preferencesStore.read()
|
|
100
|
+
const instanceStore = new JsonStore(`${dataDir}/instance.json`, { instanceId: "" })
|
|
101
|
+
const instance = instanceStore.read()
|
|
102
|
+
if (!instance.instanceId) {
|
|
103
|
+
instance.instanceId = randomId(24)
|
|
104
|
+
instanceStore.write(instance)
|
|
105
|
+
}
|
|
106
|
+
const defaults = new ManualInitialization({
|
|
107
|
+
host, accounts, directory: input.directory,
|
|
108
|
+
markerStore: new JsonStore(`${dataDir}/install-defaults-marker.json`, {
|
|
109
|
+
status: "wait_config",
|
|
110
|
+
reason: "wait_config",
|
|
111
|
+
instanceId: instance.instanceId,
|
|
112
|
+
fields: {},
|
|
113
|
+
}),
|
|
114
|
+
backupStore: new JsonStore(`${dataDir}/install-defaults-backup.json`, {}),
|
|
115
|
+
})
|
|
116
|
+
const skillManager = new SkillManager({
|
|
117
|
+
dataDir,
|
|
118
|
+
host,
|
|
119
|
+
api,
|
|
120
|
+
session,
|
|
121
|
+
store: new JsonStore(`${dataDir}/skill-registry.json`, { entries: {} }),
|
|
122
|
+
})
|
|
123
|
+
const sync = new SyncEngine({
|
|
124
|
+
config,
|
|
125
|
+
api,
|
|
126
|
+
session,
|
|
127
|
+
credentials,
|
|
128
|
+
accounts,
|
|
129
|
+
nativeProviders,
|
|
130
|
+
skills: skillManager,
|
|
131
|
+
defaults,
|
|
132
|
+
preferences,
|
|
133
|
+
hostVersion,
|
|
134
|
+
instanceId: instance.instanceId,
|
|
135
|
+
snapshotStore: new JsonStore(`${dataDir}/sync-state.json`, { state: null }),
|
|
136
|
+
})
|
|
137
|
+
const diagnostics = { phase: "starting", lastSuccessAt: "", recoveryCount: 0, errorCode: "" }
|
|
138
|
+
const control = createNativeControl({
|
|
139
|
+
diagnostics,
|
|
140
|
+
config,
|
|
141
|
+
session,
|
|
142
|
+
sync,
|
|
143
|
+
accounts,
|
|
144
|
+
nativeProviders,
|
|
145
|
+
skills: skillManager,
|
|
146
|
+
host,
|
|
147
|
+
api,
|
|
148
|
+
preferencesStore,
|
|
149
|
+
defaults,
|
|
150
|
+
hostVersion,
|
|
151
|
+
})
|
|
152
|
+
const page = createPageServer({
|
|
153
|
+
config,
|
|
154
|
+
session,
|
|
155
|
+
sync,
|
|
156
|
+
accounts,
|
|
157
|
+
skills: skillManager,
|
|
158
|
+
control,
|
|
159
|
+
skillManager,
|
|
160
|
+
api,
|
|
161
|
+
host,
|
|
162
|
+
defaults,
|
|
163
|
+
preferencesStore,
|
|
164
|
+
hostVersion,
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
let hooks = null, starting = null, retryTimer = null, stopped = false
|
|
168
|
+
const runtime = {
|
|
169
|
+
config,
|
|
170
|
+
dataDir,
|
|
171
|
+
api,
|
|
172
|
+
accounts,
|
|
173
|
+
nativeProviders,
|
|
174
|
+
session,
|
|
175
|
+
credentials,
|
|
176
|
+
host,
|
|
177
|
+
sync,
|
|
178
|
+
skillManager,
|
|
179
|
+
defaults,
|
|
180
|
+
page,
|
|
181
|
+
hooks,
|
|
182
|
+
control,
|
|
183
|
+
attachInput(nextInput) {
|
|
184
|
+
const directory = hostDirectory(nextInput)
|
|
185
|
+
if (directory !== input.directory) throw new Error("Magpie changed input.directory while the plugin host was running")
|
|
186
|
+
if (nextInput.client) runtime.client = nextInput.client
|
|
187
|
+
},
|
|
188
|
+
diagnostics,
|
|
189
|
+
start() {
|
|
190
|
+
if (stopped || page.server.listening) return Promise.resolve()
|
|
191
|
+
if (starting) return starting
|
|
192
|
+
clearTimeout(retryTimer)
|
|
193
|
+
diagnostics.phase = "starting"
|
|
194
|
+
starting = page.start().then(() => {
|
|
195
|
+
diagnostics.phase = "ready"
|
|
196
|
+
diagnostics.lastSuccessAt = new Date().toISOString()
|
|
197
|
+
diagnostics.errorCode = ""
|
|
198
|
+
runtime.serviceError = ""
|
|
199
|
+
}).catch(error => {
|
|
200
|
+
diagnostics.phase = "waiting"
|
|
201
|
+
diagnostics.errorCode = String(error?.code || "SERVICE_START_FAILED")
|
|
202
|
+
runtime.serviceError = diagnostics.errorCode
|
|
203
|
+
diagnostics.recoveryCount++
|
|
204
|
+
console.error("ArkFlow for Magpie: page service unavailable: " + diagnostics.errorCode)
|
|
205
|
+
if (!stopped) {
|
|
206
|
+
retryTimer = setTimeout(() => void runtime.start(), Math.min(30_000, 2000 * diagnostics.recoveryCount))
|
|
207
|
+
retryTimer.unref?.()
|
|
208
|
+
}
|
|
209
|
+
}).finally(() => { starting = null })
|
|
210
|
+
return starting
|
|
211
|
+
},
|
|
212
|
+
async stop() {
|
|
213
|
+
control.stop()
|
|
214
|
+
stopped = true
|
|
215
|
+
clearTimeout(retryTimer)
|
|
216
|
+
sync.stop()
|
|
217
|
+
if (starting) await starting
|
|
218
|
+
await page.stop()
|
|
219
|
+
},
|
|
220
|
+
}
|
|
221
|
+
singleton = runtime
|
|
222
|
+
// Bind the page before migrations, Library work or remote synchronization.
|
|
223
|
+
if (process.env.NOVAFLOW_PLUGIN_DISABLE_SERVICE !== "1") void runtime.start()
|
|
224
|
+
runtime.client = input.client
|
|
225
|
+
hooks = createNovaFlowProvider({
|
|
226
|
+
client: input.client,
|
|
227
|
+
config,
|
|
228
|
+
api,
|
|
229
|
+
session,
|
|
230
|
+
accounts,
|
|
231
|
+
control,
|
|
232
|
+
credentials,
|
|
233
|
+
sync,
|
|
234
|
+
hostVersion,
|
|
235
|
+
report: (event, details) => {
|
|
236
|
+
if (process.env.NOVAFLOW_PLUGIN_DIAGNOSTICS === "1") {
|
|
237
|
+
console.error("ArkFlow for Magpie: " + JSON.stringify({ event, ...details }))
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
})
|
|
241
|
+
runtime.hooks = hooks
|
|
242
|
+
session.onChange((projection, reason) => {
|
|
243
|
+
if (projection.status !== "authenticated" || reason === "account-switch" || reason === "login" || reason === "credentials-cleared") {
|
|
244
|
+
accounts.disposeOwnedOnly()
|
|
245
|
+
skillManager.storeCatalog = null
|
|
246
|
+
skillManager.catalogProjection = []
|
|
247
|
+
skillManager.persist()
|
|
248
|
+
sync.resetSession()
|
|
249
|
+
}
|
|
250
|
+
if (projection.status === "authenticated") {
|
|
251
|
+
if (reason === "account-switch" || reason === "login") {
|
|
252
|
+
void nativeProviders.clearForeign().catch(() => { runtime.nativeCleanupFailed = true })
|
|
253
|
+
}
|
|
254
|
+
sync.start()
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
sync.stop("ArkFlow session is no longer usable")
|
|
258
|
+
void nativeProviders.clear().catch(() => { runtime.nativeCleanupFailed = true })
|
|
259
|
+
})
|
|
260
|
+
// Page startup and the host hook return must not wait for filesystem
|
|
261
|
+
// migration, host auth cleanup or remote model discovery.
|
|
262
|
+
runtime.ready = (async () => {
|
|
263
|
+
// Non-page CLI hosts receive a private temporary port from Magpie. They
|
|
264
|
+
// must not run background account migrations or mutate native connections.
|
|
265
|
+
if (temporaryService) return
|
|
266
|
+
// Retire only the old account placeholder, never per-Key connections.
|
|
267
|
+
const legacyEntryRemoved = await nativeProviders.retireLegacyEntry()
|
|
268
|
+
// Resume the current account before optional legacy auth cleanup, which
|
|
269
|
+
// may depend on a host bridge that is not answering.
|
|
270
|
+
if (session.internalAuth()?.access?.startsWith("nfpc_")) {
|
|
271
|
+
accounts.disposeOwnedOnly()
|
|
272
|
+
sync.resetSession()
|
|
273
|
+
session.state.status = "reauthorize"
|
|
274
|
+
session.state.access = session.state.refresh = ""
|
|
275
|
+
session.persist()
|
|
276
|
+
} else if (session.internalAuth()) {
|
|
277
|
+
await nativeProviders.clearForeign()
|
|
278
|
+
if (!stopped) sync.start()
|
|
279
|
+
} else if (session.projection().status !== "reauthorize" && Object.keys(nativeProviders.store.read().entries || {}).length) {
|
|
280
|
+
await nativeProviders.clear()
|
|
281
|
+
}
|
|
282
|
+
const migrationStore = new JsonStore(`${dataDir}/page-login-migration.json`, {})
|
|
283
|
+
if (!migrationStore.read().hostAuthRetired && (legacyEntryRemoved || session.internalAuth()) && input.client?.auth?.remove) {
|
|
284
|
+
try {
|
|
285
|
+
await input.client.auth.remove({ path: { id: "novaflow" } })
|
|
286
|
+
migrationStore.write({ hostAuthRetired: true })
|
|
287
|
+
} catch { runtime.legacyAuthCleanupPending = true }
|
|
288
|
+
}
|
|
289
|
+
})().catch(error => {
|
|
290
|
+
runtime.initializationError = String(error?.code || "INITIALIZATION_PENDING")
|
|
291
|
+
if (!stopped && !temporaryService && session.internalAuth()) sync.start()
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
return runtime
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export async function resetRuntimeForTest() {
|
|
298
|
+
if (initializing) await initializing.catch(() => {})
|
|
299
|
+
if (!singleton) return
|
|
300
|
+
await singleton.stop()
|
|
301
|
+
singleton = null
|
|
302
|
+
}
|
package/src/session.mjs
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { JsonStore, randomId, stableId } from "./state-store.mjs"
|
|
3
|
+
|
|
4
|
+
const OAUTH_REQUIRED = new Set([
|
|
5
|
+
"PLUGIN_SESSION_REVOKED",
|
|
6
|
+
"PLUGIN_IDENTITY_UNAVAILABLE",
|
|
7
|
+
"PLUGIN_COMPANY_INACTIVE",
|
|
8
|
+
"PLUGIN_MEMBERSHIP_INACTIVE",
|
|
9
|
+
])
|
|
10
|
+
|
|
11
|
+
export class SessionManager {
|
|
12
|
+
constructor({ api, store, now = () => Date.now() }) {
|
|
13
|
+
this.api = api
|
|
14
|
+
this.store = store ?? new JsonStore("", {})
|
|
15
|
+
this.now = now
|
|
16
|
+
this.state = this.store.read()
|
|
17
|
+
this.savedState = JSON.stringify(this.state)
|
|
18
|
+
this.generation = Number.isSafeInteger(this.state.generation) ? this.state.generation : 0
|
|
19
|
+
this.refreshing = new Map()
|
|
20
|
+
this.listeners = new Set()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
onChange(listener) {
|
|
24
|
+
this.listeners.add(listener)
|
|
25
|
+
return () => this.listeners.delete(listener)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
emit(reason) {
|
|
29
|
+
for (const listener of this.listeners) {
|
|
30
|
+
try {
|
|
31
|
+
listener(this.projection(), reason)
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
persist() {
|
|
37
|
+
if (JSON.stringify(this.store.read()) !== this.savedState) {
|
|
38
|
+
this.reload()
|
|
39
|
+
throw Object.assign(new Error("ArkFlow session changed before saving"), { code: "PLUGIN_SESSION_CHANGED" })
|
|
40
|
+
}
|
|
41
|
+
this.state.generation = this.generation
|
|
42
|
+
this.state.sessionRevision = randomId()
|
|
43
|
+
this.store.write(this.state)
|
|
44
|
+
this.savedState = JSON.stringify(this.store.read())
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
reload() {
|
|
48
|
+
const next = this.store.read()
|
|
49
|
+
const saved = JSON.stringify(next)
|
|
50
|
+
if (saved === this.savedState) return false
|
|
51
|
+
const previous = this.state
|
|
52
|
+
this.state = next
|
|
53
|
+
this.savedState = saved
|
|
54
|
+
const credentialChanged = previous.access !== next.access || previous.refresh !== next.refresh
|
|
55
|
+
const loginChanged = credentialChanged || previous.loginRevision !== next.loginRevision || previous.status !== next.status
|
|
56
|
+
// A login in another process invalidates work even if it reused a key
|
|
57
|
+
// and persisted the same generation as this process.
|
|
58
|
+
if (loginChanged || previous.accountId !== next.accountId) this.generation = Math.max(this.generation + 1, Number(next.generation) || 0)
|
|
59
|
+
this.emit(previous.accountId !== next.accountId ? "account-switch" : loginChanged ? "login" : "session-reloaded")
|
|
60
|
+
return true
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
ownership() {
|
|
64
|
+
this.reload()
|
|
65
|
+
return stableId(this.state.status, this.state.accountId, this.state.access, this.state.refresh, this.state.loginRevision)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
assertOwnership(owner) {
|
|
69
|
+
this.reload()
|
|
70
|
+
if (owner !== this.ownership()) {
|
|
71
|
+
throw Object.assign(new Error("ArkFlow session changed; retry with the current account"), { code: "PLUGIN_SESSION_CHANGED" })
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
projection() {
|
|
76
|
+
this.reload()
|
|
77
|
+
const authenticated = this.state.status === "authenticated"
|
|
78
|
+
return {
|
|
79
|
+
status: this.state.status ?? "signed_out",
|
|
80
|
+
setup: authenticated && this.state.setupStage ? { id: this.state.loginRevision, stage: this.state.setupStage } : null,
|
|
81
|
+
userId: authenticated ? this.state.userId ?? null : null,
|
|
82
|
+
displayName: authenticated ? this.state.displayName ?? "" : "",
|
|
83
|
+
accountMode: authenticated ? this.state.accountMode ?? null : null,
|
|
84
|
+
role: authenticated ? this.state.role ?? null : null,
|
|
85
|
+
capabilities: authenticated ? this.state.bootstrap?.capabilities ?? {} : {},
|
|
86
|
+
company: authenticated && this.state.bootstrap?.company ? {
|
|
87
|
+
id: this.state.bootstrap.company.id,
|
|
88
|
+
displayName: this.state.bootstrap.company.display_name,
|
|
89
|
+
timezone: this.state.bootstrap.company.timezone,
|
|
90
|
+
status: this.state.bootstrap.company.status,
|
|
91
|
+
} : null,
|
|
92
|
+
generation: this.generation,
|
|
93
|
+
logoutSynced: this.state.logoutSynced !== false,
|
|
94
|
+
lastError: this.state.lastError ?? "",
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
internalAuth() {
|
|
99
|
+
this.reload()
|
|
100
|
+
if (this.state.status !== "authenticated" || !this.state.access) return null
|
|
101
|
+
return {
|
|
102
|
+
access: this.state.access,
|
|
103
|
+
refresh: this.state.refresh,
|
|
104
|
+
expiresAt: this.state.expiresAt,
|
|
105
|
+
userId: this.state.userId,
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async acceptLogin(result, { owner, signal } = {}) {
|
|
110
|
+
// Provider credentials enter the same session boundary as token pairs.
|
|
111
|
+
const access = result?.access_token ?? result?.access
|
|
112
|
+
const refresh = result?.refresh_token ?? result?.refresh
|
|
113
|
+
if (!access || !refresh) throw new Error("ArkFlow login returned no token pair")
|
|
114
|
+
const bootstrap = await this.api.bootstrap(access, signal)
|
|
115
|
+
signal?.throwIfAborted()
|
|
116
|
+
if (!bootstrap || bootstrap.schema_version !== 1) {
|
|
117
|
+
throw Object.assign(new Error("ArkFlow contract schema is unsupported"), { code: "PLUGIN_SCHEMA_UNSUPPORTED" })
|
|
118
|
+
}
|
|
119
|
+
if (owner !== undefined) this.assertOwnership(owner)
|
|
120
|
+
else this.reload()
|
|
121
|
+
const previousAccount = this.state.accountId
|
|
122
|
+
const credential = stableId(access, refresh)
|
|
123
|
+
const supersededCredentials = new Set(this.state.supersededCredentials ?? [])
|
|
124
|
+
if (this.state.access && this.state.refresh) supersededCredentials.add(stableId(this.state.access, this.state.refresh))
|
|
125
|
+
supersededCredentials.delete(credential)
|
|
126
|
+
this.generation++
|
|
127
|
+
const accountId = String(bootstrap.user_id ?? result.accountId ?? stableId(access).slice(0, 24))
|
|
128
|
+
this.state = {
|
|
129
|
+
status: "authenticated",
|
|
130
|
+
accountId,
|
|
131
|
+
userId: String(bootstrap.user_id ?? ""),
|
|
132
|
+
displayName: String(bootstrap.display_name ?? ""),
|
|
133
|
+
accountMode: bootstrap.account_mode === "enterprise" ? "enterprise" : "personal",
|
|
134
|
+
role: String(bootstrap.role ?? ""),
|
|
135
|
+
access: String(access),
|
|
136
|
+
refresh: String(refresh),
|
|
137
|
+
sessionId: result.session_id || "",
|
|
138
|
+
expiresAt: result.refresh_token_rotation === "none" && result.expires_in === null ? 0 : Number(result.expires || this.now() + Number(result.expires_in ?? 7200) * 1000),
|
|
139
|
+
bootstrap,
|
|
140
|
+
loginRevision: randomId(),
|
|
141
|
+
setupStage: "sync",
|
|
142
|
+
setupPid: process.pid,
|
|
143
|
+
supersededCredentials: [...supersededCredentials].slice(-32),
|
|
144
|
+
localLogout: false,
|
|
145
|
+
logoutSynced: true,
|
|
146
|
+
lastError: "",
|
|
147
|
+
generation: this.generation,
|
|
148
|
+
}
|
|
149
|
+
this.persist()
|
|
150
|
+
this.emit(previousAccount && previousAccount !== accountId ? "account-switch" : "login")
|
|
151
|
+
return { accountId, bootstrap }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
setSetupStage(id, from, stage, { worker = false } = {}) {
|
|
155
|
+
const setup = this.projection().setup
|
|
156
|
+
if (!setup || setup.id !== id || setup.stage !== from) return false
|
|
157
|
+
const pid = this.state.setupPid
|
|
158
|
+
if (worker && pid && pid !== process.pid) {
|
|
159
|
+
try { process.kill(pid, 0); return false } catch (error) { if (error.code !== "ESRCH") return false }
|
|
160
|
+
}
|
|
161
|
+
this.state.setupPid = process.pid
|
|
162
|
+
this.state.setupStage = stage
|
|
163
|
+
this.persist()
|
|
164
|
+
return true
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async activateAuth(auth) {
|
|
168
|
+
this.reload()
|
|
169
|
+
if (!auth || auth.type !== "oauth" || !auth.access || !auth.refresh) {
|
|
170
|
+
throw Object.assign(new Error("Sign in to ArkFlow in Magpie"), { signIn: "expired" })
|
|
171
|
+
}
|
|
172
|
+
// Magpie shows the provider's display name as accountId. ArkFlow's
|
|
173
|
+
// stable identity travels beside it in uid, so a UI label change never
|
|
174
|
+
// looks like a different account and invalidates an in-flight sync.
|
|
175
|
+
// Accounts saved before uid existed are matched by their token pair.
|
|
176
|
+
const sameSecret = this.state.access === auth.access || this.state.refresh === auth.refresh
|
|
177
|
+
const accountId = String(auth.uid || (sameSecret ? this.state.accountId : "") || stableId(auth.access).slice(0, 24))
|
|
178
|
+
if (this.state.localLogout && (sameSecret || this.state.loggedOutCredential === stableId(auth.access, auth.refresh))) {
|
|
179
|
+
throw Object.assign(new Error("ArkFlow was signed out here; sign in again in Magpie"), { signIn: "expired" })
|
|
180
|
+
}
|
|
181
|
+
if (this.state.supersededCredentials?.includes(stableId(auth.access, auth.refresh))) {
|
|
182
|
+
throw Object.assign(new Error("ArkFlow credentials were replaced; use the current sign-in"), { code: "PLUGIN_SESSION_CHANGED" })
|
|
183
|
+
}
|
|
184
|
+
if (
|
|
185
|
+
this.state.status === "authenticated"
|
|
186
|
+
&& this.state.accountId === accountId
|
|
187
|
+
&& sameSecret
|
|
188
|
+
&& Number(this.state.expiresAt ?? 0) >= Number(auth.expires ?? 0)
|
|
189
|
+
&& this.state.access
|
|
190
|
+
&& this.state.refresh
|
|
191
|
+
) {
|
|
192
|
+
return this.internalAuth()
|
|
193
|
+
}
|
|
194
|
+
const switched = !!this.state.accountId && this.state.accountId !== accountId
|
|
195
|
+
const changed = switched || !sameSecret
|
|
196
|
+
if (changed) {
|
|
197
|
+
// Read the identity with the incoming credential before publishing it;
|
|
198
|
+
// no request or page may pair the new credential with the old user.
|
|
199
|
+
await this.acceptLogin(auth, { owner: this.ownership() })
|
|
200
|
+
return this.internalAuth()
|
|
201
|
+
}
|
|
202
|
+
this.state = {
|
|
203
|
+
...this.state,
|
|
204
|
+
status: "authenticated",
|
|
205
|
+
accountId,
|
|
206
|
+
access: String(auth.access),
|
|
207
|
+
refresh: String(auth.refresh),
|
|
208
|
+
expiresAt: Number(auth.expires ?? 0),
|
|
209
|
+
localLogout: false,
|
|
210
|
+
lastError: "",
|
|
211
|
+
generation: this.generation,
|
|
212
|
+
}
|
|
213
|
+
this.persist()
|
|
214
|
+
return this.internalAuth()
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
isDue(leadMs = 5 * 60_000) {
|
|
218
|
+
return !!this.state.expiresAt && this.state.expiresAt - leadMs <= this.now()
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async ensureFresh({ force = false, signal } = {}) {
|
|
222
|
+
this.reload()
|
|
223
|
+
if (this.state.status !== "authenticated") {
|
|
224
|
+
throw Object.assign(new Error("Sign in to ArkFlow in Magpie"), { signIn: "expired" })
|
|
225
|
+
}
|
|
226
|
+
if (!force && !this.isDue()) return this.state.access
|
|
227
|
+
const refresh = this.state.refresh
|
|
228
|
+
const owner = this.ownership()
|
|
229
|
+
const key = createHash("sha256").update(refresh).digest("hex")
|
|
230
|
+
if (this.refreshing.has(key)) return this.refreshing.get(key)
|
|
231
|
+
const promise = this.api.refresh(refresh).then((tokens) => {
|
|
232
|
+
this.assertOwnership(owner)
|
|
233
|
+
if (!tokens?.access_token || !tokens?.refresh_token) throw new Error("ArkFlow refresh returned an incomplete token pair")
|
|
234
|
+
this.state.access = tokens.access_token
|
|
235
|
+
this.state.refresh = tokens.refresh_token
|
|
236
|
+
this.state.expiresAt = tokens.refresh_token_rotation === "none" && tokens.expires_in === null ? 0 : this.now() + Number(tokens.expires_in ?? 7200) * 1000
|
|
237
|
+
this.state.status = "authenticated"
|
|
238
|
+
this.state.lastError = ""
|
|
239
|
+
this.persist()
|
|
240
|
+
this.emit("refresh")
|
|
241
|
+
return this.state.access
|
|
242
|
+
}).catch((error) => {
|
|
243
|
+
this.assertOwnership(owner)
|
|
244
|
+
if (error.status === 401 || error.status === 403 || OAUTH_REQUIRED.has(error.code)) {
|
|
245
|
+
this.state.status = "expired"
|
|
246
|
+
this.state.access = ""
|
|
247
|
+
this.state.refresh = ""
|
|
248
|
+
this.state.lastError = error.message
|
|
249
|
+
this.persist()
|
|
250
|
+
this.emit("expired")
|
|
251
|
+
throw Object.assign(new Error("ArkFlow sign-in expired; sign in again"), { signIn: "expired", cause: error })
|
|
252
|
+
}
|
|
253
|
+
throw error
|
|
254
|
+
}).finally(() => {
|
|
255
|
+
this.refreshing.delete(key)
|
|
256
|
+
})
|
|
257
|
+
this.refreshing.set(key, promise)
|
|
258
|
+
return promise
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async withAccess(fn, { signal } = {}) {
|
|
262
|
+
let access = await this.ensureFresh({ signal })
|
|
263
|
+
let owner = this.ownership()
|
|
264
|
+
try {
|
|
265
|
+
const result = await fn(access)
|
|
266
|
+
this.assertOwnership(owner)
|
|
267
|
+
return result
|
|
268
|
+
} catch (error) {
|
|
269
|
+
this.assertOwnership(owner)
|
|
270
|
+
if (error.status !== 401) throw error
|
|
271
|
+
access = await this.ensureFresh({ force: true, signal })
|
|
272
|
+
owner = this.ownership()
|
|
273
|
+
const result = await fn(access)
|
|
274
|
+
this.assertOwnership(owner)
|
|
275
|
+
return result
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async updateBootstrap(bootstrap, { owner } = {}) {
|
|
280
|
+
this.reload()
|
|
281
|
+
if (owner !== undefined) this.assertOwnership(owner)
|
|
282
|
+
if (!bootstrap || bootstrap.schema_version !== 1) return
|
|
283
|
+
const accountId = String(bootstrap.user_id ?? this.state.userId ?? "")
|
|
284
|
+
const switched = accountId && this.state.accountId && accountId !== this.state.accountId
|
|
285
|
+
if (switched) {
|
|
286
|
+
this.state.loginRevision = randomId()
|
|
287
|
+
this.state.setupStage = "sync"
|
|
288
|
+
this.state.setupPid = process.pid
|
|
289
|
+
this.generation++
|
|
290
|
+
}
|
|
291
|
+
this.state.accountId = accountId
|
|
292
|
+
this.state.userId = accountId
|
|
293
|
+
this.state.bootstrap = bootstrap
|
|
294
|
+
this.state.displayName = String(bootstrap.display_name ?? this.state.displayName ?? "")
|
|
295
|
+
this.state.accountMode = bootstrap.account_mode === "enterprise" ? "enterprise" : "personal"
|
|
296
|
+
this.state.role = String(bootstrap.role ?? "")
|
|
297
|
+
this.persist()
|
|
298
|
+
if (switched) this.emit("account-switch")
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async logout() {
|
|
302
|
+
this.reload()
|
|
303
|
+
const owner = this.ownership()
|
|
304
|
+
if (this.state.access?.startsWith("nfds_")) {
|
|
305
|
+
try { await this.api.revoke(this.state.access) } catch (error) { if (error.status !== 401) throw error }
|
|
306
|
+
this.assertOwnership(owner)
|
|
307
|
+
}
|
|
308
|
+
const loggedOutCredential = stableId(this.state.access, this.state.refresh)
|
|
309
|
+
this.generation++
|
|
310
|
+
this.state = {
|
|
311
|
+
...this.state,
|
|
312
|
+
status: "signed_out",
|
|
313
|
+
access: "",
|
|
314
|
+
refresh: "",
|
|
315
|
+
expiresAt: 0,
|
|
316
|
+
localLogout: true,
|
|
317
|
+
loggedOutCredential,
|
|
318
|
+
logoutSynced: true,
|
|
319
|
+
lastError: "",
|
|
320
|
+
generation: this.generation,
|
|
321
|
+
}
|
|
322
|
+
this.persist()
|
|
323
|
+
this.emit("logout")
|
|
324
|
+
// The connection key belongs to the platform account, not this installation.
|
|
325
|
+
// Signing out locally must not revoke it for this or other devices.
|
|
326
|
+
return { ok: true, synced: true }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
revoke(reason = "ArkFlow access was revoked") {
|
|
330
|
+
this.reload()
|
|
331
|
+
this.generation++
|
|
332
|
+
this.state = {
|
|
333
|
+
...this.state,
|
|
334
|
+
status: "expired",
|
|
335
|
+
access: "",
|
|
336
|
+
refresh: "",
|
|
337
|
+
expiresAt: 0,
|
|
338
|
+
lastError: reason,
|
|
339
|
+
generation: this.generation,
|
|
340
|
+
}
|
|
341
|
+
this.persist()
|
|
342
|
+
this.emit("revoked")
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
clearCredentials() {
|
|
346
|
+
this.reload()
|
|
347
|
+
this.generation++
|
|
348
|
+
this.state = {
|
|
349
|
+
...this.state,
|
|
350
|
+
status: "signed_out",
|
|
351
|
+
accountId: "",
|
|
352
|
+
userId: "",
|
|
353
|
+
displayName: "",
|
|
354
|
+
accountMode: null,
|
|
355
|
+
role: null,
|
|
356
|
+
access: "",
|
|
357
|
+
refresh: "",
|
|
358
|
+
expiresAt: 0,
|
|
359
|
+
bootstrap: null,
|
|
360
|
+
lastError: "",
|
|
361
|
+
generation: this.generation,
|
|
362
|
+
}
|
|
363
|
+
this.persist()
|
|
364
|
+
this.emit("credentials-cleared")
|
|
365
|
+
}
|
|
366
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Read only display metadata, never execute or interpret skill instructions.
|
|
2
|
+
// Magpie displays SKILL.md front matter with whitespace collapsed.
|
|
3
|
+
export function skillDescription(content) {
|
|
4
|
+
const text = Buffer.from(content ?? "").toString("utf8").replace(/\r\n/g, "\n")
|
|
5
|
+
if (!text.startsWith("---\n")) return ""
|
|
6
|
+
const end = text.indexOf("\n---", 4)
|
|
7
|
+
if (end < 0) return ""
|
|
8
|
+
const lines = text.slice(4, end).split("\n")
|
|
9
|
+
for (let index = 0; index < lines.length; index++) {
|
|
10
|
+
const match = /^(?:description|"description"|'description'):\s*(.*)$/.exec(lines[index])
|
|
11
|
+
if (!match) continue
|
|
12
|
+
let value = match[1].trim()
|
|
13
|
+
const following = []
|
|
14
|
+
for (let next = index + 1; next < lines.length && (/^\s/.test(lines[next]) || !lines[next].trim()); next++) following.push(lines[next].trim())
|
|
15
|
+
if (/^[>|][+-]?[1-9]?(?:\s+#.*)?$/.test(value)) value = following.join(" ")
|
|
16
|
+
else {
|
|
17
|
+
value = [value, ...following].join(" ").trim()
|
|
18
|
+
if (value.startsWith('"')) {
|
|
19
|
+
// Double quoted YAML accepts JSON's common escaped scalar forms.
|
|
20
|
+
const quoted = /^("(?:[^"\\]|\\.)*")(?:\s+#.*)?$/.exec(value)
|
|
21
|
+
if (!quoted) return ""
|
|
22
|
+
try { value = JSON.parse(quoted[1]) } catch { return "" }
|
|
23
|
+
} else if (value.startsWith("'")) {
|
|
24
|
+
const quoted = /^'((?:[^']|'')*)'(?:\s+#.*)?$/.exec(value)
|
|
25
|
+
if (!quoted) return ""
|
|
26
|
+
value = quoted[1].replace(/''/g, "'")
|
|
27
|
+
} else value = value.replace(/\s+#.*$/, "")
|
|
28
|
+
}
|
|
29
|
+
return value.replace(/\s+/g, " ").trim()
|
|
30
|
+
}
|
|
31
|
+
return ""
|
|
32
|
+
}
|