universal-plugin-hub 1.0.25 → 1.0.35

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/src/runtime.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Apply saved hub changes to the running DSH profile.
3
+ *
4
+ * Writing cordis.patch.yml is persistence, not activation. The host owns the
5
+ * loader lifecycle, so new plugin/MCP entries go through its HMR service rather
6
+ * than a second connection layer or a process restart.
7
+ *
8
+ * Two constraints shape this module:
9
+ *
10
+ * 1. The application runs *after* the HTTP response. The hub loads from a
11
+ * linked directory, so a reconciliation may stop and restart the hub fiber;
12
+ * awaiting that inside a request the hub is serving would leave the response
13
+ * waiting on its own plugin being torn down.
14
+ * 2. A restart rebuilds the applicator, and with it the status. So the status
15
+ * is seeded from a token the client was already given: after a restart the
16
+ * new instance answers `applied` for that token instead of `idle`, and the
17
+ * poll converges instead of spinning out its window.
18
+ *
19
+ * Every outcome carries the token it belongs to, so a poll for change A can
20
+ * never read the result of change B.
21
+ */
22
+ export function createProfileApplicator(ctx) {
23
+ let queue = Promise.resolve()
24
+ let seq = 0
25
+ // Tokens that survived this process. A restarted fiber starts empty, so the
26
+ // first token it mints continues from the highest one the host handed out.
27
+ let last = Object.freeze({ application: 'idle', token: 0 })
28
+ let queued = null
29
+
30
+ // A reconciliation the host never settles would pin the status at `pending`
31
+ // and retain every closure queued behind it. Bound it: a timeout is reported
32
+ // as a failure the client can act on, and the queue moves on.
33
+ const RECONCILE_TIMEOUT_MS = 60_000
34
+
35
+ function applyProfile(requiredIds = []) {
36
+ const token = ++seq
37
+ last = Object.freeze({ application: 'pending', token })
38
+ // A change arriving while the queued reconciliation has not started yet is
39
+ // folded into it: one reconcile covers both, instead of restarting the hub
40
+ // once per rapid save. Its required ids join the same set.
41
+ if (queued && !queued.started) {
42
+ queued.token = token
43
+ queued.ids.push(...requiredIds)
44
+ // `done` must resolve with *this* change's token, not the token the run
45
+ // started with: report the caller's own identity.
46
+ const done = queued.run.then((outcome) => ({ ...outcome, token }))
47
+ done.then((outcome) => {
48
+ if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
49
+ }, () => {})
50
+ return { token, done }
51
+ }
52
+ const pending = { started: false, token, ids: [...requiredIds], run: null }
53
+ queued = pending
54
+ const run = pending.run = queue.then(async () => {
55
+ pending.started = true
56
+ const ids = [...new Set(pending.ids)]
57
+ try {
58
+ // Resolve inside the try: a throwing service lookup must become a
59
+ // reported failure, not a rejection that strands the status.
60
+ const hmr = ctx?.root?.get?.('hmr') || ctx?.get?.('hmr')
61
+ if (!hmr || typeof hmr.reconcileProfile !== 'function') {
62
+ return { application: 'restart-required', restartReason: 'no-hmr', token: pending.token }
63
+ }
64
+ const reconcile = () => hmr.reconcileProfile(ids)
65
+ let timer
66
+ const timeout = new Promise((_, reject) => {
67
+ timer = setTimeout(() => reject(new Error(`reconcileProfile did not settle within ${RECONCILE_TIMEOUT_MS}ms`)), RECONCILE_TIMEOUT_MS)
68
+ timer.unref?.()
69
+ })
70
+ const result = await Promise.race([
71
+ typeof hmr.runExclusive === 'function' ? hmr.runExclusive(reconcile) : reconcile(),
72
+ timeout,
73
+ ]).finally(() => clearTimeout(timer))
74
+ // `reconcileProfile` reports a restart need either profile-wide or per
75
+ // pending module; either one means the change is not live yet.
76
+ const restartReason = result?.restartReason
77
+ || (Array.isArray(result?.pending) && result.pending.length ? result.pending[0]?.reason : undefined)
78
+ return {
79
+ application: restartReason ? 'restart-required' : 'applied',
80
+ token: pending.token,
81
+ ...(restartReason ? { restartReason } : {}),
82
+ }
83
+ } catch (error) {
84
+ // The saved change is still valid. Report that it is not live instead
85
+ // of turning a successful install into a misleading "install failed".
86
+ return {
87
+ application: 'failed',
88
+ token: pending.token,
89
+ applicationError: error instanceof Error ? error.message : String(error),
90
+ }
91
+ }
92
+ })
93
+ // One failed application must not poison later, independent changes.
94
+ queue = run.then(() => {}, () => {})
95
+ run.then((outcome) => {
96
+ // Only the newest change owns the status; an older, slower one must not
97
+ // overwrite a newer result a poll is already waiting on.
98
+ if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
99
+ }, () => {})
100
+ return { token, done: run }
101
+ }
102
+
103
+ // A poll for a token this instance has not issued means the change was
104
+ // applied by a previous fiber that the reconciliation restarted — which is
105
+ // the success path for a linked plugin, not a superseded change.
106
+ applyProfile.status = (token) => {
107
+ if (typeof token === 'number' && token > seq) {
108
+ return Object.freeze({ application: 'applied', token: APPLIED_TOKEN })
109
+ }
110
+ return last
111
+ }
112
+ return applyProfile
113
+ }
114
+
115
+ /** Status served to a poll whose token predates this (restarted) instance. */
116
+ export const APPLIED_TOKEN = -1
117
+
118
+ /**
119
+ * Persist first, apply in the background. The response reports `scheduled`
120
+ * plus the token the client polls with; the outcome arrives through
121
+ * `status()`.
122
+ */
123
+ export function scheduledResult(result, applyProfile, requiredIds = []) {
124
+ if (typeof applyProfile !== 'function') return result
125
+ // Never await: a reconciliation can stop this very plugin. A fault while
126
+ // enqueueing must not turn a persisted change into an error response.
127
+ let token
128
+ try {
129
+ token = applyProfile(requiredIds).token
130
+ } catch (error) {
131
+ return { ...result, application: 'failed', applicationError: error instanceof Error ? error.message : String(error) }
132
+ }
133
+ return { ...result, application: 'scheduled', applicationToken: token }
134
+ }
package/src/skills.js CHANGED
@@ -31,17 +31,49 @@ function policyValue(value, fallback) {
31
31
  if (['false', 'no', 'off', '0'].includes(normalized)) return false
32
32
  throw new Error('调用策略必须是布尔值')
33
33
  }
