@capyclaw/ppt-suite 2.5.70 → 2.5.72

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.
Files changed (109) hide show
  1. package/composition.lock.json +27 -27
  2. package/contract/ppt-contract.json +1 -1
  3. package/dsh-suite.json +27 -17
  4. package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
  5. package/node_modules/@capyclaw/asset-service/package.json +1 -1
  6. package/node_modules/@capyclaw/asset-service/src/index.mjs +4 -3
  7. package/node_modules/@capyclaw/document-workbench/package.json +6 -3
  8. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +56 -3
  9. package/node_modules/@capyclaw/document-workbench/src/client/visibility.mjs +112 -0
  10. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +6 -4
  11. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +7 -2
  12. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +8 -0
  13. package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +17 -10
  14. package/node_modules/@capyclaw/document-workbench/src/store/projection.mjs +39 -0
  15. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +14 -11
  16. package/node_modules/@capyclaw/editor-host/dsh-suite.json +1 -1
  17. package/node_modules/@capyclaw/editor-host/package.json +1 -1
  18. package/node_modules/@capyclaw/editor-host/src/index.mjs +12 -21
  19. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  20. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  21. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  22. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  24. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  25. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  26. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  27. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  28. package/node_modules/@capyclaw/foundation/package.json +1 -1
  29. package/node_modules/@capyclaw/plugin-kit/package.json +4 -1
  30. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  31. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  32. package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
  33. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  34. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  35. package/node_modules/@capyclaw/portal/package.json +1 -1
  36. package/node_modules/@capyclaw/ppt-editor/app.js +458 -10
  37. package/node_modules/@capyclaw/ppt-editor/contract/ppt-contract.json +1 -1
  38. package/node_modules/@capyclaw/ppt-editor/heartbeat-worker.js +5 -2
  39. package/node_modules/@capyclaw/ppt-editor/index.html +4 -0
  40. package/node_modules/@capyclaw/ppt-editor/package.json +2 -2
  41. package/node_modules/@capyclaw/ppt-skill-api/contract/ppt-contract.json +1 -1
  42. package/node_modules/@capyclaw/ppt-skill-api/package.json +1 -1
  43. package/node_modules/@capyclaw/ppt-skill-api/skills/pptist-api/references/tool-contract.md +1 -1
  44. package/node_modules/@capyclaw/ppt-skill-proposal/contract/ppt-contract.json +1 -1
  45. package/node_modules/@capyclaw/ppt-skill-proposal/package.json +1 -1
  46. package/node_modules/@capyclaw/ppt-workbench/contract/ppt-contract.json +1 -1
  47. package/node_modules/@capyclaw/ppt-workbench/core/deck-layout.js +3 -1
  48. package/node_modules/@capyclaw/ppt-workbench/core/ops/slide.js +9 -3
  49. package/node_modules/@capyclaw/ppt-workbench/core/text.js +14 -2
  50. package/node_modules/@capyclaw/ppt-workbench/package.json +10 -8
  51. package/node_modules/@capyclaw/ppt-workbench/plugin.mjs +13 -1
  52. package/node_modules/@capyclaw/ppt-workbench/server/contract.mjs +1 -1
  53. package/node_modules/@capyclaw/ppt-workbench/server/embedded-host.mjs +200 -29
  54. package/node_modules/@capyclaw/ppt-workbench/server/relay.mjs +10 -7
  55. package/node_modules/@capyclaw/ppt-workbench/server/shared/SHARED_MANIFEST.json +4 -4
  56. package/node_modules/@capyclaw/ppt-workbench/server/store/backends/file-backend.mjs +3 -0
  57. package/node_modules/@capyclaw/ppt-workbench/server/store/checkpoints.mjs +4 -1
  58. package/node_modules/@capyclaw/ppt-workbench/server/store/index.mjs +4 -0
  59. package/node_modules/@capyclaw/ppt-workbench/server/store/sessions.mjs +139 -4
  60. package/node_modules/@capyclaw/ppt-workbench/server/store/shape.mjs +37 -0
  61. package/node_modules/@capyclaw/service-broker/README.md +1 -1
  62. package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
  63. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +13 -5
  64. package/node_modules/@capyclaw/service-broker/package.json +1 -1
  65. package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
  66. package/node_modules/@capyclaw/service-host/package.json +2 -2
  67. package/node_modules/@capyclaw/service-host/src/index.mjs +45 -27
  68. package/node_modules/@capyclaw/skills-service/README.md +42 -10
  69. package/node_modules/@capyclaw/skills-service/package.json +6 -3
  70. package/node_modules/@capyclaw/skills-service/server.mjs +129 -51
  71. package/node_modules/@capyclaw/suite-kit/README.md +289 -0
  72. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  73. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  74. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  75. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  76. package/node_modules/@capyclaw/suite-kit/package.json +58 -0
  77. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  78. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  79. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  80. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  81. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  82. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  83. package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
  84. package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
  85. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  86. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  87. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  88. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  89. package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
  90. package/node_modules/@capyclaw/tool-host/dsh-suite.json +1 -1
  91. package/node_modules/@capyclaw/tool-host/lib/host.mjs +15 -4
  92. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  93. package/node_modules/@capyclaw/tool-host/src/index.mjs +19 -5
  94. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +71 -3
  95. package/node_modules/@capyclaw/work-store/README.md +83 -0
  96. package/node_modules/@capyclaw/work-store/STANDARD.md +263 -0
  97. package/node_modules/@capyclaw/work-store/cordis.patch.yml +3 -0
  98. package/node_modules/@capyclaw/work-store/dsh-suite.json +33 -0
  99. package/node_modules/@capyclaw/work-store/icon.svg +7 -0
  100. package/node_modules/@capyclaw/work-store/lib/host.mjs +21 -0
  101. package/node_modules/@capyclaw/work-store/package.json +68 -0
  102. package/node_modules/@capyclaw/work-store/src/backend.mjs +90 -0
  103. package/node_modules/@capyclaw/work-store/src/db.mjs +199 -0
  104. package/node_modules/@capyclaw/work-store/src/envelope.mjs +132 -0
  105. package/node_modules/@capyclaw/work-store/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/work-store/src/interop.mjs +70 -0
  107. package/node_modules/@capyclaw/work-store/src/refs.mjs +99 -0
  108. package/node_modules/@capyclaw/work-store/src/routes.mjs +135 -0
  109. package/package.json +16 -14
