@capyclaw/skills-service 0.1.4 → 0.2.2

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 (68) hide show
  1. package/README.md +3 -3
  2. package/node_modules/@capyclaw/foundation/README.md +51 -0
  3. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  4. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  5. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  6. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  7. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  8. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  9. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  10. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  11. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  12. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  13. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  14. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  15. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  16. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  17. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  25. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  26. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  27. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  28. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  29. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  30. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  31. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  32. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  33. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  34. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  35. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  36. package/node_modules/@capyclaw/foundation/package.json +53 -0
  37. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  38. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  39. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  40. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  41. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +143 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +41 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  67. package/package.json +10 -3
  68. package/server.mjs +49 -13
@@ -0,0 +1,13 @@
1
+ export * from './service/http.mjs'
2
+ export * from './service/server.mjs'
3
+ export * from './service/mcp-http.mjs'
4
+ export * from './service/api.mjs'
5
+ export * from './cli.mjs'
6
+ export * from './zip.mjs'
7
+ export * from './tools/validate.mjs'
8
+ export * from './skills/provider.mjs'
9
+ export * from './editor/lease.mjs'
10
+ export * from './store/journal-store.mjs'
11
+ export * from './store/blob-store.mjs'
12
+ export * from './workspace/manager.mjs'
13
+ export * from './runtime/context.mjs'
@@ -0,0 +1,230 @@
1
+ /** 插件打包:按 package.json files 收集文件、自检(含 manifest 语义校验)、写 ZIP。 */
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { writeZipFromDir, listZipEntries } from './zip.mjs'
5
+
6
+ /**
7
+ * suite/domain manifest 的语义校验器由外部注入。
8
+ *
9
+ * 为什么不在本模块静态 import:`@capyclaw/plugin-kit` 是**可独立发布**的插件 SDK,
10
+ * 而语义校验规则住在 `@capyclaw/suite-kit`(编排层)。硬 import 会让本包在 npm 上
11
+ * 必须连带发布 suite-kit,并把它内部的相对路径问题一起暴露给消费者。
12
+ *
13
+ * 用法(打包工具侧):
14
+ * import { setManifestValidators } from '@capyclaw/plugin-kit/packaging/pack'
15
+ * setManifestValidators({ validateSuiteManifest, validateDomainManifest })
16
+ * 未注入时只做结构校验,并在 warnings 里明确说明语义校验被跳过。
17
+ */
18
+ let injectedValidators = null
19
+
20
+ export function setManifestValidators(validators) {
21
+ injectedValidators = validators && typeof validators === 'object' ? validators : null
22
+ }
23
+
24
+ export function getManifestValidators() {
25
+ return injectedValidators
26
+ }
27
+
28
+ const ALWAYS_INCLUDE = ['package.json', 'README.md', 'LICENSE', 'LICENSE.md', 'THIRD_PARTY_NOTICES.md']
29
+ const DEFAULT_EXCLUDES = [
30
+ 'node_modules', '.git', '.DS_Store', 'dist', 'build', 'coverage', '.temp-pack',
31
+ /* 运行时状态绝不可进发布包:`.host` 里是 discovery.json / .relay-instance.lock,
32
+ * 打进去等于把"上一台机器上跑过的实例"带走——新机器首次启动会以为端口被占、
33
+ * 单实例锁被持有,服务起不来。日志同理。 */
34
+ '.host', '*.log',
35
+ ]
36
+
37
+ function normalize(value) {
38
+ return value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
39
+ }
40
+
41
+ function globToRegExp(glob) {
42
+ let out = '^'
43
+ for (let i = 0; i < glob.length; i++) {
44
+ const char = glob[i]
45
+ if (char === '*') {
46
+ if (glob[i + 1] === '*') {
47
+ out += '.*'
48
+ i++
49
+ if (glob[i + 1] === '/') i++
50
+ } else {
51
+ out += '[^/]*'
52
+ }
53
+ } else if (char === '?') out += '[^/]'
54
+ else out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
55
+ }
56
+ return new RegExp(out + '$')
57
+ }
58
+
59
+ function matches(rel, pattern) {
60
+ const p = normalize(pattern)
61
+ if (!p.includes('*') && !p.includes('?')) return rel === p || rel.startsWith(p + '/')
62
+ return globToRegExp(p).test(rel)
63
+ }
64
+
65
+ function exists(dir, rel) {
66
+ return fs.existsSync(path.join(dir, rel))
67
+ }
68
+
69
+ function walk(dir, base = dir) {
70
+ const out = []
71
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
72
+ const full = path.join(dir, entry.name)
73
+ if (entry.isDirectory()) out.push(...walk(full, base))
74
+ else if (entry.isFile()) out.push(path.relative(base, full).replace(/\\/g, '/'))
75
+ }
76
+ return out.sort()
77
+ }
78
+
79
+ function expandEntry(srcDir, entry) {
80
+ const rel = normalize(entry)
81
+ if (rel.includes('*') || rel.includes('?')) {
82
+ return walk(srcDir).filter((file) => matches(file, rel))
83
+ }
84
+ if (!exists(srcDir, rel)) return []
85
+ const full = path.join(srcDir, rel)
86
+ if (fs.statSync(full).isDirectory()) return walk(full).map((file) => `${rel}/${file}`)
87
+ return [rel]
88
+ }
89
+
90
+ export function collectPluginFiles(srcDir, pkg, { keepNodeModules = false } = {}) {
91
+ const includes = []
92
+ const excludes = [
93
+ ...DEFAULT_EXCLUDES.filter((item) => !(keepNodeModules && item === 'node_modules')),
94
+ ...(pkg.files || []).filter((item) => String(item).startsWith('!')).map((item) => normalize(String(item).slice(1))),
95
+ ]
96
+ const declared = (pkg.files || []).filter((item) => !String(item).startsWith('!')).map(String)
97
+
98
+ for (const item of ALWAYS_INCLUDE) if (exists(srcDir, item) && !includes.includes(item)) includes.push(item)
99
+ if (!declared.length || keepNodeModules) {
100
+ /* keepNodeModules:整目录收集(拼装产物 node_modules 里的成员必须随包走)。 */
101
+ for (const item of fs.readdirSync(srcDir)) {
102
+ const rel = normalize(item)
103
+ if (excludes.some((ex) => matches(rel, ex))) continue
104
+ for (const file of expandEntry(srcDir, rel)) if (!includes.includes(file)) includes.push(file)
105
+ }
106
+ } else {
107
+ for (const item of declared) {
108
+ const expanded = expandEntry(srcDir, item)
109
+ if (!expanded.length) throw new Error(`package.json files 条目不存在: ${item}`)
110
+ for (const file of expanded) if (!includes.includes(file)) includes.push(file)
111
+ }
112
+ }
113
+
114
+ const files = includes
115
+ .filter((rel) => !excludes.some((ex) => matches(rel, ex)))
116
+ .sort()
117
+ if (!files.includes('package.json')) throw new Error('打包结果缺少 package.json')
118
+ return files
119
+ }
120
+
121
+ function copyFile(srcDir, destDir, rel) {
122
+ const src = path.join(srcDir, rel)
123
+ const dest = path.join(destDir, rel)
124
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
125
+ fs.copyFileSync(src, dest)
126
+ }
127
+
128
+ export function validateStaged(stagedDir, pkg) {
129
+ const errors = []
130
+ if (!fs.existsSync(path.join(stagedDir, 'package.json'))) errors.push('缺少 package.json')
131
+ if (pkg.main && !fs.existsSync(path.join(stagedDir, pkg.main))) errors.push(`缺少入口文件: ${pkg.main}`)
132
+ const patch = pkg.dsh?.bundle?.patch
133
+ /* 成员包(dsh.member: true)随套件分发,本就不该带补丁;带了会和套件重复声明同一行,
134
+ * 那个行归属冲突会直接卡死卸载(bundle-in-use)。 */
135
+ if (pkg.dsh?.member === true) {
136
+ if (patch) errors.push('成员包(dsh.member: true)不应声明 dsh.bundle.patch')
137
+ } else if (pkg.dsh && !patch) {
138
+ errors.push('缺少 dsh.bundle.patch 配置')
139
+ } else if (patch && !fs.existsSync(path.join(stagedDir, patch))) {
140
+ errors.push(`缺少 cordis patch: ${patch}`)
141
+ }
142
+ if (pkg.dsh?.suite && !fs.existsSync(path.join(stagedDir, pkg.dsh.suite))) {
143
+ errors.push(`缺少 suite manifest: ${pkg.dsh.suite}`)
144
+ }
145
+ if (errors.length) throw new Error(`打包自检失败:\n- ${errors.join('\n- ')}`)
146
+ return true
147
+ }
148
+
149
+ /** manifest 语义校验:若已注入 @capyclaw/suite-kit 的校验器则用同一套规则(与安装侧一致),
150
+ * 否则只做结构校验并在 warnings 里说明。返回 { errors, warnings };不传 baseDir——
151
+ * ZIP 内引用的兄弟包路径在包外,存在性检查留给安装侧。 */
152
+ export function validateManifests(stagedDir, pkg) {
153
+ const errors = []
154
+ const warnings = []
155
+ const readJson = (rel) => JSON.parse(fs.readFileSync(path.join(stagedDir, rel), 'utf8'))
156
+ const suiteRel = pkg.dsh?.suite
157
+ if (suiteRel) {
158
+ if (!injectedValidators?.validateSuiteManifest) {
159
+ warnings.push(`未注入 suite 语义校验器,已跳过 ${suiteRel} 的语义检查(仅校验存在性)`)
160
+ } else {
161
+ try {
162
+ const result = injectedValidators.validateSuiteManifest(readJson(suiteRel))
163
+ errors.push(...result.errors)
164
+ warnings.push(...result.warnings)
165
+ } catch (error) {
166
+ errors.push(`suite manifest 解析失败 (${suiteRel}): ${error.message}`)
167
+ }
168
+ }
169
+ }
170
+ const domainRel = pkg.dsh?.domain || (fs.existsSync(path.join(stagedDir, 'dsh-domain.json')) ? 'dsh-domain.json' : null)
171
+ if (domainRel) {
172
+ if (!injectedValidators?.validateDomainManifest) {
173
+ warnings.push(`未注入 domain 语义校验器,已跳过 ${domainRel} 的语义检查(仅校验存在性)`)
174
+ } else {
175
+ try {
176
+ const result = injectedValidators.validateDomainManifest(readJson(domainRel))
177
+ errors.push(...result.errors)
178
+ warnings.push(...result.warnings)
179
+ } catch (error) {
180
+ errors.push(`domain manifest 解析失败 (${domainRel}): ${error.message}`)
181
+ }
182
+ }
183
+ }
184
+ return { errors, warnings }
185
+ }
186
+
187
+ /**
188
+ * 把插件复制到 staging 目录。
189
+ *
190
+ * keepNodeModules:拼装产物(dist/suites/<bridge>/package)的成员就装在包内
191
+ * node_modules 里,打包时必须整目录带走,否则 zip 解压后成员全丢。
192
+ *
193
+ * @param {{srcDir:string,destDir:string,keepNodeModules?:boolean}} options
194
+ */
195
+ export function stagePlugin({ srcDir, destDir, keepNodeModules = false }) {
196
+ const pkg = JSON.parse(fs.readFileSync(path.join(srcDir, 'package.json'), 'utf8'))
197
+ const files = collectPluginFiles(srcDir, pkg, { keepNodeModules })
198
+ fs.rmSync(destDir, { recursive: true, force: true })
199
+ for (const file of files) copyFile(srcDir, destDir, file)
200
+ validateStaged(destDir, pkg)
201
+ const { errors, warnings } = validateManifests(destDir, pkg)
202
+ if (errors.length) throw new Error(`打包自检失败(manifest 语义校验):\n- ${errors.join('\n- ')}`)
203
+ return { pkg, files, warnings }
204
+ }
205
+
206
+ /**
207
+ * 生成插件 ZIP —— 本仓唯一的「插件 → zip」实现。
208
+ *
209
+ * 命名约定与源索引一致:`<包名去 scope>-<version>.zip`(如
210
+ * `@capyclaw/ppt-suite@2.5.0` → `capyclaw-ppt-suite-2.5.0.zip`)。
211
+ * `releasePlugin`(发布闸 + vendor)与 `pack-plugin` CLI 都走这里,不再各写一份。
212
+ *
213
+ * @param {{srcDir:string,outDir:string,name?:string,version?:string,keepNodeModules?:boolean,
214
+ * beforeZip?:(stagingDir:string)=>void}} options
215
+ */
216
+ export function packPlugin({ srcDir, outDir, name, version, keepNodeModules = false, beforeZip }) {
217
+ const pkg = JSON.parse(fs.readFileSync(path.join(srcDir, 'package.json'), 'utf8'))
218
+ const safeName = String(name || pkg.name).replace(/^@/, '').replace(/[\\/]/g, '-')
219
+ const outFile = path.join(outDir, `${safeName}-${version || pkg.version}.zip`)
220
+ const staging = path.join(outDir, `.stage-${safeName}-${process.pid}`)
221
+ fs.mkdirSync(outDir, { recursive: true })
222
+ try {
223
+ const staged = stagePlugin({ srcDir, destDir: staging, keepNodeModules })
224
+ if (beforeZip) beforeZip(staging)
225
+ writeZipFromDir(staging, outFile)
226
+ return { outFile, files: staged.files, entries: listZipEntries(outFile), pkg: staged.pkg, warnings: staged.warnings }
227
+ } finally {
228
+ fs.rmSync(staging, { recursive: true, force: true })
229
+ }
230
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Runtime context:插件启动时读取本次 DSH runtime 的端口、目录、namespace。
3
+ *
4
+ * 优先级:
5
+ * 1. 显式 runtimeFile / config.runtimeFile
6
+ * 2. DSH_RUNTIME_FILE
7
+ * 3. DSH_RUNTIME_ID + DSH_STORE_ROOT + DSH_STORE_TOKEN 环境变量
8
+ *
9
+ * 插件不应再读全局插件目录或写死端口;所有持久化内容都走
10
+ * WorkspaceClient,确保只作用于当前 runtime 的 namespace。
11
+ */
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { WorkspaceManager, WorkspaceClient } from '../workspace/manager.mjs'
15
+
16
+ function readJson(file, fallback = null) {
17
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return fallback }
18
+ }
19
+
20
+ export function runtimeFileFromEnv(env = process.env) {
21
+ return env.DSH_RUNTIME_FILE || ''
22
+ }
23
+
24
+ export function loadRuntimeContext({ runtimeFile, env = process.env } = {}) {
25
+ const file = runtimeFile || runtimeFileFromEnv(env)
26
+ if (file && fs.existsSync(file)) {
27
+ const runtime = readJson(file, null)
28
+ if (!runtime) throw new Error(`runtime 文件损坏: ${file}`)
29
+ return normalizeRuntime(runtime, { runtimeFile: path.resolve(file), env })
30
+ }
31
+ if (env.DSH_RUNTIME_ID && env.DSH_STORE_ROOT) {
32
+ return normalizeRuntime({
33
+ runtimeId: env.DSH_RUNTIME_ID,
34
+ storeRoot: env.DSH_STORE_ROOT,
35
+ ports: {
36
+ harness: Number(env.DSH_PROXY_PORT) || 0,
37
+ dsh: Number(env.DSH_UP_PORT) || 0,
38
+ content: Number(env.DSH_CONTENT_PORT) || 0,
39
+ },
40
+ paths: {
41
+ root: env.DSH_RUNTIME_ROOT || '',
42
+ dshHome: env.DSH_HOME || '',
43
+ workspace: env.DSH_WORKSPACE || '',
44
+ logs: env.DSH_LOG_DIR || '',
45
+ tmp: env.DSH_TMP_DIR || '',
46
+ contentState: env.DSH_CONTENT_STATE || '',
47
+ },
48
+ store: {
49
+ root: env.DSH_STORE_ROOT,
50
+ namespace: env.DSH_STORE_NAMESPACE || env.DSH_RUNTIME_ID,
51
+ token: env.DSH_STORE_TOKEN || '',
52
+ },
53
+ workId: env.DSH_WORK_ID || 'main',
54
+ profile: env.DSH_PROFILE || '',
55
+ domain: env.DSH_DOMAIN || '',
56
+ }, { runtimeFile: null, env })
57
+ }
58
+ return null
59
+ }
60
+
61
+ function normalizeRuntime(runtime, { runtimeFile = null, env = process.env } = {}) {
62
+ const store = runtime.store || {}
63
+ const paths = runtime.paths || {}
64
+ const ports = runtime.ports || {}
65
+ return {
66
+ ...runtime,
67
+ runtimeFile,
68
+ runtimeId: runtime.runtimeId || env.DSH_RUNTIME_ID || '',
69
+ storeRoot: runtime.storeRoot || store.root || env.DSH_STORE_ROOT || '',
70
+ store: {
71
+ root: store.root || runtime.storeRoot || env.DSH_STORE_ROOT || '',
72
+ namespace: store.namespace || runtime.runtimeId || env.DSH_RUNTIME_ID || '',
73
+ token: store.token || env.DSH_STORE_TOKEN || '',
74
+ },
75
+ ports: {
76
+ harness: Number(ports.harness) || Number(env.DSH_PROXY_PORT) || 0,
77
+ dsh: Number(ports.dsh) || Number(env.DSH_UP_PORT) || 0,
78
+ content: Number(ports.content) || Number(env.DSH_CONTENT_PORT) || 0,
79
+ ...ports,
80
+ },
81
+ paths: {
82
+ root: paths.root || '',
83
+ dshHome: paths.dshHome || env.DSH_HOME || '',
84
+ workspace: paths.workspace || env.DSH_WORKSPACE || '',
85
+ logs: paths.logs || env.DSH_LOG_DIR || '',
86
+ tmp: paths.tmp || env.DSH_TMP_DIR || '',
87
+ contentState: paths.contentState || env.DSH_CONTENT_STATE || '',
88
+ ...paths,
89
+ },
90
+ workId: runtime.workId || env.DSH_WORK_ID || 'main',
91
+ }
92
+ }
93
+
94
+ export function runtimeContextFromConfig(config = {}, options = {}) {
95
+ if (config && config.runtimeContext && typeof config.runtimeContext === 'object') {
96
+ return normalizeRuntime(config.runtimeContext, options)
97
+ }
98
+ if (config && config.runtimeFile) return loadRuntimeContext({ ...options, runtimeFile: config.runtimeFile })
99
+ return loadRuntimeContext(options)
100
+ }
101
+
102
+ export function createRuntimeStoreClient(context, { workId } = {}) {
103
+ if (!context || !context.store || !context.store.root || !context.store.token) {
104
+ return null
105
+ }
106
+ const store = new WorkspaceManager({ storeRoot: context.store.root })
107
+ return new WorkspaceClient({
108
+ manager: store,
109
+ runtimeId: context.store.namespace || context.runtimeId,
110
+ token: context.store.token,
111
+ workId: workId || context.workId || 'main',
112
+ })
113
+ }
114
+
115
+ export function runtimePaths(context) {
116
+ return (context && context.paths) || {}
117
+ }
118
+
119
+ export function isPathInside(root, target) {
120
+ if (!root || !target) return false
121
+ const rel = path.relative(path.resolve(root), path.resolve(target))
122
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
123
+ }
124
+
125
+ export function assertPathInside(root, target, label = 'path') {
126
+ if (!isPathInside(root, target)) throw new Error(`${label} 越出 runtime 根目录: ${target}`)
127
+ return path.resolve(target)
128
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * 自包含打包(vendoring)—— 全流水线唯一实现。
3
+ *
4
+ * 背景:本仓的插件既要走 **zip 分发**(dist/plugins/*.zip),也要走 **npm 分发**
5
+ * (`dsh plugin add @capyclaw/xxx`)。两条通道的「自包含」语义此前不一致:
6
+ *
7
+ * - zip 通道:plugin-kit 的 packPlugin 会保留 node_modules,产物自带成员 → 自包含;
8
+ * - npm 通道:`npm pack` / `npm publish` **默认剥离 node_modules**,只有包内
9
+ * `bundledDependencies` 列出的依赖才会被打进 tarball → 不自包含。
10
+ *
11
+ * 结果:同一个包,zip 装完是自包含的,npm 装完却要回头去 registry 逐个解析依赖。
12
+ * 用户侧表现为「明明包里带了 skill,换个机器 npm 装出来却还要联网拉一堆东西」。
13
+ *
14
+ * 本模块把 npm 语义收敛到与 zip 一致:给定一个 staging 目录,
15
+ * 1. 从根 package.json 的 dependencies 出发求**传递闭包**;
16
+ * 2. 闭包里每个包都解析到实体目录并拷进 `<staging>/node_modules/`;
17
+ * 3. 把闭包写进根 package.json 的 `bundledDependencies`。
18
+ *
19
+ * 三条约束(实测 npm 行为,见 scripts/test 里的用例):
20
+ * - `bundledDependencies` 会**覆盖** `files` 白名单:列出的包一定进 tarball;
21
+ * - 不在 bundledDependencies 里的 node_modules 目录会被**剥离**;
22
+ * - 必须同时满足「在 bundledDependencies 里」且「在依赖图可达」两个条件,
23
+ * 否则 npm 会丢弃(孤立的 pako 实验即此)。故闭包口径 = 可达 ∩ 有实体。
24
+ *
25
+ * `files` 不需要改:npm 对 bundledDependencies 另有通道。
26
+ * `dependencies` 也不要删:bundledDependencies 要求包在依赖图里可达。
27
+ */
28
+ import fs from 'node:fs'
29
+ import path from 'node:path'
30
+
31
+ /** 拷贝依赖时跳过的目录(运行时状态、VCS、测试与非分发内容)。
32
+ * 注意:**不能跳 `dist`**。我们自己的包把源码放 src/,但第三方依赖常常只有 dist/
33
+ * (pptxgenjs 的 main 就是 `dist/pptxgen.cjs.js`)——跳过它等于把依赖拷成一个空壳,
34
+ * 装出来的包里 `ppt_export_pptx` 会报「没有安装 pptxgenjs」,而目录明明存在。 */
35
+ const VENDOR_SKIP_DIRS = new Set([
36
+ 'node_modules', '.git', '.github', 'test', 'tests', '__tests__',
37
+ 'coverage', '.host', '__pycache__', '.cache', '.temp-pack',
38
+ ])
39
+
40
+ function readJson(file) {
41
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
42
+ }
43
+
44
+ function hasPackage(dir) {
45
+ return Boolean(dir) && fs.existsSync(path.join(dir, 'package.json'))
46
+ }
47
+
48
+ /**
49
+ * 目录里的包是否**真的可用**:package.json 声明的入口文件必须存在。
50
+ *
51
+ * 为什么不能只看 package.json:曾经 `dist` 被当成「非分发内容」跳过,
52
+ * 于是 pptxgenjs 拷进来只有 package.json + types,`hasPackage()` 为真、
53
+ * 拼装闸放行,安装后 `import('pptxgenjs')` 才炸。空壳包必须能被识别出来重拷。
54
+ */
55
+ export function isUsablePackage(dir) {
56
+ if (!hasPackage(dir)) return false
57
+ let pkg
58
+ try { pkg = readJson(path.join(dir, 'package.json')) } catch { return false }
59
+ const entries = []
60
+ const exportsField = pkg.exports
61
+ if (typeof exportsField === 'string') entries.push(exportsField)
62
+ else if (exportsField && typeof exportsField === 'object') {
63
+ const root = exportsField['.'] ?? exportsField
64
+ if (typeof root === 'string') entries.push(root)
65
+ else if (root && typeof root === 'object') {
66
+ for (const value of Object.values(root)) {
67
+ if (typeof value === 'string') entries.push(value)
68
+ else if (value && typeof value === 'object') {
69
+ for (const deep of Object.values(value)) if (typeof deep === 'string') entries.push(deep)
70
+ }
71
+ }
72
+ }
73
+ }
74
+ if (typeof pkg.main === 'string') entries.push(pkg.main)
75
+ if (typeof pkg.module === 'string') entries.push(pkg.module)
76
+ /* 没有入口声明(纯资源包):只要目录里有文件就算可用。 */
77
+ if (!entries.length) {
78
+ try {
79
+ return fs.readdirSync(dir).some((name) => name !== 'package.json')
80
+ } catch { return false }
81
+ }
82
+ return entries.some((rel) => fs.existsSync(path.join(dir, rel.replace(/^\.\//, ''))))
83
+ }
84
+
85
+ /**
86
+ * 工作区包解析器:按本仓布局把包名解析到实体目录。
87
+ *
88
+ * 查找顺序(先近后远,staging 内已有的优先,避免重复劳动):
89
+ * 1. `<staging>/node_modules/<name>` —— 已拼装/已 vendor 的成员
90
+ * 2. `<root>/node_modules/<name>` —— 仓库已安装的第三方依赖与 workspace 链接
91
+ * 3. `<root>/packages/<dir名>` —— 公共基建包
92
+ * 4. `<root>/B/official/<dir名>`
93
+ * 5. `<root>/projects/<项目>/artifacts/plugin/<dir名>` —— 各项目的构建产物
94
+ *
95
+ * `@scope/name` → 目录名候选 `@scope/name` 与 `scope-name` 两种形态都试。
96
+ */
97
+ export function createWorkspaceResolver({ root, stagingDir }) {
98
+ const dirNameCandidates = (name) => {
99
+ const out = new Set([name])
100
+ if (name.startsWith('@') && name.includes('/')) {
101
+ const [scope, base] = name.slice(1).split('/')
102
+ out.add(`${scope}-${base}`)
103
+ out.add(base)
104
+ }
105
+ return [...out]
106
+ }
107
+
108
+ /** 项目产物目录:projects/<任意>/artifacts/plugin。 */
109
+ const projectArtifactDirs = () => {
110
+ const out = []
111
+ const projectsDir = path.join(root, 'A/projects')
112
+ let projects = []
113
+ try { projects = fs.readdirSync(projectsDir, { withFileTypes: true }) } catch { return out }
114
+ for (const entry of projects) {
115
+ if (!entry.isDirectory()) continue
116
+ out.push(path.join(projectsDir, entry.name, 'artifacts', 'plugin'))
117
+ }
118
+ return out
119
+ }
120
+
121
+ return function resolve(name) {
122
+ for (const candidate of dirNameCandidates(name)) {
123
+ const direct = [
124
+ path.join(stagingDir, 'node_modules', candidate),
125
+ path.join(root, 'node_modules', candidate),
126
+ path.join(root, 'C/packages', candidate),
127
+ path.join(root, 'B', 'official', candidate),
128
+ ]
129
+ for (const dir of direct) {
130
+ if (hasPackage(dir)) return dir
131
+ }
132
+ for (const base of projectArtifactDirs()) {
133
+ const dir = path.join(base, candidate)
134
+ if (hasPackage(dir)) return dir
135
+ }
136
+ }
137
+ return null
138
+ }
139
+ }
140
+
141
+ /**
142
+ * 从根 package.json 求**可达依赖闭包**,并标注每个包是否已有实体。
143
+ *
144
+ * @returns {{names:string[], present:string[], missing:string[]}}
145
+ */
146
+ export function computeDependencyClosure(pkg, resolve) {
147
+ const present = []
148
+ const missing = []
149
+ const seen = new Set()
150
+ const queue = [
151
+ ...Object.keys(pkg.dependencies || {}),
152
+ ...Object.keys(pkg.optionalDependencies || {}),
153
+ ]
154
+
155
+ while (queue.length) {
156
+ const name = queue.shift()
157
+ if (seen.has(name)) continue
158
+ seen.add(name)
159
+
160
+ const dir = resolve(name)
161
+ if (!dir) { missing.push(name); continue }
162
+
163
+ present.push(name)
164
+ let depPkg = {}
165
+ try { depPkg = readJson(path.join(dir, 'package.json')) } catch { /* 坏清单:仍保留实体,不阻断 */ }
166
+ for (const dep of Object.keys(depPkg.dependencies || {})) {
167
+ if (!seen.has(dep)) queue.push(dep)
168
+ }
169
+ for (const dep of Object.keys(depPkg.optionalDependencies || {})) {
170
+ if (!seen.has(dep)) queue.push(dep)
171
+ }
172
+ /* peerDependencies 不作为传递展开项:npm 语义里 peer 由上层提供,
173
+ * 但若上层确实装了实体,它已在 dependencies 链路里;不额外强拉。 */
174
+ }
175
+
176
+ return { names: [...seen].sort(), present: present.sort(), missing: [...new Set(missing)].sort() }
177
+ }
178
+
179
+ /** 把目录内容递归拷到目标(跳过 VENDOR_SKIP_DIRS)。返回拷贝的文件数。 */
180
+ export function copyDirContents(srcDir, destDir) {
181
+ let count = 0
182
+ const walk = (from, to) => {
183
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
184
+ if (VENDOR_SKIP_DIRS.has(entry.name)) continue
185
+ const s = path.join(from, entry.name)
186
+ const d = path.join(to, entry.name)
187
+ if (entry.isDirectory()) {
188
+ fs.mkdirSync(d, { recursive: true })
189
+ walk(s, d)
190
+ } else if (entry.isFile()) {
191
+ fs.mkdirSync(path.dirname(d), { recursive: true })
192
+ fs.copyFileSync(s, d)
193
+ count++
194
+ }
195
+ }
196
+ }
197
+ walk(srcDir, destDir)
198
+ return count
199
+ }
200
+
201
+ /** 覆写根 package.json 的 bundledDependencies(数组已排序、去重)。 */
202
+ export function writeBundledDependencies(pkgFile, names) {
203
+ const pkg = readJson(pkgFile)
204
+ const unique = [...new Set(names)].sort()
205
+ pkg.bundledDependencies = unique
206
+ fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`)
207
+ return unique
208
+ }
209
+
210
+ /**
211
+ * 让一个 staging 目录变成自包含包。
212
+ *
213
+ * 幂等:已存在于 `<staging>/node_modules/<name>` 的包不会被重复拷贝,
214
+ * 因此对 C 段拼装产物(成员已就位)调用只是补第三方依赖 + 写清单。
215
+ *
216
+ * @param {{stagingDir:string, root:string, verbose?:boolean}} options
217
+ * @returns {{bundled:string[], missing:string[], copied:number}}
218
+ */
219
+ export function makeSelfContained({ stagingDir, root, verbose = false }) {
220
+ const pkgFile = path.join(stagingDir, 'package.json')
221
+ if (!fs.existsSync(pkgFile)) throw new Error(`自包含打包缺少 package.json: ${stagingDir}`)
222
+
223
+ const pkg = readJson(pkgFile)
224
+ const resolve = createWorkspaceResolver({ root, stagingDir })
225
+ const closure = computeDependencyClosure(pkg, resolve)
226
+
227
+ const modulesDir = path.join(stagingDir, 'node_modules')
228
+ /* 重拷空壳时不能再解析到 staging 自己(解析器优先 staging,删掉后就 ENOENT)。 */
229
+ const resolveOutside = createWorkspaceResolver({ root, stagingDir: path.join(stagingDir, '__not_a_staging__') })
230
+ let copied = 0
231
+ let repaired = 0
232
+ for (const name of closure.present) {
233
+ const dest = path.join(modulesDir, name)
234
+ /* 已存在且入口完整 → 跳过;存在但缺入口(历史空壳)→ 删掉重拷。 */
235
+ if (isUsablePackage(dest)) continue
236
+ let src = resolve(name)
237
+ if (hasPackage(dest)) {
238
+ fs.rmSync(dest, { recursive: true, force: true })
239
+ repaired++
240
+ if (verbose) console.log(` ~ 重拷空壳依赖 ${name}`)
241
+ src = resolveOutside(name)
242
+ }
243
+ if (!src) continue
244
+ copied += copyDirContents(src, dest)
245
+ if (verbose) console.log(` + vendor ${name} ← ${path.relative(root, src).replace(/\\/g, '/')}`)
246
+ }
247
+
248
+ const bundled = writeBundledDependencies(pkgFile, closure.present)
249
+ return { bundled, missing: closure.missing, copied, repaired }
250
+ }
251
+
252
+ /**
253
+ * 校验闸:给定 staging 目录,断言它「自包含」——
254
+ * 根依赖闭包里每个包都能在**包内** node_modules 解析到实体,
255
+ * 且 bundledDependencies 与之一致。返回错误数组(空数组 = 通过)。
256
+ */
257
+ export function selfContainedErrors({ stagingDir, root }) {
258
+ const errors = []
259
+ const pkgFile = path.join(stagingDir, 'package.json')
260
+ if (!fs.existsSync(pkgFile)) return [`缺少 package.json: ${stagingDir}`]
261
+ const pkg = readJson(pkgFile)
262
+
263
+ const declared = Array.isArray(pkg.bundledDependencies)
264
+ ? pkg.bundledDependencies
265
+ : Array.isArray(pkg.bundleDependencies) ? pkg.bundleDependencies : []
266
+
267
+ const declaredDeps = Object.keys(pkg.dependencies || {})
268
+ if (!declaredDeps.length) return [] // 无运行时依赖:天然自包含
269
+
270
+ if (!declared.length) {
271
+ errors.push('缺少 bundledDependencies:npm/pnpm 打包会剥离 node_modules,安装后需回 registry 逐个解析')
272
+ return errors
273
+ }
274
+
275
+ /* 包内实体必须齐:这是「解压即用」的硬条件。
276
+ * 注意要查**整个闭包**而非只有直接依赖——传递依赖缺一个,安装后照样要联网。
277
+ * 解析器会回退到仓库根目录,所以这里必须显式只看包内 node_modules。 */
278
+ const resolve = createWorkspaceResolver({ root, stagingDir })
279
+ const closure = computeDependencyClosure(pkg, resolve)
280
+ if (closure.missing.length) {
281
+ errors.push(`依赖闭包无法解析到实体(会迫使安装侧联网): ${closure.missing.join(', ')}`)
282
+ }
283
+
284
+ const missingInPackage = closure.present.filter(
285
+ (name) => !hasPackage(path.join(stagingDir, 'node_modules', name)),
286
+ )
287
+ if (missingInPackage.length) {
288
+ errors.push(`依赖未随包携带(安装后需从 registry 拉取): ${missingInPackage.join(', ')}`)
289
+ }
290
+
291
+ /* 有目录但没入口 = 空壳:比缺目录更隐蔽,必须单独报。 */
292
+ const hollow = closure.present.filter((name) => {
293
+ const dir = path.join(stagingDir, 'node_modules', name)
294
+ return hasPackage(dir) && !isUsablePackage(dir)
295
+ })
296
+ if (hollow.length) {
297
+ errors.push(`依赖是空壳(package.json 在、入口文件缺): ${hollow.join(', ')}`)
298
+ }
299
+
300
+ /* bundledDependencies 必须覆盖闭包。 */
301
+ const notBundled = closure.present.filter((name) => !declared.includes(name))
302
+ if (notBundled.length) {
303
+ errors.push(`传递依赖未列入 bundledDependencies(npm 会丢弃): ${notBundled.join(', ')}`)
304
+ }
305
+
306
+ return errors
307
+ }