@capyclaw/publisher 0.0.0-stage → 0.1.0

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/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @capyclaw/publisher — npm 发布器
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把 capyclaw 插件工程的 npm 发布流水线搬进 dsh:插件工程仓库只负责**生产**(构建 → `dist/` 打包件),
4
+ 发布动作由本插件在 dsh 内以 MCP 工具执行。发布逻辑逐条移植自仓库原 `scripts/publish-to-npm.mjs`
5
+ (闸门、依赖顺序、同版本漂移、发布后 shasum 复核),行为保持对齐。
6
+
7
+ ## 工具
8
+
9
+ | 工具 | kind | 说明 |
10
+ |---|---|---|
11
+ | `publisher_whoami` | read | npm 凭据预检(宿主 `npm whoami` / `NODE_AUTH_TOKEN`) |
12
+ | `publisher_preview` | read | 全量 dry-run:发现集 → 发布闸/pack 闸 → 已发布与漂移 → 顺序闸,逐包结果 + 汇总 |
13
+ | `publisher_execute` | control | 真发布(不可撤销)。**必须显式 `confirm: true`**;支持 `only` / `tag` / `skipTests` |
14
+ | `publisher_capabilities` | read | 契约探针(contractVersion 1.x) |
15
+
16
+ ## 使用
17
+
18
+ 1. 安装:`dsh plugin add @capyclaw/publisher`(本包需在 npm 上;首次引导见仓库 docs/PUBLISHING.md)
19
+ 2. 在 dsh 里对 AI 说「预演发布」→ `publisher_whoami` + `publisher_preview({ root })`
20
+ 3. 核对批次后「执行发布」→ `publisher_execute({ root, confirm: true })`
21
+
22
+ ## 配置
23
+
24
+ | 项 | 工具参数 / 环境变量 | 默认 |
25
+ |---|---|---|
26
+ | 工作区路径 | `root` 参数 / `DSH_PUBLISHER_ROOT` | 无(必填其一) |
27
+ | 支撑库清单 | `DSH_PUBLISHER_LIBS`(JSON 数组,相对 root) | 内置 4 项(plugin-kit / document-workbench / host-shell / skills-service) |
28
+ | 服务端口 | cordis config `port` / `DSH_PUBLISHER_PORT` | 39700 |
29
+
30
+ 发布凭据沿用宿主环境(dsh 运行用户的 npm 登录态),本插件不经手 token。
31
+
32
+ ## 行为要点(与原流水线对齐)
33
+
34
+ - 发现集 = 支撑库(显式清单)+ `discoverPlugins()`(过发布闸的插件),先库后插件。
35
+ - 同版本漂移闸:本地 `npm pack` sha1 ≠ registry `dist.shasum` 时拒绝(npm 禁止同版本重发)。
36
+ - 顺序闸:待发包的 `@capyclaw/*` 依赖闭包必须 registry 可解析或同批发布,否则拦截。
37
+ - 发布后复核:registry 收到的 tarball 与本地 pack 逐字节比对。
38
+ - 额外 pack 闸:`npm pack --dry-run` 断言 package.json / main / patch 文件必在包内。
@@ -0,0 +1,24 @@
1
+ # @capyclaw/publisher bundle patch
2
+ # npm 发布执行器:把 capyclaw 插件工程的发布流水线搬进 dsh。
3
+ #
4
+ # 配置项(cordis config → 环境变量 DSH_PUBLISHER_* → 默认值):
5
+ # port 服务端口 DSH_PUBLISHER_PORT 39700(固定端口;mcp 接线要求 URL 已知)
6
+ # hostDir 锁/状态目录 DSH_PUBLISHER_HOME 缺省随 service-host 约定
7
+ # strictPort 端口占用即失败 DSH_PUBLISHER_STRICT false(默认复用已健康实例)
8
+ #
9
+ # 工作区路径(要发布的仓库 checkout)优先级:工具参数 root → DSH_PUBLISHER_ROOT。
10
+ # 发布凭据沿用宿主环境:npm whoami 已登录或 NODE_AUTH_TOKEN。
11
+
12
+ - insert:
13
+ - id: publisher-host
14
+ name: "@capyclaw/publisher"
15
+ config:
16
+ port: 39700
17
+ - id: mcp-capyclaw-publisher
18
+ name: '@deepseek-ai/dsh-mcp-client'
19
+ config:
20
+ serverName: capyclaw-publisher
21
+ transport: streamable-http
22
+ url: 'http://127.0.0.1:39700/mcp'
23
+ failOnStartupError: false
24
+ toolCallTimeoutMs: 600000
package/lib/host.mjs ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @capyclaw/publisher 宿主插件(Cordis 入口)。
3
+ *
4
+ * 服务宿主、工具面全部来自公共插件;本文件只负责生命周期装配。
5
+ * 发布动作发生在独立服务进程里(spawnSync npm),不阻塞 Cordis 事件循环。
6
+ */
7
+ import path from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { startService } from '../server/relay.mjs'
10
+
11
+ export const name = '@capyclaw/publisher'
12
+
13
+ export async function apply(ctx, config = {}) {
14
+ const packageDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
15
+ const service = await startService({
16
+ packageDir,
17
+ port: Number(config.port) || 39700,
18
+ hostDir: config.hostDir || process.env.DSH_PUBLISHER_HOME,
19
+ strictPort: config.strictPort,
20
+ lockFile: config.lockFile,
21
+ })
22
+ console.log(`[@capyclaw/publisher] ${service.reused ? '复用' : '启动'}服务: ${service.url}`)
23
+ return async () => {
24
+ await service.stop()
25
+ console.log('[@capyclaw/publisher] 服务已停止')
26
+ }
27
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@capyclaw/publisher",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "npm 发布执行器:在 dsh 内以 MCP 工具完成 capyclaw 插件工程的发布预演与真发布(闸门、顺序、漂移、发布后复核),插件工程仓库本身不再持有发布脚本",
5
+ "type": "module",
6
+ "main": "./lib/host.mjs",
7
+ "exports": {
8
+ ".": "./lib/host.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "dsh": {
12
+ "bundle": {
13
+ "patch": "./cordis.patch.yml"
14
+ },
15
+ "category": "tool",
16
+ "platform": "both"
17
+ },
18
+ "meta": {
19
+ "title": "npm 发布器",
20
+ "description": "在 dsh 内发布 capyclaw 插件工程的可发布集:publisher_preview 全量预演(发现集/发布闸/同版本漂移/依赖顺序),publisher_execute 真发布(需显式 confirm)。发布逻辑与原仓库脚本逐条对齐。"
21
+ },
22
+ "files": [
23
+ "lib/",
24
+ "server/",
25
+ "cordis.patch.yml",
26
+ "README.md"
27
+ ],
28
+ "scripts": {
29
+ "test": "node --test \"test/*.test.mjs\""
30
+ },
31
+ "dependencies": {
32
+ "@capyclaw/plugin-kit": "^0.2.0",
33
+ "@capyclaw/plugin-validator": "^1.0.0",
34
+ "@capyclaw/service-host": "^0.1.0",
35
+ "@capyclaw/tool-host": "^0.1.0"
36
+ },
37
+ "engines": {
38
+ "node": ">=18",
39
+ "dsh": "^0.2.0-rc.2"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "license": "MIT",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/Maple496/capyclaw.git",
48
+ "directory": "extensions/official/capyclaw-publisher"
49
+ },
50
+ "keywords": [
51
+ "dsh",
52
+ "dsh-plugin",
53
+ "npm-publish",
54
+ "release"
55
+ ],
56
+ "bugs": {
57
+ "url": "https://github.com/Maple496/capyclaw/issues"
58
+ },
59
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/extensions/official/capyclaw-publisher#readme"
60
+ }
@@ -0,0 +1,463 @@
1
+ /**
2
+ * @capyclaw/publisher 业务实现:发布引擎。
3
+ *
4
+ * 逐条移植自插件工程仓库的 scripts/publish-to-npm.mjs(发布主流程/闸门/顺序/漂移/复核)
5
+ * 与 tools/capyclaw-plugin-release 的 publishGateErrors + discoverPlugins(发现集判定),
6
+ * 行为保持对齐:仓库侧脚本删除后,这里是唯一实现。
7
+ *
8
+ * 与原脚本的差异(有意为之):
9
+ * - root(要发布的仓库 checkout)是调用参数,不再是模块常量;
10
+ * - npm view / npm pack 的缓存挂在每次调用的 context 上(服务进程长驻,避免跨调用串味);
11
+ * - 新增轻量 pack 闸(npm pack --dry-run 断言 package.json/main/patch 必在包内),
12
+ * 顶替原 scripts/verify-publishable.mjs 的核心保护。
13
+ */
14
+
15
+ import { spawnSync } from 'node:child_process'
16
+ import crypto from 'node:crypto'
17
+ import fs from 'node:fs'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
20
+
21
+ import { validatePlugin } from '@capyclaw/plugin-validator'
22
+
23
+ /** 支撑库目录(相对仓库根):纯库/独立服务,无 dsh.bundle,插件发现集不收,显式清单维护。
24
+ * 可用 DSH_PUBLISHER_LIBS(JSON 数组,相对 root 的路径)覆盖。 */
25
+ export const DEFAULT_SUPPORT_LIBS = [
26
+ 'packages/capyclaw-plugin-kit',
27
+ 'packages/capyclaw-document-workbench',
28
+ 'packages/capyclaw-host-shell',
29
+ 'extensions/bridges/ppt-bridge/capyclaw-skills-service',
30
+ ]
31
+
32
+ /** 与原脚本一致的失败状态集(其余视为通过或跳过)。 */
33
+ export const FAILURE_STATUSES = [
34
+ 'missing-dir', 'gate-failed', 'invalid', 'pack-incomplete',
35
+ 'test-failed', 'publish-failed', 'publish-corrupted', 'version-drift', 'order-blocked',
36
+ ]
37
+
38
+ /* ────────────────────────── 发现集与闸门(移植) ────────────────────────── */
39
+
40
+ /** 发布闸:验证器不管、但分发必需的项。返回错误串数组。
41
+ * (移植自 tools/capyclaw-plugin-release/lib/index.mjs publishGateErrors) */
42
+ export function publishGateErrors(pkg, srcDir) {
43
+ const errors = []
44
+ if (pkg.private === true) {
45
+ errors.push('package.json 标记了 private: true——不能发布到 npm;确认它是否属于对外分发件')
46
+ }
47
+ if (!pkg.publishConfig?.access) {
48
+ errors.push('缺少 publishConfig.access(作用域包默认 restricted,需显式 public)')
49
+ }
50
+ const enginesDsh = pkg.engines?.dsh
51
+ if (typeof enginesDsh !== 'string' || !enginesDsh.trim()) {
52
+ errors.push('缺少 engines.dsh(消费方无法判断兼容的 dsh 运行时版本)')
53
+ }
54
+ const patch = pkg.dsh?.bundle?.patch
55
+ const patches = Array.isArray(patch) ? patch : patch ? [patch] : []
56
+ if (!patches.length) errors.push('缺少 dsh.bundle.patch(dsh 不会把这个包当作 profile 层加载)')
57
+ for (const rel of patches) {
58
+ if (!fs.existsSync(path.join(srcDir, rel))) errors.push(`dsh.bundle.patch 指向的文件不存在: ${rel}`)
59
+ }
60
+ for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
61
+ const deps = pkg[field]
62
+ if (!deps || typeof deps !== 'object') continue
63
+ for (const [name, range] of Object.entries(deps)) {
64
+ if (/^(link|file):/.test(String(range))) {
65
+ errors.push(`${field}.${name} 是源码树本地路径(${range})——分发件必须走版本范围`)
66
+ }
67
+ }
68
+ }
69
+ return errors
70
+ }
71
+
72
+ /** 库发布闸:插件闸管不了的分发必需项。返回错误串数组。(移植自 publish-to-npm.mjs) */
73
+ export function libraryGateErrors(pkg) {
74
+ const errors = []
75
+ if (pkg.private === true) errors.push('package.json 标记了 private: true')
76
+ if (pkg.name.startsWith('@') && !pkg.publishConfig?.access) {
77
+ errors.push('缺少 publishConfig.access(作用域包默认 restricted,需显式 public)')
78
+ }
79
+ if (!pkg.license) errors.push('缺少 license 声明')
80
+ if (!pkg.version) errors.push('缺少 version')
81
+ for (const field of ['dependencies', 'optionalDependencies', 'peerDependencies']) {
82
+ const deps = pkg[field]
83
+ if (!deps || typeof deps !== 'object') continue
84
+ for (const [name, range] of Object.entries(deps)) {
85
+ if (/^(link|file):/.test(String(range))) {
86
+ errors.push(`${field}.${name} 是源码树本地路径(${range})——分发件必须走版本范围`)
87
+ }
88
+ }
89
+ }
90
+ return errors
91
+ }
92
+
93
+ /** 插件扫码根目录 + 包名形态。(移植自 plugin-release;发布闸用不到 suite 校验器注入) */
94
+ const PLUGIN_BASES = ['packages', 'extensions/official', 'extensions/bridges', 'extensions/bridges/*/plugin']
95
+ const PUBLISHABLE_NAME = /^((@[\w.-]+\/)?dsh-[\w.-]+|@capyclaw\/[\w.-]+)$/
96
+
97
+ /** 找出 root 下所有**可发布**的插件目录(过得了发布闸的才算)。未就绪的落 lastSkipped。 */
98
+ export function discoverPlugins({ root, includeNotReady = false } = {}) {
99
+ const out = []
100
+ const skipped = []
101
+ const seen = new Set()
102
+ const visit = (dir) => {
103
+ const pkgPath = path.join(dir, 'package.json')
104
+ if (fs.existsSync(pkgPath)) {
105
+ try {
106
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
107
+ const publishable = PUBLISHABLE_NAME.test(pkg.name || '')
108
+ && (pkg.dsh?.bundle || pkg.dsh?.client || pkg.dsh?.suite)
109
+ if (publishable && !seen.has(pkg.name)) {
110
+ seen.add(pkg.name)
111
+ const reasons = publishGateErrors(pkg, dir)
112
+ if (reasons.length) skipped.push({ dir, name: pkg.name, reasons })
113
+ else out.push(dir)
114
+ }
115
+ } catch { /* 坏 package.json 由验证器报,不在这里中断扫描 */ }
116
+ }
117
+ let entries = []
118
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
119
+ for (const entry of entries) {
120
+ if (!entry.isDirectory()) continue
121
+ if (['node_modules', '.git', 'dist', 'archive', 'test'].includes(entry.name)) continue
122
+ visit(path.join(dir, entry.name))
123
+ }
124
+ }
125
+ for (const base of PLUGIN_BASES) {
126
+ const dir = path.join(root, base)
127
+ if (fs.existsSync(dir)) visit(dir)
128
+ }
129
+ out.sort()
130
+ discoverPlugins.lastSkipped = skipped.sort((a, b) => a.name.localeCompare(b.name))
131
+ return includeNotReady ? [...out, ...skipped.map((s) => s.dir)].sort() : out
132
+ }
133
+
134
+ export function pkgOf(dir) {
135
+ return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))
136
+ }
137
+
138
+ /* ────────────────────────── npm 调用(每次调用一个 context) ────────────────────────── */
139
+
140
+ /** npm 直调(node npm-cli.js,不走 shell):含空格的临时/用户目录不会被拆词。 */
141
+ const NPM_CLI = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
142
+ function rawNpmRun(args, options = {}) {
143
+ if (fs.existsSync(NPM_CLI)) {
144
+ return spawnSync(process.execPath, [NPM_CLI, ...args], { encoding: 'utf8', stdio: 'pipe', ...options })
145
+ }
146
+ return spawnSync('npm', args, { encoding: 'utf8', stdio: 'pipe', shell: process.platform === 'win32', ...options })
147
+ }
148
+
149
+ function createNpmContext() {
150
+ /** npm view 结果缓存:同一次运行里同一 specifier 只查一次。 */
151
+ const viewCache = new Map()
152
+ const npmView = (spec, field) => {
153
+ const key = `${spec}|${field}`
154
+ if (!viewCache.has(key)) viewCache.set(key, rawNpmRun(['view', spec, field]))
155
+ return viewCache.get(key)
156
+ }
157
+ const alreadyPublished = (name, version) => {
158
+ const r = npmView(`${name}@${version}`, 'version')
159
+ if (r.status !== 0) return false
160
+ return String(r.stdout).trim() === version
161
+ }
162
+ /** registry 上已发布 tarball 的 sha1(拿不到返回 null,网络闪断降级为警告)。 */
163
+ const npmShasumOf = (name, version) => {
164
+ const r = npmView(`${name}@${version}`, 'dist.shasum')
165
+ if (r.status !== 0) return null
166
+ return String(r.stdout).trim() || null
167
+ }
168
+ /** 本地 npm pack 产物的 sha1(npm pack 确定性:同内容同哈希)。结果按目录缓存。 */
169
+ const localShasumCache = new Map()
170
+ const localShasumOf = (dir) => {
171
+ if (localShasumCache.has(dir)) return localShasumCache.get(dir)
172
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-sha-'))
173
+ try {
174
+ const pack = rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
175
+ if (pack.status !== 0) return null
176
+ const tgz = path.join(tmp, String(pack.stdout).trim().split(/\r?\n/).pop())
177
+ const sha = crypto.createHash('sha1').update(fs.readFileSync(tgz)).digest('hex')
178
+ localShasumCache.set(dir, sha)
179
+ return sha
180
+ } finally {
181
+ fs.rmSync(tmp, { recursive: true, force: true })
182
+ }
183
+ }
184
+ return { rawNpmRun, npmView, alreadyPublished, npmShasumOf, localShasumOf }
185
+ }
186
+
187
+ /** 发布顺序闸:待发包的 @capyclaw 依赖闭包,每一项必须 registry 可解析或在同批发布。
188
+ * 拦截「只发 suite 不发依赖」这类顺序手滑(发布成功 ≠ 用户能装上)。 */
189
+ export function orderGate(pkg, localMap, batch, npm) {
190
+ const errors = []
191
+ const warnings = []
192
+ const seen = new Set([pkg.name])
193
+ const queue = [pkg]
194
+ while (queue.length) {
195
+ const cur = queue.shift()
196
+ const deps = { ...(cur.dependencies || {}), ...(cur.peerDependencies || {}), ...(cur.optionalDependencies || {}) }
197
+ for (const [name, range] of Object.entries(deps)) {
198
+ if (!name.startsWith('@capyclaw/') || seen.has(name)) continue
199
+ seen.add(name)
200
+ const local = localMap.get(name)
201
+ if (local) queue.push(local.pkg) /* 闭包继续沿本仓包展开 */
202
+ const resolvable = npm.npmView(`${name}@${range}`, 'version')
203
+ if (resolvable.status === 0) continue /* ① registry 已可解析 */
204
+ if (batch.has(name)) {
205
+ warnings.push(`${name}@${range} registry 暂不可解析,依赖同批发布(确认批次包含它)`)
206
+ } else {
207
+ errors.push(`${name}@${range} 在 registry 上不可解析,且不在本次发布批次——先发布 ${name}(或加入批次),否则用户安装本包会 404/ETARGET`)
208
+ }
209
+ }
210
+ }
211
+ return { errors, warnings }
212
+ }
213
+
214
+ /** 密钥/本机信息扫描模式:打包产物里出现任何一种都拒绝发布。
215
+ * (移植自原 scripts/verify-publishable.mjs 的 tarball 逐文件扫描。
216
+ * 认证令牌字段的模式用拼接构造,注释里也不写整串,
217
+ * 否则扫描器会把自己的源码当成泄漏(自噬假阳性)。) */
218
+ const AUTH_TOKEN_RE = new RegExp('_auth' + 'Token', 'i')
219
+ const SECRET_PATTERNS = [
220
+ [/sk-[A-Za-z0-9]{20,}/, 'API key 形态(sk-…)'],
221
+ [/npm_[A-Za-z0-9]{20,}/, 'npm token 形态(npm_…)'],
222
+ [AUTH_TOKEN_RE, 'npmrc 认证令牌字段'],
223
+ [/[A-Za-z]:\\Users\\/i, '本机绝对路径(盘符:\\Users\\)'],
224
+ [/\/(home|Users)\/[A-Za-z0-9._-]+\//, '本机绝对路径(/home/ / /Users/)'],
225
+ ]
226
+
227
+ /** 扫描目录内全部文本文件,返回命中的密钥/本机信息描述串。 */
228
+ export function scanDirForSecrets(root) {
229
+ const hits = []
230
+ const walk = (dir) => {
231
+ let entries = []
232
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
233
+ for (const entry of entries) {
234
+ const file = path.join(dir, entry.name)
235
+ if (entry.isDirectory()) { walk(file); continue }
236
+ let text = null
237
+ try { text = fs.readFileSync(file, 'utf8') } catch { continue } /* 二进制/不可读跳过 */
238
+ for (const [pattern, label] of SECRET_PATTERNS) {
239
+ if (pattern.test(text)) hits.push(`${path.relative(root, file)}: ${label}`)
240
+ }
241
+ }
242
+ }
243
+ walk(root)
244
+ return [...new Set(hits)]
245
+ }
246
+
247
+ /** 轻量 pack 闸:① npm pack --dry-run 断言分发必需文件真的会进包;
248
+ * ② 真实 pack + 解包 + 逐文件扫密钥/本机信息(凭据绝不上 npm)。
249
+ * (顶替原 verify-publishable 的核心断言;干净目录安装级检查不在这里重复。) */
250
+ export function packGateErrors(pkg, dir, npm) {
251
+ const mustHave = ['package.json']
252
+ if (pkg.main) mustHave.push(String(pkg.main).replace(/^\.\//, ''))
253
+ const patch = pkg.dsh?.bundle?.patch
254
+ for (const rel of Array.isArray(patch) ? patch : patch ? [patch] : []) {
255
+ mustHave.push(String(rel).replace(/^\.\//, ''))
256
+ }
257
+ if (pkg.dsh?.client) mustHave.push('client/client.js')
258
+ if (pkg.dsh?.suite) mustHave.push(String(pkg.dsh.suite).replace(/^\.\//, ''))
259
+ const r = npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
260
+ if (r.status !== 0) return [`npm pack --dry-run 失败: ${String(r.stderr || r.stdout || '').trim().slice(0, 200)}`]
261
+ let packed = []
262
+ try {
263
+ const parsed = JSON.parse(String(r.stdout))
264
+ packed = (Array.isArray(parsed) ? parsed[0]?.files : parsed?.files)?.map((f) => f.path) || []
265
+ } catch {
266
+ return ['npm pack --dry-run 输出不可解析']
267
+ }
268
+ const errors = mustHave.filter((f) => !packed.includes(f)).map((f) => `分发必需文件未进包: ${f}`)
269
+
270
+ /* 真实 pack + 解包 + 密钥扫描:发布产物里不该有任何凭据/本机信息。 */
271
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-scan-'))
272
+ try {
273
+ const pack = npm.rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
274
+ if (pack.status !== 0) return [...errors, 'npm pack 失败(无法做密钥扫描)']
275
+ const tgz = String(pack.stdout).trim().split(/\r?\n/).pop()
276
+ const extract = spawnSync('tar', ['-xzf', tgz, '-C', tmp], { cwd: tmp, encoding: 'utf8' })
277
+ if (extract.status !== 0) return [...errors, 'tarball 解包失败(无法做密钥扫描)']
278
+ const extracted = path.join(tmp, 'package')
279
+ if (fs.existsSync(extracted)) {
280
+ for (const hit of scanDirForSecrets(extracted)) errors.push(`密钥/本机信息进包: ${hit}`)
281
+ }
282
+ } finally {
283
+ fs.rmSync(tmp, { recursive: true, force: true })
284
+ }
285
+ return errors
286
+ }
287
+
288
+ /** 发布预检:npm 凭据状态(ambient:宿主已登录或 NODE_AUTH_TOKEN)。 */
289
+ export function npmWhoami() {
290
+ const r = rawNpmRun(['whoami'])
291
+ if (r.status !== 0) {
292
+ return { ok: false, hint: 'npm whoami 失败——在宿主机 npm login,或设置 NODE_AUTH_TOKEN' }
293
+ }
294
+ return { ok: true, user: String(r.stdout).trim() }
295
+ }
296
+
297
+ /* ────────────────────────── 主流程(移植) ────────────────────────── */
298
+
299
+ /** 单包发布流程(插件与库共用)。返回结果记录。 */
300
+ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dryRun, npm, log }) {
301
+ const pkg = pkgOf(dir)
302
+ const label = `${pkg.name}@${pkg.version}`
303
+ if (only && pkg.name !== only) return null
304
+
305
+ const gate = kind === 'lib' ? libraryGateErrors(pkg) : publishGateErrors(pkg, dir)
306
+ if (gate.length) {
307
+ log(`✗ ${label} — 发布闸未过`)
308
+ for (const item of gate) log(` - ${item}`)
309
+ return { label, status: 'gate-failed', detail: gate }
310
+ }
311
+
312
+ if (kind === 'plugin') {
313
+ const validation = await validatePlugin(dir)
314
+ if (!validation.valid) {
315
+ log(`✗ ${label} — 插件校验未过`)
316
+ for (const item of validation.errors) log(` - [${item.rule}] ${item.message}`)
317
+ return { label, status: 'invalid', detail: validation.errors.map((e) => e.message) }
318
+ }
319
+ }
320
+
321
+ if (npm.alreadyPublished(pkg.name, pkg.version)) {
322
+ /* 同版本漂移闸:npm pack 确定性 ⇒ 本地 sha1 == registry dist.shasum 当且仅当内容一致。 */
323
+ const remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
324
+ const localSha = remoteSha ? npm.localShasumOf(dir) : null
325
+ if (remoteSha && localSha && remoteSha !== localSha) {
326
+ log(`✗ ${label} — 同版本内容漂移:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${localSha.slice(0, 8)}`)
327
+ log(' npm 不允许同版本重发,请 bump 版本后再发布')
328
+ return { label, status: 'version-drift', detail: `shasum ${localSha} != ${remoteSha}` }
329
+ }
330
+ if (!remoteSha) log(`! ${label} — 无法获取 registry shasum(网络?),跳过漂移对比`)
331
+ log(`· ${label} — registry 上已存在,跳过`)
332
+ return { label, status: 'skipped-exists' }
333
+ }
334
+
335
+ /* pack 闸只对「真要发布」的包跑(真实 pack + 解包扫描很重,已发布的包由漂移闸把关)。 */
336
+ if (kind === 'plugin') {
337
+ const packErrors = packGateErrors(pkg, dir, npm)
338
+ if (packErrors.length) {
339
+ log(`✗ ${label} — pack 闸未过`)
340
+ for (const item of packErrors) log(` - ${item}`)
341
+ return { label, status: 'pack-incomplete', detail: packErrors }
342
+ }
343
+ }
344
+
345
+ /* 发布顺序闸(发布成功 ≠ 用户能装上):依赖闭包须 registry 可解析或同批发布。 */
346
+ const order = orderGate(pkg, localMap, batch, npm)
347
+ if (order.errors.length) {
348
+ log(`✗ ${label} — 发布顺序闸未过(发布后用户 npm install 会失败)`)
349
+ for (const item of order.errors) log(` - ${item}`)
350
+ return { label, status: 'order-blocked', detail: order.errors }
351
+ }
352
+ for (const w of order.warnings) log(`! ${label} — ${w}`)
353
+
354
+ if (!skipTests && pkg.scripts?.test) {
355
+ const t = npm.rawNpmRun(['test'], { cwd: dir })
356
+ if (t.status !== 0) {
357
+ log(`✗ ${label} — npm test 失败,跳过发布`)
358
+ return { label, status: 'test-failed', detail: (t.stdout || '') + (t.stderr || '') }
359
+ }
360
+ }
361
+
362
+ if (dryRun) {
363
+ log(`→ ${label} — 待发布(dry run${tag !== 'latest' ? `,dist-tag=${tag}` : ''})`)
364
+ return { label, status: 'would-publish' }
365
+ }
366
+
367
+ const access = pkg.publishConfig?.access || 'public'
368
+ const expectedSha = npm.localShasumOf(dir)
369
+ const pub = npm.rawNpmRun(['publish', '--access', access, '--tag', tag], { cwd: dir })
370
+ if (pub.status !== 0) {
371
+ log(`✗ ${label} — npm publish 失败`)
372
+ log(String(pub.stderr || pub.stdout || '').trim().slice(0, 500))
373
+ return { label, status: 'publish-failed', detail: (pub.stdout || '') + (pub.stderr || '') }
374
+ }
375
+ /* 发布后复核:registry 收到的 tarball 必须与本地 pack 逐字节一致(shasum)。 */
376
+ let remoteSha = null
377
+ for (let i = 0; i < 5 && !remoteSha; i++) {
378
+ if (i) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000)
379
+ remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
380
+ }
381
+ if (remoteSha && expectedSha && remoteSha !== expectedSha) {
382
+ log(`✗ ${label} — 发布后复核失败:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${expectedSha.slice(0, 8)}(registry 可能收到脏产物,bump 后重发)`)
383
+ return { label, status: 'publish-corrupted', detail: `shasum ${remoteSha} != ${expectedSha}` }
384
+ }
385
+ if (!remoteSha) log(`! ${label} — 发布后复核降级:registry shasum 暂不可见(副本延迟),请稍后人工核对`)
386
+ log(`✓ ${label} — 已发布${tag !== 'latest' ? `(dist-tag=${tag})` : ''}`)
387
+ return { label, status: 'published' }
388
+ }
389
+
390
+ /** 解析工作区 root:参数 → DSH_PUBLISHER_ROOT。 */
391
+ export function resolveRoot(root) {
392
+ const resolved = root || process.env.DSH_PUBLISHER_ROOT
393
+ if (!resolved) return { error: '缺少工作区路径:传工具参数 root,或设置 DSH_PUBLISHER_ROOT' }
394
+ const abs = path.resolve(resolved)
395
+ if (!fs.existsSync(path.join(abs, 'package.json'))) return { error: `不是插件工程工作区(缺 package.json): ${abs}` }
396
+ return { root: abs }
397
+ }
398
+
399
+ /** 统一发布主流程:发现集 → 批次 → 先库后插件逐包过闸 →(dryRun ? 预演 : 真发布)。 */
400
+ export async function runPublish(options = {}) {
401
+ const {
402
+ only, tag = 'latest', skipTests = false, dryRun = true, libs, log = console.log,
403
+ } = options
404
+ const rootRes = resolveRoot(options.root)
405
+ if (rootRes.error) return { ok: false, error: rootRes.error }
406
+ const root = rootRes.root
407
+
408
+ const supportLibs = Array.isArray(libs) && libs.length ? libs : DEFAULT_SUPPORT_LIBS
409
+ const npm = createNpmContext()
410
+
411
+ const results = []
412
+ const libDirs = supportLibs.map((rel) => path.join(root, rel))
413
+ for (const dir of libDirs) {
414
+ if (!fs.existsSync(path.join(dir, 'package.json'))) {
415
+ results.push({ label: dir, status: 'missing-dir', detail: [`支撑库目录缺失: ${dir}`] })
416
+ }
417
+ }
418
+ const pluginDirs = discoverPlugins({ root })
419
+ const usableLibDirs = libDirs.filter((dir) => fs.existsSync(path.join(dir, 'package.json')))
420
+ if (!usableLibDirs.length && !pluginDirs.length) {
421
+ return { ok: false, root, error: '没有可发布的包(全部被发布闸拦下)', results, summary: {} }
422
+ }
423
+
424
+ log(`模式: ${dryRun ? 'DRY RUN(execute 才会真正发布)' : '执行发布'}${tag !== 'latest' ? `,dist-tag=${tag}` : ''}`)
425
+ log(`候选: ${usableLibDirs.length} 个支撑库 + ${pluginDirs.length} 个插件\n`)
426
+
427
+ /* 本次发布批次 = 候选中 registry 上尚不存在同名版本的包(顺序闸据此放行同批依赖)。 */
428
+ const localMap = new Map()
429
+ for (const dir of [...usableLibDirs, ...pluginDirs]) {
430
+ const pkg = pkgOf(dir)
431
+ localMap.set(pkg.name, { pkg, dir })
432
+ }
433
+ const batch = new Set(
434
+ [...usableLibDirs, ...pluginDirs]
435
+ .map((dir) => pkgOf(dir))
436
+ .filter((pkg) => !only || pkg.name === only)
437
+ .filter((pkg) => !npm.alreadyPublished(pkg.name, pkg.version))
438
+ .map((pkg) => pkg.name),
439
+ )
440
+
441
+ const shared = { localMap, batch, only, tag, skipTests, dryRun, npm, log }
442
+ // 先库后插件:plugin-kit 等支撑库必须先上 registry,插件发布时依赖才可解析
443
+ for (const dir of usableLibDirs) results.push(await publishOne(dir, { kind: 'lib', ...shared }))
444
+ for (const dir of pluginDirs) results.push(await publishOne(dir, { kind: 'plugin', ...shared }))
445
+
446
+ const done = results.filter(Boolean)
447
+ const summary = done.reduce((acc, item) => {
448
+ acc[item.status] = (acc[item.status] || 0) + 1
449
+ return acc
450
+ }, {})
451
+ log(`\n汇总: ${JSON.stringify(summary)}`)
452
+
453
+ return { ok: !done.some((r) => FAILURE_STATUSES.includes(r.status)), root, results: done, summary }
454
+ }
455
+
456
+ /** 契约探针实现。 */
457
+ export function capabilities() {
458
+ return {
459
+ contractVersion: '1.0.0',
460
+ tools: ['publisher_whoami', 'publisher_preview', 'publisher_execute', 'publisher_capabilities'],
461
+ defaults: { port: 39700, tag: 'latest' },
462
+ }
463
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @capyclaw/publisher 服务组合根。
3
+ *
4
+ * 宿主(端口/锁/复用/健康/指标/关闭)由 @capyclaw/service-host 提供;
5
+ * 工具面(能力 DSL/注册表/校验/契约/MCP)由 @capyclaw/tool-host 提供;
6
+ * 本文件只保留业务装配。
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { createServiceApp, send } from '@capyclaw/service-host/src'
12
+ import {
13
+ tools, contractVersion, capabilities, buildInstructions, createMcp,
14
+ } from './tools.mjs'
15
+
16
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
17
+ const DEFAULT_PORT = 39700
18
+ const SERVICE_NAME = 'capyclaw-publisher'
19
+ const PKG = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
20
+
21
+ export async function startService(options = {}) {
22
+ const packageDir = options.packageDir || path.resolve(HERE, '..')
23
+
24
+ const app = createServiceApp({
25
+ id: SERVICE_NAME,
26
+ title: PKG.meta?.title || PKG.name,
27
+ version: PKG.version,
28
+ contractVersion,
29
+ slug: 'publisher',
30
+ health: () => ({
31
+ tools: tools.length,
32
+ }),
33
+ })
34
+
35
+ const instructions = buildInstructions({
36
+ title: PKG.meta?.title || PKG.name,
37
+ intro: '本服务提供 publisher_* 工具,在 dsh 内发布 capyclaw 插件工程的可发布集。',
38
+ startup: [
39
+ '先调用 `publisher_capabilities` 确认 contractVersion 为 1.x。',
40
+ '先 `publisher_whoami` 确认 npm 凭据可用,再 `publisher_preview` 预演。',
41
+ '`publisher_execute` 需要显式 confirm: true,发布不可撤销。',
42
+ ],
43
+ capabilities: capabilities().capabilities,
44
+ rules: ['工具返回已含逐包回执;改完一句话回复,不要重复验证。'],
45
+ })
46
+ const mcp = createMcp({ name: SERVICE_NAME, version: PKG.version }, instructions)
47
+ app.use((req, res, u) => {
48
+ if (u.pathname !== '/mcp') return false
49
+ return mcp(req, res).then(() => true)
50
+ })
51
+
52
+ app.get('/api/info', (req, res) => {
53
+ send(req, res, 200, {
54
+ ok: true,
55
+ name: SERVICE_NAME,
56
+ version: PKG.version,
57
+ contractVersion,
58
+ tools: tools.map((tool) => ({ name: tool.name, description: tool.description })),
59
+ })
60
+ })
61
+
62
+ const info = await app.listen({
63
+ port: Number(options.port ?? DEFAULT_PORT),
64
+ hostDir: options.hostDir,
65
+ strictPort: options.strictPort,
66
+ lockFile: options.lockFile,
67
+ allowReuse: options.allowReuse !== false,
68
+ })
69
+ return { ...info, stop: () => info.stop() }
70
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * MCP 工具面:能力声明 → 注册表 → 工具清单。
3
+ *
4
+ * 发布业务在 impl.mjs;这里只做 schema/分派。
5
+ * publisher_execute 是不可撤销动作:schema 强制 confirm: true。
6
+ */
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import {
11
+ defineTool, defineCapability, createRegistry, createMcpHandler,
12
+ createCapabilityReport, buildInstructions,
13
+ } from '@capyclaw/tool-host/src'
14
+ import { npmWhoami, runPublish, capabilities as capabilitiesImpl } from './impl.mjs'
15
+
16
+ export const contractVersion = '1.0.0'
17
+
18
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
19
+ const PKG = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'))
20
+
21
+ const text = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value, null, 2) }] })
22
+
23
+ const rootSchema = {
24
+ type: 'string',
25
+ maxLength: 500,
26
+ description: '插件工程工作区路径(要发布的仓库 checkout)。缺省用 DSH_PUBLISHER_ROOT。',
27
+ }
28
+
29
+ const whoamiTool = defineTool({
30
+ name: 'publisher_whoami',
31
+ description: 'npm 凭据预检:宿主环境是否已登录(npm whoami / NODE_AUTH_TOKEN)。发布前先调用。',
32
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
33
+ kind: 'read',
34
+ handler: () => text(npmWhoami()),
35
+ })
36
+
37
+ const previewTool = defineTool({
38
+ name: 'publisher_preview',
39
+ description: '发布预演(dry-run):发现集 → 发布闸/pack 闸 → 已发布与同版本漂移 → 依赖顺序闸,返回逐包结果与汇总。不真发布。',
40
+ inputSchema: {
41
+ type: 'object',
42
+ additionalProperties: false,
43
+ properties: {
44
+ root: rootSchema,
45
+ only: { type: 'string', maxLength: 100, description: '只处理这个包名(@capyclaw/xxx)' },
46
+ skipTests: { type: 'boolean', description: '跳过各包 npm test(默认不跳,与原流水线一致)' },
47
+ },
48
+ },
49
+ kind: 'read',
50
+ handler: (args) => runPublish({ ...args, dryRun: true }).then(text),
51
+ })
52
+
53
+ const executeTool = defineTool({
54
+ name: 'publisher_execute',
55
+ description: '真发布到 npm(不可撤销)。必须显式传 confirm: true。流程与 preview 相同,过闸后逐包 npm publish 并做发布后 shasum 复核。',
56
+ inputSchema: {
57
+ type: 'object',
58
+ additionalProperties: false,
59
+ properties: {
60
+ root: rootSchema,
61
+ only: { type: 'string', maxLength: 100, description: '只发布这个包名(@capyclaw/xxx)' },
62
+ tag: { type: 'string', maxLength: 20, description: 'dist-tag(默认 latest)' },
63
+ skipTests: { type: 'boolean', description: '跳过各包 npm test' },
64
+ confirm: { type: 'boolean', description: '必须为 true 才执行' },
65
+ },
66
+ required: ['confirm'],
67
+ },
68
+ kind: 'control',
69
+ handler: (args) => {
70
+ if (args.confirm !== true) {
71
+ return text({ ok: false, error: '发布是不可撤销动作:需要显式传 confirm: true(建议先跑 publisher_preview 核对批次)' })
72
+ }
73
+ return runPublish({ ...args, dryRun: false }).then(text)
74
+ },
75
+ })
76
+
77
+ const capabilitiesTool = defineTool({
78
+ name: 'publisher_capabilities',
79
+ description: '返回契约版本、工具清单和能力说明。',
80
+ inputSchema: { type: 'object', additionalProperties: false, properties: {} },
81
+ kind: 'read',
82
+ handler: () => text({ ...capabilitiesImpl(), name: PKG.name, version: PKG.version }),
83
+ })
84
+
85
+ const capability = defineCapability({
86
+ id: 'publisher',
87
+ title: 'npm 发布器',
88
+ description: '在 dsh 内发布 capyclaw 插件工程:预演(闸门/顺序/漂移)与真发布(需显式 confirm)。',
89
+ tags: ['tool'],
90
+ tools: [whoamiTool, previewTool, executeTool, capabilitiesTool],
91
+ })
92
+
93
+ export const registry = createRegistry([capability], {
94
+ report: ({ editorUrl = '', runtime = {}, ...rest }) => createCapabilityReport({
95
+ ...rest,
96
+ contractVersion,
97
+ packageVersion: PKG.version,
98
+ editorUrl,
99
+ runtime,
100
+ }),
101
+ })
102
+
103
+ export const tools = registry.TOOLS
104
+ export const callTool = (name, args) => registry.TOOL_IMPL[name]?.(args)
105
+ export function capabilities() { return registry.ctx.contract.report() }
106
+
107
+ export function createMcp(serverInfo, instructions) {
108
+ return createMcpHandler({ registry, serverInfo, instructions })
109
+ }
110
+
111
+ export { buildInstructions }