@@ -0,0 +1,100 @@
1
+ /**
2
+ * 编排闸 / 授权 Mandate / 统一事件(docs/suite-interop-standard.md §C)。
3
+ *
4
+ * 编排器是「平级作品」:它只是一个声明了调度类能力的套件,结构上与 ppt/browser 平等,
5
+ * 可替换(自研或 dsh-superagent 参考实现)、可嵌套、可被嵌入。套件不认识编排器。
6
+ * 本模块是给任意编排器复用的纯函数原语,不 import 任何套件。
7
+ *
8
+ * 参考吸收:deepseek-ai/dsh-superagent-prototype 的 Ticket + 不可变 Mandate 授权、
9
+ * 「只在人必须行动时说话」、外部看门狗。这里是其契约层的最小实现。
10
+ */
11
+ import { randomBytes } from 'node:crypto'
12
+
13
+ export const EVENT_KINDS = Object.freeze(['progress', 'artifact', 'confirm', 'login', 'result', 'error'])
14
+
15
+ const id = (prefix) => `${prefix}_${randomBytes(10).toString('hex')}`
16
+
17
+ /**
18
+ * 闸评估:能力执行前的唯一入口。
19
+ * ctx: { authenticated?, mandate?, now?, sessionId?, stepId?, artifactIds?, preview? }
20
+ * 返回 {decision:'proceed'|'confirm'|'login', ...}:
21
+ * - auth 必需且未确认登录 → login(会话内暂停该步,登录后续跑,不崩链)
22
+ * - confirm/risk:high 且无有效 Mandate → confirm(强制停下等用户,不可悄悄发布)
23
+ * - 其余 → proceed
24
+ */
25
+ export function evaluateGate(descriptor, ctx = {}) {
26
+ const now = ctx.now ?? Date.now()
27
+ if (!descriptor || typeof descriptor !== 'object') {
28
+ return { decision: 'error', reason: '缺少能力描述符' }
29
+ }
30
+ if (descriptor.auth && ctx.authenticated !== true) {
31
+ return { decision: 'login', auth: descriptor.auth, capability: descriptor.name, reason: `需要登录态 ${descriptor.auth}(未确认登录,暂停该步)` }
32
+ }
33
+ const needsConfirm = descriptor.confirm === true || descriptor.risk === 'high'
34
+ if (needsConfirm) {
35
+ if (ctx.mandate && mandateCovers(ctx.mandate, descriptor, { now, sessionId: ctx.sessionId, artifactIds: ctx.artifactIds })) {
36
+ return { decision: 'proceed', mandateId: ctx.mandate.mandateId, capability: descriptor.name }
37
+ }
38
+ return {
39
+ decision: 'confirm',
40
+ capability: descriptor.name,
41
+ gate: Object.freeze({
42
+ gateId: id('gate'), kind: 'confirm', capability: descriptor.name,
43
+ risk: descriptor.risk ?? 'low', sessionId: ctx.sessionId ?? null, stepId: ctx.stepId ?? null,
44
+ preview: ctx.preview ?? null, createdAt: now,
45
+ }),
46
+ reason: '不可逆/高风险动作:执行前强制用户确认',
47
+ }
48
+ }
49
+ return { decision: 'proceed', capability: descriptor.name }
50
+ }
51
+
52
+ /**
53
+ * 不可变授权(用户在确认闸上「接受」后签发)。一旦签发不可修改;
54
+ * 过期/换会话/换产物即失效。scope.artifactIds 非空时把授权钉死在具体产物上。
55
+ */
56
+ export function createMandate({ capability, grantedBy, sessionId, scope = {}, ttlMs = null, now = Date.now() } = {}) {
57
+ if (typeof capability !== 'string' || !capability) throw new Error('createMandate: capability 必填')
58
+ if (typeof grantedBy !== 'string' || !grantedBy) throw new Error('createMandate: grantedBy 必填(谁授的权)')
59
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('createMandate: sessionId 必填(授权不跨会话)')
60
+ if (ttlMs != null && (!Number.isFinite(ttlMs) || ttlMs <= 0)) throw new Error('createMandate: ttlMs 必须为正数或 null')
61
+ return Object.freeze({
62
+ mandateId: id('mdt'),
63
+ capability,
64
+ grantedBy,
65
+ sessionId,
66
+ scope: Object.freeze({ ...scope }),
67
+ grantedAt: now,
68
+ expiresAt: ttlMs == null ? null : now + ttlMs,
69
+ })
70
+ }
71
+
72
+ /** Mandate 是否覆盖本次调用:能力对得上 + 同会话 + 未过期 + 产物在授权范围内。 */
73
+ export function mandateCovers(mandate, descriptor, { now = Date.now(), sessionId = null, artifactIds = [] } = {}) {
74
+ if (!mandate || !descriptor) return false
75
+ if (mandate.capability !== descriptor.name && mandate.capability !== descriptor.capability) return false
76
+ if (mandate.sessionId && sessionId && mandate.sessionId !== sessionId) return false
77
+ if (mandate.expiresAt != null && now >= mandate.expiresAt) return false
78
+ const scoped = mandate.scope?.artifactIds
79
+ if (Array.isArray(scoped) && scoped.length > 0) {
80
+ if (!Array.isArray(artifactIds) || artifactIds.length === 0) return false
81
+ if (!artifactIds.every((a) => scoped.includes(a))) return false
82
+ }
83
+ return true
84
+ }
85
+
86
+ /** 统一事件流(§C.5):接口步骤与浏览器步骤同构,都发这种事件到会话视图。 */
87
+ export function createEvent({ kind, sessionId = null, stepId = null, capability = null, payload = null, now = Date.now() } = {}) {
88
+ if (!EVENT_KINDS.includes(kind)) throw new Error(`createEvent: kind 必须是 ${EVENT_KINDS.join('|')},收到: ${kind}`)
89
+ return Object.freeze({ eventId: id('evt'), kind, sessionId, stepId, capability, payload, at: now })
90
+ }
91
+
92
+ /** 步骤模型(§C.2):能力调用 + 输入/输出引用 + 状态。两种操控模式同构。 */
93
+ export function createStep({ capability, controlMode, inputs = [], outputs = [], sessionId = null, status = 'pending' } = {}) {
94
+ if (typeof capability !== 'string' || !capability) throw new Error('createStep: capability 必填')
95
+ return Object.freeze({
96
+ stepId: id('step'), capability, controlMode: controlMode ?? null,
97
+ inputs: Object.freeze([...inputs]), outputs: Object.freeze([...outputs]),
98
+ sessionId, status,
99
+ })
100
+ }
@@ -0,0 +1,584 @@
1
+ /**
2
+ * 安装 / doctor:把 suite 装进 DSH profile,并验证组合是否真的工作。
3
+ */
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import { spawnSync } from 'node:child_process'
8
+ import { composeSuites, renderCordisPatch } from './compose.mjs'
9
+ import { loadSuiteManifest, validateSuiteManifest } from './manifest.mjs'
10
+ import { resolvePackageSpec } from './artifacts.mjs'
11
+ import { writeActivationRegistry } from './activation-registry.mjs'
12
+
13
+ export function defaultDshHome() {
14
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
15
+ }
16
+
17
+ export function profileDirOf(dshHome, profile) {
18
+ return path.join(path.resolve(dshHome), 'profiles', profile)
19
+ }
20
+
21
+ function readJson(file) {
22
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
23
+ }
24
+
25
+ function writeJson(file, value) {
26
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n')
27
+ }
28
+
29
+ function backup(file) {
30
+ if (!fs.existsSync(file)) return
31
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
32
+ fs.copyFileSync(file, `${file}.bak-${stamp}`)
33
+ }
34
+
35
+ function readJsonSafe(file) {
36
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
37
+ }
38
+
39
+ function packageVersionOf(dir, entry) {
40
+ const target = entry?.path ? path.resolve(dir, entry.path) : null
41
+ const manifest = target ? readJsonSafe(path.join(target, 'package.json')) : null
42
+ return {
43
+ version: manifest?.version || entry?.version || '',
44
+ apiVersion: manifest?.dsh?.apiVersion || null,
45
+ dir: target,
46
+ }
47
+ }
48
+
49
+ function buildCompositionLock({ profile, dir, suites, composed }) {
50
+ const packages = {}
51
+ for (const pkg of composed.packages) {
52
+ const info = packageVersionOf(pkg.dir, pkg.entry)
53
+ packages[pkg.name] = {
54
+ version: info.version,
55
+ range: pkg.entry?.version || '',
56
+ role: pkg.entry?.role || '',
57
+ apiVersion: info.apiVersion,
58
+ suite: pkg.suite || '',
59
+ }
60
+ }
61
+ return {
62
+ version: 1,
63
+ profile,
64
+ suites: suites.map(({ manifest }) => ({ name: manifest.name, version: manifest.version })),
65
+ packages: Object.fromEntries(Object.entries(packages).sort(([a], [b]) => a.localeCompare(b))),
66
+ }
67
+ }
68
+
69
+ function majorOf(version) {
70
+ const match = /^(\d+)/.exec(String(version || ''))
71
+ return match ? match[1] : ''
72
+ }
73
+
74
+ function diffCompositionLocks(previous, next) {
75
+ if (!previous) return []
76
+ const changes = []
77
+ const names = new Set([...Object.keys(previous.packages || {}), ...Object.keys(next.packages || {})])
78
+ for (const name of [...names].sort()) {
79
+ const before = previous.packages?.[name]
80
+ const after = next.packages?.[name]
81
+ if (!before) changes.push({ type: 'added', name, version: after.version })
82
+ else if (!after) changes.push({ type: 'removed', name, version: before.version })
83
+ else if (before.version !== after.version || before.range !== after.range || before.role !== after.role) {
84
+ changes.push({ type: 'updated', name, from: before.version, to: after.version })
85
+ }
86
+ if (before && after && before.apiVersion && after.apiVersion && majorOf(before.apiVersion) !== majorOf(after.apiVersion)) {
87
+ changes.push({ type: 'api-major', name, from: before.apiVersion, to: after.apiVersion })
88
+ }
89
+ }
90
+ const suiteNames = new Set([
91
+ ...(previous.suites || []).map((suite) => suite.name),
92
+ ...(next.suites || []).map((suite) => suite.name),
93
+ ])
94
+ for (const name of [...suiteNames].sort()) {
95
+ const before = (previous.suites || []).find((suite) => suite.name === name)
96
+ const after = (next.suites || []).find((suite) => suite.name === name)
97
+ if (!before) changes.push({ type: 'suite-added', name, version: after.version })
98
+ else if (!after) changes.push({ type: 'suite-removed', name, version: before.version })
99
+ else if (before.version !== after.version) changes.push({ type: 'suite-updated', name, from: before.version, to: after.version })
100
+ }
101
+ return changes
102
+ }
103
+
104
+ function validateSuiteLock(suite, composed) {
105
+ const file = path.join(suite.dir, 'composition.lock.json')
106
+ const lock = readJsonSafe(file)
107
+ if (!lock) return { file, ok: true, warnings: [] }
108
+ const warnings = []
109
+ if (lock.suite !== suite.manifest.name) {
110
+ warnings.push(`${suite.manifest.name}: composition.lock 的 suite=${lock.suite} 与 manifest 不一致`)
111
+ }
112
+ if (String(lock.suiteVersion) !== String(suite.manifest.version)) {
113
+ warnings.push(`${suite.manifest.name}: composition.lock 版本 ${lock.suiteVersion} 与 manifest ${suite.manifest.version} 不一致`)
114
+ }
115
+ const byName = new Map((composed?.packages || []).map((pkg) => [pkg.name, pkg]))
116
+ for (const [name, locked] of Object.entries(lock.packages || {})) {
117
+ const pkg = byName.get(name)
118
+ if (!pkg) { warnings.push(`${suite.manifest.name}: composition.lock 引用了不存在的包 ${name}`); continue }
119
+ const actual = packageVersionOf(pkg.dir, pkg.entry)
120
+ if (locked.version && actual.version && locked.version !== actual.version) {
121
+ warnings.push(`${suite.manifest.name}: ${name} lock 版本 ${locked.version} ≠ 实际 ${actual.version}`)
122
+ }
123
+ if (locked.apiVersion && actual.apiVersion && majorOf(locked.apiVersion) !== majorOf(actual.apiVersion)) {
124
+ warnings.push(`${suite.manifest.name}: ${name} lock API major ${locked.apiVersion} ≠ 实际 ${actual.apiVersion}`)
125
+ }
126
+ }
127
+ return { file, ok: warnings.length === 0, lock, warnings }
128
+ }
129
+
130
+ function samePath(left, right) {
131
+ try { return fs.realpathSync(left).toLowerCase() === fs.realpathSync(right).toLowerCase() } catch { return false }
132
+ }
133
+
134
+ function linkDir(target, dest) {
135
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
136
+ try {
137
+ const stat = fs.lstatSync(dest)
138
+ if (stat.isSymbolicLink()) {
139
+ if (samePath(dest, target)) return false
140
+ fs.rmSync(dest, { recursive: true, force: true })
141
+ } else if (stat.isDirectory()) {
142
+ let name = ''
143
+ try { name = readJson(path.join(dest, 'package.json')).name } catch { /* 非包目录 */ }
144
+ if (name !== path.basename(dest)) {
145
+ throw new Error(`${dest} 是真实目录且不是同名包,拒绝覆盖`)
146
+ }
147
+ fs.rmSync(dest, { recursive: true, force: true })
148
+ }
149
+ } catch (error) {
150
+ if (error.code !== 'ENOENT') throw error
151
+ }
152
+ fs.symlinkSync(target, dest, 'junction')
153
+ return true
154
+ }
155
+
156
+ /** 从 insert 块中按 entry 删除指定 row,保留同块内其它 row。 */
157
+ function filterInsertBlock(block, wanted) {
158
+ const header = block[0]
159
+ const entries = []
160
+ let current = []
161
+ for (const line of block.slice(1)) {
162
+ if (/^\s+- id:\s*/.test(line)) {
163
+ if (current.length) entries.push(current)
164
+ current = [line]
165
+ } else {
166
+ current.push(line)
167
+ }
168
+ }
169
+ if (current.length) entries.push(current)
170
+ if (!entries.length) return block
171
+ const kept = entries.filter((entry) => {
172
+ const hit = /^\s+- id:\s*([^\s#]+)\s*$/.exec(entry[0])
173
+ return !hit || !wanted.has(hit[1])
174
+ })
175
+ if (!kept.length) return []
176
+ return [header, ...kept.flat()]
177
+ }
178
+
179
+ /** 从 profile patch 里移除指定 row 的顶层块(用于旧版单装迁移)。 */
180
+ export function stripPatchRows(text, ids) {
181
+ const wanted = new Set(ids || [])
182
+ if (!wanted.size) return text
183
+ const lines = text.split(/\r?\n/)
184
+ const out = []
185
+ for (let i = 0; i < lines.length; i++) {
186
+ const line = lines[i]
187
+ if (/^- insert:\s*$/.test(line)) {
188
+ let j = i + 1
189
+ const block = [line]
190
+ while (j < lines.length) {
191
+ const next = lines[j]
192
+ if (next.trim() !== '' && !/^\s/.test(next)) break
193
+ block.push(next)
194
+ j++
195
+ }
196
+ out.push(...filterInsertBlock(block, wanted))
197
+ i = j - 1
198
+ continue
199
+ }
200
+ const hit = /^- id:\s*([^\s#]+)\s*$/.exec(line)
201
+ if (hit && wanted.has(hit[1])) {
202
+ let j = i + 1
203
+ while (j < lines.length && (lines[j].trim() === '' || /^\s/.test(lines[j]))) j++
204
+ i = j - 1
205
+ continue
206
+ }
207
+ out.push(line)
208
+ }
209
+ return out.join('\n').replace(/\n{3,}/g, '\n\n')
210
+ }
211
+
212
+ function runPnpm(profileDir) {
213
+ const result = process.platform === 'win32'
214
+ ? spawnSync(process.env.ComSpec || 'cmd.exe',
215
+ ['/d', '/s', '/c', 'pnpm install --ignore-scripts --reporter=silent'],
216
+ { cwd: profileDir, stdio: 'inherit' })
217
+ : spawnSync('pnpm', ['install', '--ignore-scripts', '--reporter=silent'],
218
+ { cwd: profileDir, stdio: 'inherit' })
219
+ return result.status === 0
220
+ }
221
+
222
+ /**
223
+ * @param {{
224
+ * suiteInputs: string[],
225
+ * profile?: string,
226
+ * dshHome?: string,
227
+ * dryRun?: boolean,
228
+ * runPnpm?: boolean,
229
+ * removeDependencies?: string[],
230
+ * packageSpecs?: string[],
231
+ * rollbackTo?: string,
232
+ * artifactRoot?: string
233
+ * }} options
234
+ */
235
+ export function installSuites(options) {
236
+ const profile = options.profile || process.env.DSH_PROFILE || 'web'
237
+ const dshHome = options.dshHome || defaultDshHome()
238
+ const dir = profileDirOf(dshHome, profile)
239
+ const manifestPath = path.join(dir, 'package.json')
240
+ const patchPath = path.join(dir, 'cordis.patch.yml')
241
+ if (!fs.existsSync(manifestPath)) throw new Error(`找不到 profile: ${dir}`)
242
+
243
+ const suites = options.suiteInputs.map((input) => loadSuiteManifest(input))
244
+ const composed = composeSuites(suites)
245
+ if (!composed.ok) throw new Error('suite 组合冲突:\n- ' + composed.errors.join('\n- '))
246
+
247
+ const overrides = []
248
+ const applyOverride = (spec) => {
249
+ const meta = resolvePackageSpec(spec, { root: options.artifactRoot })
250
+ const pkg = composed.packages.find((item) => item.name === meta.name)
251
+ if (!pkg) throw new Error(`artifact 覆盖失败: suite 组合里没有包 ${meta.name}`)
252
+ pkg.entry = { ...pkg.entry, path: meta.dir, version: meta.version }
253
+ pkg.artifact = meta
254
+ overrides.push({ name: meta.name, version: meta.version, dir: meta.dir })
255
+ return meta
256
+ }
257
+ if (options.rollbackTo) {
258
+ const target = path.resolve(options.rollbackTo)
259
+ const targetLock = readJsonSafe(target)
260
+ if (!targetLock?.packages) throw new Error(`rollback 锁文件不可读或缺少 packages: ${target}`)
261
+ for (const [name, meta] of Object.entries(targetLock.packages)) {
262
+ if (!meta?.version) continue
263
+ try { applyOverride(`${name}@${meta.version}`) }
264
+ catch (error) { throw new Error(`rollback ${name}@${meta.version} 失败: ${error.message}`) }
265
+ }
266
+ }
267
+ for (const spec of options.packageSpecs || []) applyOverride(spec)
268
+
269
+ const compositionLockPath = path.join(dir, 'dsh-composition.lock.json')
270
+ const previousLock = readJsonSafe(compositionLockPath)
271
+ const compositionLock = buildCompositionLock({ profile, dir, suites, composed })
272
+ const lockChanges = diffCompositionLocks(previousLock, compositionLock)
273
+ const suiteLockResults = suites.map((suite) => validateSuiteLock(suite, composed))
274
+ const lockWarnings = []
275
+ for (const change of lockChanges) {
276
+ if (change.type === 'api-major') {
277
+ lockWarnings.push(`公共插件 ${change.name} API major ${change.from} → ${change.to};请确认消费者已升级`)
278
+ }
279
+ }
280
+ for (const result of suiteLockResults) lockWarnings.push(...result.warnings)
281
+
282
+ const legacy = new Set(options.removeDependencies || [])
283
+ const manifest = readJson(manifestPath)
284
+ manifest.dependencies ||= {}
285
+ manifest.dsh ||= {}
286
+ manifest.dsh.profile ||= {}
287
+ const previous = manifest.dshSuiteKit?.managedPackages || []
288
+ for (const name of previous) delete manifest.dependencies[name]
289
+ for (const name of manifest.dshSuiteKit?.suites || []) {
290
+ delete manifest.dependencies[name]
291
+ }
292
+ for (const name of legacy) delete manifest.dependencies[name]
293
+
294
+ for (const suite of suites) {
295
+ manifest.dependencies[suite.manifest.name] = `link:${suite.dir.replace(/\\/g, '/')}`
296
+ }
297
+
298
+ const managedPackages = composed.packages
299
+ .filter(({ entry }) => entry.path)
300
+ .map(({ name }) => name)
301
+ const suiteNames = suites.map(({ manifest: m }) => m.name)
302
+ const bundles = (manifest.dsh.profile.bundles || [])
303
+ .filter((name) => !previous.includes(name))
304
+ .filter((name) => !(manifest.dshSuiteKit?.suites || []).includes(name))
305
+ .filter((name) => !legacy.has(name))
306
+ for (const name of suiteNames) if (!bundles.includes(name)) bundles.push(name)
307
+ manifest.dsh.profile.bundles = bundles
308
+ manifest.dshSuiteKit = {
309
+ version: 1,
310
+ suites: suiteNames,
311
+ managedPackages,
312
+ updatedAt: new Date().toISOString(),
313
+ }
314
+
315
+ const plan = {
316
+ profile,
317
+ dir,
318
+ suites: suiteNames,
319
+ bundles,
320
+ dependencies: Object.keys(manifest.dependencies),
321
+ managedPackages,
322
+ warnings: [...composed.warnings, ...lockWarnings],
323
+ dryRun: !!options.dryRun,
324
+ lock: compositionLock,
325
+ lockPath: compositionLockPath,
326
+ lockChanges,
327
+ suiteLocks: suiteLockResults.map((result) => ({ file: result.file, ok: result.ok })),
328
+ overrides,
329
+ rollbackTo: options.rollbackTo ? path.resolve(options.rollbackTo) : null,
330
+ }
331
+ if (options.dryRun) return plan
332
+
333
+ backup(manifestPath)
334
+ backup(patchPath)
335
+ backup(compositionLockPath)
336
+ writeJson(manifestPath, manifest)
337
+ writeJson(compositionLockPath, compositionLock)
338
+ const writtenLock = readJsonSafe(compositionLockPath)
339
+ if (!writtenLock || JSON.stringify(writtenLock) !== JSON.stringify(compositionLock)) {
340
+ throw new Error(`组合锁写入校验失败: ${compositionLockPath}`)
341
+ }
342
+
343
+ /* 运行期激活面:suite 组合结果编译成 launch-engine 注册表,随 profile 落盘。 */
344
+ const activationRegistry = writeActivationRegistry(dir, { suites, composed })
345
+ plan.activationRegistry = { file: activationRegistry.file, capabilities: activationRegistry.capabilities }
346
+ for (const warning of activationRegistry.warnings) plan.warnings.push(`activation-registry: ${warning}`)
347
+ if (options.removeRows?.length && fs.existsSync(patchPath)) {
348
+ const before = fs.readFileSync(patchPath, 'utf8')
349
+ const after = stripPatchRows(before, options.removeRows)
350
+ if (after !== before) fs.writeFileSync(patchPath, after)
351
+ }
352
+
353
+ if (options.runPnpm !== false) {
354
+ if (!runPnpm(dir)) plan.warnings.push('pnpm install 未成功;junction 仍会建立,但 lockfile 可能不是最新')
355
+ }
356
+
357
+ const linked = []
358
+ for (const suite of suites) {
359
+ linkDir(suite.dir, path.join(dir, 'node_modules', suite.manifest.name))
360
+ linked.push(suite.manifest.name)
361
+ }
362
+ for (const packageInfo of composed.packages) {
363
+ const target = packageInfo.entry.path
364
+ ? path.resolve(packageInfo.dir, packageInfo.entry.path)
365
+ : null
366
+ if (!target) continue
367
+ linkDir(target, path.join(dir, 'node_modules', packageInfo.name))
368
+ linked.push(packageInfo.name)
369
+ }
370
+ plan.linked = linked
371
+ return plan
372
+ }
373
+
374
+ async function fetchJson(url, init, timeoutMs) {
375
+ const controller = new AbortController()
376
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
377
+ try {
378
+ const response = await fetch(url, { ...init, signal: controller.signal })
379
+ const text = await response.text()
380
+ let body = null
381
+ try { body = JSON.parse(text) } catch { /* 非 JSON */ }
382
+ return { status: response.status, body, text }
383
+ } finally {
384
+ clearTimeout(timer)
385
+ }
386
+ }
387
+
388
+ function pidAlive(pid) {
389
+ if (!Number.isInteger(pid) || pid <= 0) return false
390
+ try { process.kill(pid, 0); return true } catch { return false }
391
+ }
392
+
393
+ /** 把静态 check.url 的 origin 换成注册表里的真实 origin(端口是动态分配的)。 */
394
+ function rebaseUrl(original, base) {
395
+ try {
396
+ const url = new URL(original)
397
+ const real = new URL(base)
398
+ url.protocol = real.protocol
399
+ url.host = real.host
400
+ return url.toString()
401
+ } catch { return base }
402
+ }
403
+
404
+ /**
405
+ * 检查项指向的是"服务"而不是"固定端口"。
406
+ *
407
+ * 端口是动态分配的,写死任何固定端口只会制造两种假象:服务明明活着却报 connection
408
+ * refused;或者端口刚好被别的进程占用,报个假"健康"。这里按服务 id 查注册表,
409
+ * 并顺带核对进程是否真的还在 —— 这才是"插件启用了就必须能用"的判据。
410
+ */
411
+ function resolveServiceUrl(check, dshHome) {
412
+ const id = check.service
413
+ if (!id) return { url: check.url }
414
+ let rows = null
415
+ try {
416
+ rows = JSON.parse(fs.readFileSync(path.join(dshHome, 'services.json'), 'utf8'))?.services || {}
417
+ } catch {
418
+ return { error: `读不到 ${path.join(dshHome, 'services.json')},无法确认 ${id} 是否在运行` }
419
+ }
420
+ const row = rows[id]
421
+ if (!row) return { error: `注册表里没有 ${id}:服务没有被拉起(先启动 DSH 或让它自愈)` }
422
+ if (row.state !== 'running') return { error: `${id} 状态是 ${row.state},不是 running` }
423
+ if (!pidAlive(row.pid)) return { error: `${id} 登记为 running(pid ${row.pid})但进程已不存在:注册表是活的、服务是死的` }
424
+ if (!row.url) return { error: `${id} 的注册表行缺少 url` }
425
+ return { url: rebaseUrl(check.url, row.url) }
426
+ }
427
+
428
+ async function runCheck(check, dshHome, timeoutMs) {
429
+ const target = resolveServiceUrl(check, dshHome)
430
+ if (target.error) return { id: check.id, ok: false, detail: target.error }
431
+ const resolved = { ...check, url: target.url }
432
+ return check.type === 'contract' ? checkContract(resolved, timeoutMs) : checkHttp(resolved, timeoutMs)
433
+ }
434
+
435
+ async function checkHttp(check, timeoutMs) {
436
+ try {
437
+ const response = await fetchJson(check.url, { method: check.method || 'GET' }, check.timeoutMs || timeoutMs)
438
+ const wantStatus = check.expectStatus ?? 200
439
+ if (response.status !== wantStatus) {
440
+ return { id: check.id, ok: false, detail: `HTTP ${response.status},期望 ${wantStatus}` }
441
+ }
442
+ if (check.expectBody) {
443
+ for (const [key, value] of Object.entries(check.expectBody)) {
444
+ if (JSON.stringify(response.body?.[key]) !== JSON.stringify(value)) {
445
+ return { id: check.id, ok: false, detail: `body.${key}=${JSON.stringify(response.body?.[key])},期望 ${JSON.stringify(value)}` }
446
+ }
447
+ }
448
+ }
449
+ return { id: check.id, ok: true, detail: `HTTP ${response.status}` }
450
+ } catch (error) {
451
+ return { id: check.id, ok: false, detail: String(error.message || error) }
452
+ }
453
+ }
454
+
455
+ async function checkContract(check, timeoutMs) {
456
+ const timeout = check.timeoutMs || timeoutMs
457
+ try {
458
+ const init = await fetchJson(check.url, {
459
+ method: 'POST',
460
+ headers: { 'content-type': 'application/json' },
461
+ body: JSON.stringify({
462
+ jsonrpc: '2.0', id: 1, method: 'initialize',
463
+ params: { protocolVersion: '2025-03-26', capabilities: {} },
464
+ }),
465
+ }, timeout)
466
+ if (init.status !== 200) return { id: check.id, ok: false, detail: `initialize HTTP ${init.status}` }
467
+ const call = await fetchJson(check.url, {
468
+ method: 'POST',
469
+ headers: { 'content-type': 'application/json' },
470
+ body: JSON.stringify({
471
+ jsonrpc: '2.0', id: 2, method: 'tools/call',
472
+ params: { name: check.tool, arguments: {} },
473
+ }),
474
+ }, timeout)
475
+ if (call.status !== 200) return { id: check.id, ok: false, detail: `C/tools/call HTTP ${call.status}` }
476
+ const text = call.body?.result?.content?.[0]?.text
477
+ if (call.body?.result?.isError) return { id: check.id, ok: false, detail: String(text || '工具返回 isError') }
478
+ const payload = JSON.parse(text)
479
+ const major = Number(String(payload.contractVersion || '').split('.')[0])
480
+ if (major !== check.major) {
481
+ return { id: check.id, ok: false, detail: `contractVersion=${payload.contractVersion},期望 major ${check.major}` }
482
+ }
483
+ return { id: check.id, ok: true, detail: `contractVersion=${payload.contractVersion}` }
484
+ } catch (error) {
485
+ return { id: check.id, ok: false, detail: String(error.message || error) }
486
+ }
487
+ }
488
+
489
+ /**
490
+ * @param {{profile?: string, dshHome?: string, dshBin?: string, timeoutMs?: number}} [options]
491
+ */
492
+ export async function doctor(options = {}) {
493
+ const profile = options.profile || process.env.DSH_PROFILE || 'web'
494
+ const dshHome = options.dshHome || defaultDshHome()
495
+ const dir = profileDirOf(dshHome, profile)
496
+ const manifestPath = path.join(dir, 'package.json')
497
+ const errors = []
498
+ const warnings = []
499
+ const checks = []
500
+
501
+ if (!fs.existsSync(manifestPath)) {
502
+ return { ok: false, errors: [`找不到 profile: ${dir}`], warnings, checks }
503
+ }
504
+ const manifest = readJson(manifestPath)
505
+ /* 只对"源码组合"形态(dsh-* 的 suite bundle)做 compose 校验。
506
+ * 已安装的 drop-store 套件各自内嵌一份基建包,跨套件 compose 必然报路径/版本冲突,
507
+ * 那不是说套件坏了。已安装环境的体检走 `npm run check:install`(对比 drop 实载版本与构建产物)。 */
508
+ const suiteNames = manifest.dshSuiteKit?.suites
509
+ || (manifest.dsh?.profile?.bundles || []).filter((name) => name.startsWith('dsh-') && name.includes('suite'))
510
+ if (!suiteNames.length) warnings.push('profile 没有 dshSuiteKit.suites,按 bundle 名称猜测 suite')
511
+
512
+ const suites = []
513
+ for (const name of suiteNames) {
514
+ const packageDir = path.join(dir, 'node_modules', name)
515
+ if (!fs.existsSync(packageDir)) {
516
+ errors.push(`suite ${name} 未安装(缺少 node_modules/${name})`)
517
+ continue
518
+ }
519
+ try {
520
+ const loaded = loadSuiteManifest(packageDir)
521
+ const validation = validateSuiteManifest(loaded.manifest, { baseDir: loaded.dir })
522
+ if (!validation.ok) errors.push(...validation.errors.map((e) => `${name}: ${e}`))
523
+ const generated = composeSuites([loaded])
524
+ if (generated.ok) {
525
+ const expected = renderCordisPatch(generated.rows)
526
+ const patchFile = path.join(packageDir, 'cordis.patch.yml')
527
+ if (!fs.existsSync(patchFile) || fs.readFileSync(patchFile, 'utf8') !== expected) {
528
+ errors.push(`${name}: cordis.patch.yml 与 dsh-suite.json 生成结果不一致,请重跑 compose`)
529
+ }
530
+ }
531
+ suites.push(loaded)
532
+ } catch (error) {
533
+ errors.push(`${name}: ${error.message}`)
534
+ }
535
+ }
536
+
537
+ if (suites.length) {
538
+ const composed = composeSuites(suites)
539
+ errors.push(...composed.errors)
540
+ warnings.push(...composed.warnings)
541
+ for (const pkg of composed.packages) {
542
+ if (!pkg.entry.path) continue
543
+ const target = path.resolve(pkg.dir, pkg.entry.path)
544
+ if (!fs.existsSync(path.join(target, 'package.json'))) {
545
+ errors.push(`包 ${pkg.name} 不存在或不是包: ${target}`)
546
+ }
547
+ }
548
+ for (const check of composed.checks) {
549
+ checks.push(await runCheck(check, dshHome, options.timeoutMs || 3000))
550
+ }
551
+ }
552
+
553
+ if (options.dshBin) {
554
+ const bin = path.resolve(options.dshBin)
555
+ const result = spawnSync(bin, ['--profile', profile, '--dump-config'], {
556
+ cwd: dshHome,
557
+ env: { ...process.env, DSH_HOME: dshHome },
558
+ encoding: 'utf8',
559
+ timeout: 30000,
560
+ shell: process.platform === 'win32',
561
+ })
562
+ if (result.status !== 0) {
563
+ warnings.push(`dsh --dump-config 失败: ${(result.stderr || result.stdout || '').slice(0, 300)}`)
564
+ } else {
565
+ const ids = [...result.stdout.matchAll(/^- id: (.+)$/gm)].map((m) => m[1].trim())
566
+ const counts = new Map()
567
+ for (const id of ids) counts.set(id, (counts.get(id) || 0) + 1)
568
+ for (const [id, count] of counts) {
569
+ if (count > 1) errors.push(`组合后 row.id 重复: ${id} × ${count}`)
570
+ }
571
+ }
572
+ }
573
+
574
+ return { ok: errors.length === 0 && checks.every((c) => c.ok), errors, warnings, checks }
575
+ }
576
+
577
+ export function formatReport(report) {
578
+ const lines = []
579
+ for (const check of report.checks || []) lines.push(`${check.ok ? '✓' : '✗'} ${check.id}: ${check.detail}`)
580
+ for (const warning of report.warnings || []) lines.push(`! ${warning}`)
581
+ for (const error of report.errors || []) lines.push(`✗ ${error}`)
582
+ lines.push(report.ok ? '✓ suite doctor 通过' : '✗ suite doctor 未通过')
583
+ return lines.join('\n')
584
+ }