34
+ function parseYamlObject(source) {
35
+ try {
36
+ const value = parseYaml(source)
37
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined
38
+ } catch { return undefined }
39
+ }
40
+ // Some SKILL.md files carry the metadata block twice: a template header that
41
+ // was never removed sits above the real one. Only the first block was read and
42
+ // cut, so the copy rendered as a `--- name: … ---` table at the top of the
43
+ // detail page — and the card took the template's name. The body starts after
44
+ // the last leading block instead; a `---` rule further down is page content.
45
+ function splitFrontmatter(raw) {
46
+ // Both ends of a block pin the same line terminator: with `\r?` on only one
47
+ // side, an LF file matches a range running from line 1's `---` to line 2's
48
+ // closing one plus its leading `\r`, and the leftover `\n` throws the next
49
+ // round off by a line — the second copy then never matched.
50
+ const block = /^---[ \t]*(\r?\n)([\s\S]*?)\1---[ \t]*\1/
51
+ // The blank line a copy sits under is skipped with it, so the check below
52
+ // lands on the next block instead of stopping at the gap.
53
+ const gap = /^(?:[ \t]*\r?\n)*/
54
+ let yaml = '', end = 0
55
+ while (end < raw.length) {
56
+ const skip = raw.slice(end).match(gap)[0].length
57
+ const next = raw.slice(end + skip).match(block)
58
+ // Only consecutive metadata counts. A block further down sits under page
59
+ // content, where it is a horizontal rule and a table, not a header.
60
+ if (!next || parseYamlObject(next[2]) === undefined) break
61
+ yaml = next[2]
62
+ end += skip + next[0].length
63
+ }
64
+ return yaml ? { yaml, body: raw.slice(end) } : null
65
+ }
34
66
  function readSkill(file, root, isNested) {
35
67
  let raw = '', meta = {}, content = '', error = ''
36
68
  let invocation = { modelInvocable: true, userInvocable: true }
37
69
  try {
38
70
  if (statSync(file).size > MAX_FILE) throw new Error('SKILL.md 文件过大')
39
71
  raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
40
- const match = raw.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/)
41
- if (!match) throw new Error('缺少完整的 YAML 元数据')
42
- meta = parseYaml(match[1]) || {}
72
+ const parsed = splitFrontmatter(raw)
73
+ if (!parsed) throw new Error('缺少完整的 YAML 元数据')
74
+ meta = parseYaml(parsed.yaml) || {}
43
75
  if (typeof meta !== 'object' || Array.isArray(meta)) throw new Error('YAML 元数据必须是对象')
44
- content = raw.slice(match[0].length)
76
+ content = parsed.body
45
77
  if (typeof meta.name !== 'string' || !NAME.test(meta.name)) throw new Error('名称不符合 DSH 的小写连字符格式')
46
78
  if (typeof meta.description !== 'string' || !meta.description.trim()) throw new Error('缺少 description')
47
79
  invocation = { modelInvocable: !policyValue(meta['disable-model-invocation'], false), userInvocable: policyValue(meta['user-invocable'], true) }