@capyclaw/capyclaw-workbench 0.0.0-stage → 0.1.1

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 (119) hide show
  1. package/README.md +56 -2
  2. package/contract/capabilities.json +178 -0
  3. package/lib/descriptors.mjs +33 -0
  4. package/lib/host.mjs +106 -0
  5. package/lib/session-port.mjs +178 -0
  6. package/lib/session-watch.mjs +82 -0
  7. package/lib/tools.mjs +166 -0
  8. package/lib/workbench.mjs +133 -0
  9. package/lib/workspace-attach.mjs +147 -0
  10. package/node_modules/@capyclaw/foundation/README.md +51 -0
  11. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  12. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  13. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  14. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  15. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  16. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  17. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  18. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  19. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  20. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  21. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  22. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  23. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  35. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  39. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  40. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  41. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  42. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  45. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  46. package/node_modules/@capyclaw/foundation/package.json +53 -0
  47. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  48. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  49. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  50. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  51. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  79. package/node_modules/@capyclaw/service-host/README.md +86 -0
  80. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  81. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  82. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  83. package/node_modules/@capyclaw/service-host/package.json +60 -0
  84. package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
  85. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  86. package/node_modules/@capyclaw/suite-kit/README.md +289 -0
  87. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  88. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  89. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  90. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  91. package/node_modules/@capyclaw/suite-kit/package.json +58 -0
  92. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  93. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  94. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  95. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  96. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  97. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  98. package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
  99. package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
  100. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  101. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  102. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  103. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  104. package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
  105. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  106. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  107. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  108. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  109. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  110. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  111. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  114. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  115. package/package.json +68 -4
  116. package/plugin.mjs +17 -0
  117. package/ui/app.js +114 -0
  118. package/ui/index.html +64 -0
  119. package/ui/style.css +54 -0
@@ -0,0 +1,181 @@
1
+ /**
2
+ * 统一能力描述符(docs/suite-interop-standard.md §A.4 / §B.6)——公共契约层。
3
+ *
4
+ * 编排器面向「能力」而非「模式/套件」:描述符只出现产物类型,不出现对方套件。
5
+ * 本模块是纯函数校验/匹配器,不 import 任何具体套件;各套件契约(browser-contract.json、
6
+ * ppt-contract.json …)经 fromContractTool 映射成统一描述符后注册/发现。
7
+ *
8
+ * 双模态(标准 §A.5):surface 声明呈现面(独立 app / 可嵌入子窗口),
9
+ * 控制面不分模式——同一描述符在两种呈现下被同一套工具操控。
10
+ */
11
+
12
+ export const CONTROL_MODES = Object.freeze(['interface', 'browser'])
13
+ export const KINDS = Object.freeze(['read', 'write', 'control'])
14
+ export const RISK_LEVELS = Object.freeze(['low', 'high'])
15
+
16
+ /** 类型词表(B.6):住公共层、版本化;新增类型=加词条,不改套件。 */
17
+ export const TYPE_VOCAB = Object.freeze([
18
+ 'artifact:deck', 'artifact:canvas',
19
+ 'artifact:file/pptx', 'artifact:file/docx', 'artifact:file/xlsx', 'artifact:file/pdf',
20
+ 'artifact:file/html', 'artifact:file/zip',
21
+ 'artifact:image/png', 'artifact:image/jpeg', 'artifact:image/webp',
22
+ 'artifact:dataset/json', 'artifact:dataset/csv',
23
+ 'artifact:text/markdown', 'artifact:text/plain',
24
+ 'artifact:media/video', 'artifact:media/audio',
25
+ 'meta:title', 'meta:desc', 'meta:tags',
26
+ 'result:url', 'result:status',
27
+ // 会话/设置域(capyclaw-suite 子会话能力;标准 v0.3 扩词表)。
28
+ 'session:subsession', 'session:turn', 'session:list', 'session:transcript',
29
+ 'settings:snapshot', 'settings:patch',
30
+ // 编排域(conductor 套件;标准 v0.3 扩词表)。
31
+ 'meta:plan', 'meta:capabilities',
32
+ ])
33
+
34
+ /** 逻辑产物类型 → work-store 信封短类型(envelope.mjs ARTIFACT_TYPES)。
35
+ * 逻辑文档(artifact:deck/canvas)无 raw 信封映射:交接的永远是导出后的 raw asset。 */
36
+ export const ENVELOPE_TYPE_MAP = Object.freeze({
37
+ 'artifact:file/pptx': 'pptx', 'artifact:file/docx': 'docx', 'artifact:file/xlsx': 'xlsx',
38
+ 'artifact:file/pdf': 'pdf', 'artifact:file/html': 'html', 'artifact:file/zip': 'zip',
39
+ 'artifact:image/png': 'image', 'artifact:image/jpeg': 'image', 'artifact:image/webp': 'image',
40
+ 'artifact:dataset/json': 'json', 'artifact:dataset/csv': 'csv',
41
+ 'artifact:text/markdown': 'markdown', 'artifact:text/plain': 'text',
42
+ 'artifact:media/video': 'video', 'artifact:media/audio': 'audio',
43
+ })
44
+
45
+ export function envelopeTypeFor(artifactType) {
46
+ return ENVELOPE_TYPE_MAP[String(artifactType)] ?? null
47
+ }
48
+
49
+ const TYPE_RE = /^(artifact|meta|result|session|settings):[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.*-]+)*$/
50
+ const NAME_RE = /^[A-Za-z][A-Za-z0-9_.-]*$/
51
+
52
+ /** 类型匹配:精确相等,或模式以 `/*` 结尾做前缀匹配(artifact:file/* ⊇ artifact:file/pptx)。 */
53
+ export function typeMatches(pattern, type) {
54
+ const p = String(pattern), t = String(type)
55
+ if (p === t) return true
56
+ if (p.endsWith('/*')) return t.startsWith(p.slice(0, -1))
57
+ return false
58
+ }
59
+
60
+ /** 缺省补齐(不改动入参)。 */
61
+ export function normalizeCapabilityDescriptor(input = {}) {
62
+ const d = { ...input }
63
+ d.consumes = Array.isArray(d.consumes) ? [...d.consumes] : []
64
+ d.produces = Array.isArray(d.produces) ? [...d.produces] : []
65
+ d.auth = d.auth ?? null
66
+ d.risk = d.risk ?? 'low'
67
+ d.confirm = d.confirm ?? false
68
+ d.surface = { standalone: true, embeddable: false, ...(d.surface || {}) }
69
+ return d
70
+ }
71
+
72
+ /** 校验单个描述符 → {ok, errors, warnings}(与 validateSuiteManifest 同风格)。 */
73
+ export function validateCapabilityDescriptor(input, options = {}) {
74
+ const errors = []
75
+ const warnings = []
76
+ const label = options.label ? `${options.label}: ` : ''
77
+ const add = (list, message) => list.push(label + message)
78
+
79
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
80
+ return { ok: false, errors: [label + '描述符必须是 object'], warnings }
81
+ }
82
+ const d = input
83
+ if (typeof d.name !== 'string' || !NAME_RE.test(d.name)) add(errors, 'name 必须是非空标识符(字母开头,可含 . _ -)')
84
+ if (!CONTROL_MODES.includes(d.controlMode)) add(errors, `controlMode 必须是 ${CONTROL_MODES.join('|')},收到: ${d.controlMode}`)
85
+ if (!KINDS.includes(d.kind)) add(errors, `kind 必须是 ${KINDS.join('|')},收到: ${d.kind}`)
86
+ if (typeof d.capability !== 'string' || !d.capability) add(errors, 'capability 必须是非空字符串(能力语义,如 artifact.export)')
87
+
88
+ for (const key of ['consumes', 'produces']) {
89
+ const list = d[key]
90
+ if (list == null) continue
91
+ if (!Array.isArray(list)) { add(errors, `${key} 必须是字符串数组`); continue }
92
+ for (const t of list) {
93
+ if (typeof t !== 'string' || !TYPE_RE.test(t)) { add(errors, `${key} 含非法类型词条: ${t}`); continue }
94
+ if (t.includes('*') && !t.endsWith('/*')) add(errors, `${key} 通配只允许结尾 /*: ${t}`)
95
+ if (!t.includes('*') && !TYPE_VOCAB.includes(t)) add(warnings, `${key} 词条不在当前词表(可扩展,建议登记): ${t}`)
96
+ }
97
+ }
98
+
99
+ if (d.auth != null && (typeof d.auth !== 'string' || !d.auth)) add(errors, 'auth 必须是 null 或非空字符串(如 bilibili:login)')
100
+ if (!RISK_LEVELS.includes(d.risk ?? 'low')) add(errors, `risk 必须是 ${RISK_LEVELS.join('|')}`)
101
+ if (d.confirm != null && typeof d.confirm !== 'boolean') add(errors, 'confirm 必须是 boolean')
102
+ if ((d.risk ?? 'low') === 'high' && d.confirm !== true) add(errors, 'risk:high(不可逆外部动作)强制 confirm:true')
103
+
104
+ if (d.inputSchema != null && (typeof d.inputSchema !== 'object' || Array.isArray(d.inputSchema))) {
105
+ add(errors, 'inputSchema 必须是 object')
106
+ }
107
+ if (d.since != null && (typeof d.since !== 'string' || !d.since)) add(errors, 'since 必须是非空字符串(semver)')
108
+ if (d.suite != null && (typeof d.suite !== 'string' || !d.suite)) add(errors, 'suite 必须是非空字符串')
109
+
110
+ if (d.surface != null) {
111
+ if (typeof d.surface !== 'object' || Array.isArray(d.surface)) add(errors, 'surface 必须是 object')
112
+ else {
113
+ const s = d.surface
114
+ for (const key of ['standalone', 'embeddable']) {
115
+ if (s[key] != null && typeof s[key] !== 'boolean') add(errors, `surface.${key} 必须是 boolean`)
116
+ }
117
+ if (s.embeddable === true && (typeof s.embedPath !== 'string' || !s.embedPath.startsWith('/'))) {
118
+ add(errors, 'surface.embeddable:true 必须给 embedPath(同源本地绝对路径,如 /capyclaw/ppt)')
119
+ }
120
+ if (s.embedPath != null && (typeof s.embedPath !== 'string' || !s.embedPath.startsWith('/'))) {
121
+ add(errors, 'surface.embedPath 必须以 / 开头(同源本地地址)')
122
+ }
123
+ }
124
+ }
125
+ return { ok: errors.length === 0, errors, warnings }
126
+ }
127
+
128
+ /** 校验能力目录:逐个合法 + name 全局唯一。 */
129
+ export function validateCapabilityCatalog(list) {
130
+ const errors = []
131
+ const warnings = []
132
+ if (!Array.isArray(list)) return { ok: false, errors: ['能力目录必须是数组'], warnings }
133
+ const seen = new Set()
134
+ for (const [i, d] of list.entries()) {
135
+ const r = validateCapabilityDescriptor(d, { label: `#${i}${d?.name ? `(${d.name})` : ''}` })
136
+ errors.push(...r.errors)
137
+ warnings.push(...r.warnings)
138
+ if (d && typeof d.name === 'string') {
139
+ if (seen.has(d.name)) errors.push(`能力名重复: ${d.name}`)
140
+ seen.add(d.name)
141
+ }
142
+ }
143
+ return { ok: errors.length === 0, errors, warnings }
144
+ }
145
+
146
+ /**
147
+ * 现有套件契约工具 → 统一描述符。
148
+ * tool 形如 browser-contract.json 的 {name, kind, since, capability, description, inputSchema}。
149
+ * 缺省:interface 模式 auth=null;browser 模式 auth='browser:session';risk=low/confirm=false。
150
+ * 发布类能力必须显式传 risk:'high', confirm:true(校验器强制)。
151
+ */
152
+ export function fromContractTool(tool, options = {}) {
153
+ const controlMode = options.controlMode || 'interface'
154
+ return normalizeCapabilityDescriptor({
155
+ name: tool.name,
156
+ kind: tool.kind,
157
+ since: tool.since,
158
+ description: tool.description,
159
+ inputSchema: tool.inputSchema,
160
+ capability: options.capability || tool.capability || `${options.suite || 'suite'}.${tool.name}`,
161
+ suite: options.suite,
162
+ controlMode,
163
+ auth: options.auth !== undefined ? options.auth : (controlMode === 'browser' ? 'browser:session' : null),
164
+ risk: options.risk ?? 'low',
165
+ confirm: options.confirm ?? false,
166
+ consumes: options.consumes ?? [],
167
+ produces: options.produces ?? [],
168
+ surface: options.surface,
169
+ })
170
+ }
171
+
172
+ /** 链式匹配:descriptor 的 consumes 是否全部能被 producedTypes 覆盖(空 consumes 恒真)。 */
173
+ export function canConsume(descriptor, producedTypes = []) {
174
+ const consumes = Array.isArray(descriptor?.consumes) ? descriptor.consumes : []
175
+ return consumes.every((t) => producedTypes.some((p) => typeMatches(t, p)))
176
+ }
177
+
178
+ /** 发现:目录里谁能产出该类型(编排器按类型找能力,不写死套件/工具名)。 */
179
+ export function findProducers(catalog, type) {
180
+ return (catalog || []).filter((d) => Array.isArray(d.produces) && d.produces.some((p) => typeMatches(p, type)))
181
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * 多 suite 组合:合并 packages / rows / checks,检测冲突并生成 patch。
3
+ */
4
+ import { mkdirSync, writeFileSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { isValidRange, majorOf, validateSuiteManifest, versionSatisfies } from './manifest.mjs'
7
+
8
+ function stable(value) {
9
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`
10
+ if (value && typeof value === 'object') {
11
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`
12
+ }
13
+ return JSON.stringify(value)
14
+ }
15
+
16
+ export const deepEqual = (a, b) => stable(a) === stable(b)
17
+
18
+ function unique(list) {
19
+ return [...new Set(list)]
20
+ }
21
+
22
+ function mergeProvides(target, source) {
23
+ for (const key of ['tools', 'skills', 'services', 'ports']) {
24
+ if (!source?.[key]) continue
25
+ target[key] = unique([...(target[key] || []), ...source[key]])
26
+ }
27
+ if (source?.capabilities) {
28
+ target.capabilities = { ...(target.capabilities || {}), ...source.capabilities }
29
+ }
30
+ return target
31
+ }
32
+
33
+ /**
34
+ * @param {{file:string,dir:string,manifest:object}[]} suites
35
+ * @param {{allowOverride?:boolean}} [options]
36
+ */
37
+ export function composeSuites(suites, options = {}) {
38
+ const errors = []
39
+ const warnings = []
40
+ const packages = new Map()
41
+ const rows = new Map()
42
+ const checks = new Map()
43
+ const ports = new Map()
44
+ const tools = new Map()
45
+ const capabilities = new Map()
46
+
47
+ for (const suite of suites) {
48
+ const { manifest, dir, file } = suite
49
+ const validation = validateSuiteManifest(manifest)
50
+ warnings.push(...validation.warnings.map((w) => `${manifest.name}: ${w}`))
51
+ if (!validation.ok) {
52
+ errors.push(...validation.errors.map((e) => `${manifest.name}: ${e}`))
53
+ continue
54
+ }
55
+
56
+ for (const [name, entry] of Object.entries(manifest.packages)) {
57
+ const current = packages.get(name)
58
+ if (!current) {
59
+ packages.set(name, { name, entry: { ...entry }, suite: manifest.name, dir, file })
60
+ } else {
61
+ if (current.entry.version !== entry.version) {
62
+ errors.push(`包 ${name} 版本冲突: ${current.suite}=${current.entry.version} vs ${manifest.name}=${entry.version}`)
63
+ }
64
+ if (current.entry.role !== entry.role) {
65
+ errors.push(`包 ${name} role 冲突: ${current.suite}=${current.entry.role} vs ${manifest.name}=${entry.role}`)
66
+ }
67
+ if (current.entry.path && entry.path) {
68
+ const currentPath = resolve(current.dir, current.entry.path)
69
+ const nextPath = resolve(dir, entry.path)
70
+ if (currentPath !== nextPath) {
71
+ errors.push(`包 ${name} 路径冲突: ${current.suite}=${currentPath} vs ${manifest.name}=${nextPath}`)
72
+ }
73
+ }
74
+ for (const [dep, range] of Object.entries(entry.requires || {})) {
75
+ if (current.entry.requires?.[dep] && current.entry.requires[dep] !== range) {
76
+ errors.push(`包 ${name} 对 ${dep} 的 requires 冲突`)
77
+ }
78
+ current.entry.requires = { ...(current.entry.requires || {}), [dep]: range }
79
+ }
80
+ mergeProvides(current.entry.provides ||= {}, entry.provides)
81
+ }
82
+ for (const port of entry.provides?.ports || []) {
83
+ const owner = ports.get(port)
84
+ if (owner && owner !== name) errors.push(`端口 ${port} 冲突: ${owner} vs ${name}`)
85
+ else ports.set(port, name)
86
+ }
87
+ for (const tool of entry.provides?.tools || []) {
88
+ const owner = tools.get(tool)
89
+ if (owner && owner !== name) errors.push(`工具名 ${tool} 冲突: ${owner} vs ${name}`)
90
+ else tools.set(tool, name)
91
+ }
92
+ for (const [cap, version] of Object.entries(entry.provides?.capabilities || {})) {
93
+ const owner = capabilities.get(cap)
94
+ if (owner && !majorCompatible(owner.version, version)) {
95
+ errors.push(`能力 ${cap} 版本冲突: ${owner.package}=${owner.version} vs ${name}=${version}`)
96
+ } else if (!owner) {
97
+ capabilities.set(cap, { package: name, version })
98
+ }
99
+ }
100
+ }
101
+
102
+ for (const row of manifest.rows) {
103
+ const current = rows.get(row.id)
104
+ if (!current) {
105
+ rows.set(row.id, { row: { ...row }, suite: manifest.name })
106
+ continue
107
+ }
108
+ const same = current.row.name === row.name
109
+ && current.row.disabled === row.disabled
110
+ && deepEqual(current.row.config, row.config)
111
+ if (same) continue
112
+ if (options.allowOverride) {
113
+ warnings.push(`row ${row.id} 被 ${manifest.name} 覆盖(原 ${current.suite})`)
114
+ rows.set(row.id, { row: { ...row }, suite: manifest.name })
115
+ } else {
116
+ errors.push(`row ${row.id} 冲突: ${current.suite} 与 ${manifest.name} 定义了不同的 name/config`)
117
+ }
118
+ }
119
+
120
+ for (const check of manifest.checks || []) {
121
+ const current = checks.get(check.id)
122
+ if (!current) checks.set(check.id, { check: { ...check }, suite: manifest.name })
123
+ else if (deepEqual(current.check, check)) continue
124
+ else errors.push(`check ${check.id} 冲突: ${current.suite} vs ${manifest.name}`)
125
+ }
126
+ }
127
+
128
+ /* requires 必须能在组合里解析,或由调用方声明 external。 */
129
+ for (const { name, entry, suite } of packages.values()) {
130
+ for (const dep of Object.keys(entry.requires || {})) {
131
+ if (dep === 'capabilities') {
132
+ for (const [cap, range] of Object.entries(entry.requires.capabilities)) {
133
+ const provider = capabilities.get(cap)
134
+ if (!provider) {
135
+ errors.push(`${suite}: 包 ${name} 需要能力 ${cap}@${range},但组合里没有提供者`)
136
+ } else if (!majorCompatible(provider.version, range)) {
137
+ errors.push(`${suite}: 包 ${name} 需要能力 ${cap}@${range},提供者 ${provider.package}@${provider.version} 不兼容`)
138
+ }
139
+ }
140
+ } else if (!packages.has(dep)) {
141
+ warnings.push(`${suite}: 包 ${name} 依赖 ${dep},但组合里没有声明该包(按外部已安装处理)`)
142
+ }
143
+ }
144
+ }
145
+
146
+ /* 不同包的 wildcard 工具面重叠只告警,精确重名已经报错。 */
147
+ const wildcardOwners = [...packages.values()]
148
+ .filter(({ entry }) => (entry.provides?.tools || []).some((tool) => tool.includes('*')))
149
+ .map(({ name }) => name)
150
+ if (wildcardOwners.length > 1) {
151
+ warnings.push(`多个包声明通配工具面: ${wildcardOwners.join(', ')}(请确认 MCP serverName 不冲突)`)
152
+ }
153
+
154
+ return {
155
+ ok: errors.length === 0,
156
+ errors,
157
+ warnings,
158
+ packages: [...packages.values()].sort((a, b) => a.name.localeCompare(b.name)),
159
+ rows: [...rows.values()].map(({ row, suite }) => ({ ...row, _suite: suite })),
160
+ checks: [...checks.values()].map(({ check, suite }) => ({ ...check, _suite: suite })),
161
+ capabilities: [...capabilities.entries()].map(([capability, info]) => ({ capability, ...info })),
162
+ }
163
+ }
164
+
165
+ /** 生成 cordis.patch.yml(YAML;config 用 JSON 内联,避免 YAML 引号坑)。 */
166
+ export function renderCordisPatch(rows, { header = true } = {}) {
167
+ const lines = []
168
+ if (header) {
169
+ lines.push('# 由 @capyclaw/suite-kit 生成;改 dsh-suite.json 后重跑 compose。', '')
170
+ }
171
+ lines.push('- insert:')
172
+ for (const row of rows) {
173
+ lines.push(` - id: ${row.id}`)
174
+ lines.push(` name: ${JSON.stringify(row.name)}`)
175
+ if (row.disabled !== undefined) lines.push(` disabled: ${row.disabled ? 'true' : 'false'}`)
176
+ if (row.config !== undefined) lines.push(` config: ${JSON.stringify(row.config)}`)
177
+ }
178
+ return lines.join('\n') + '\n'
179
+ }
180
+
181
+ export function composeToDir(suites, outDir) {
182
+ const result = composeSuites(suites)
183
+ mkdirSync(outDir, { recursive: true })
184
+ if (result.ok) writeFileSync(join(outDir, 'cordis.patch.yml'), renderCordisPatch(result.rows))
185
+ writeFileSync(join(outDir, 'suite-compose.json'), JSON.stringify(result, null, 2) + '\n')
186
+ return result
187
+ }
188
+
189
+ /** 版本范围兼容:优先用精确版本对 range 求解,无法判断时退回 major 比较。 */
190
+ export function majorCompatible(left, right) {
191
+ const a = String(left || '').trim()
192
+ const b = String(right || '').trim()
193
+ if (a === '*' || b === '*' || a === 'latest' || b === 'latest') return true
194
+ if (!isValidRange(a) || !isValidRange(b)) return false
195
+ const exact = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
196
+ if (exact.test(a) && !exact.test(b)) return versionSatisfies(b, a)
197
+ if (exact.test(b) && !exact.test(a)) return versionSatisfies(a, b)
198
+ const majorA = majorOf(a)
199
+ const majorB = majorOf(b)
200
+ return majorA != null && majorB != null && majorA === majorB
201
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Domain Pack:面向“某个工作领域”的组合入口。
3
+ *
4
+ * component = 一个可独立安装的 suite(内部可以再包含 plugin / skills / MCP)
5
+ * domain = 选择哪些 component 一起启动,以及 base profile / 端口 / 检查
6
+ *
7
+ * 启动时只为该 domain 生成 profile:base + web-app + 选中的 suite;
8
+ * 未选中的插件、skill、MCP 不会进入该 profile。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { composeSuites } from './compose.mjs'
13
+ import { loadSuiteManifest } from './manifest.mjs'
14
+
15
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
16
+ const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
17
+ export const DOMAIN_FILENAMES = ['dsh-domain.json', 'domain.json']
18
+
19
+ export function findDomainManifest(input) {
20
+ const abs = path.resolve(input)
21
+ if (!fs.existsSync(abs)) throw new Error(`domain 路径不存在: ${abs}`)
22
+ if (fs.statSync(abs).isFile()) return abs
23
+ for (const name of DOMAIN_FILENAMES) {
24
+ const file = path.join(abs, name)
25
+ if (fs.existsSync(file)) return file
26
+ }
27
+ throw new Error(`目录里没有 ${DOMAIN_FILENAMES.join(' / ')}: ${abs}`)
28
+ }
29
+
30
+ export function loadDomainManifest(input) {
31
+ const file = findDomainManifest(input)
32
+ return { file, dir: path.dirname(file), manifest: JSON.parse(fs.readFileSync(file, 'utf8')) }
33
+ }
34
+
35
+ export function validateDomainManifest(manifest) {
36
+ const errors = []
37
+ const warnings = []
38
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
39
+ return { ok: false, errors: ['domain manifest 必须是 object'], warnings }
40
+ }
41
+ if (!NAME_RE.test(manifest.name || '')) errors.push('name 必须是 kebab-case')
42
+ if (!VERSION_RE.test(manifest.version || '')) errors.push('version 必须是 semver')
43
+ if (!Array.isArray(manifest.components) || manifest.components.length === 0) {
44
+ errors.push('components 必须是非空数组')
45
+ } else for (const component of manifest.components) {
46
+ if (typeof component !== 'string' || !component) errors.push('components 必须是路径字符串数组')
47
+ }
48
+ if (manifest.baseBundles != null && (!Array.isArray(manifest.baseBundles) || manifest.baseBundles.some((v) => typeof v !== 'string'))) {
49
+ errors.push('baseBundles 必须是 string[]')
50
+ }
51
+ if (manifest.profile != null && (typeof manifest.profile !== 'object' || Array.isArray(manifest.profile))) {
52
+ errors.push('profile 必须是 object')
53
+ }
54
+ if (manifest.runtime != null) {
55
+ if (typeof manifest.runtime !== 'object' || Array.isArray(manifest.runtime)) {
56
+ errors.push('runtime 必须是 object')
57
+ } else {
58
+ if (manifest.runtime.driver != null && !['node', 'jobobject', 'docker', 'wsl'].includes(manifest.runtime.driver)) {
59
+ errors.push(`runtime.driver 非法: ${manifest.runtime.driver}`)
60
+ }
61
+ for (const key of ['requires', 'scope']) {
62
+ if (manifest.runtime[key] != null && (typeof manifest.runtime[key] !== 'object' || Array.isArray(manifest.runtime[key]))) {
63
+ errors.push(`runtime.${key} 必须是 object`)
64
+ }
65
+ }
66
+ if (manifest.runtime.bindings != null) {
67
+ if (!Array.isArray(manifest.runtime.bindings)) errors.push('runtime.bindings 必须是数组')
68
+ else for (const [index, binding] of manifest.runtime.bindings.entries()) {
69
+ if (!binding || typeof binding !== 'object' || (!binding.row && !binding.package)) {
70
+ errors.push(`runtime.bindings[${index}] 必须包含 row 或 package`)
71
+ }
72
+ }
73
+ }
74
+ for (const key of ['tools', 'services', 'capabilities']) {
75
+ const list = manifest.runtime.requires?.[key]
76
+ if (list != null && (!Array.isArray(list) || list.some((item) => typeof item !== 'string'))) {
77
+ errors.push(`runtime.requires.${key} 必须是 string[]`)
78
+ }
79
+ }
80
+ const scope = manifest.runtime.scope
81
+ if (scope != null) {
82
+ if (scope.sessions != null && (typeof scope.sessions !== 'object' || Array.isArray(scope.sessions))) {
83
+ errors.push('runtime.scope.sessions 必须是 object')
84
+ }
85
+ if (scope.files != null) {
86
+ if (!Array.isArray(scope.files)) errors.push('runtime.scope.files 必须是数组')
87
+ else for (const [index, entry] of scope.files.entries()) {
88
+ if (!entry || typeof entry !== 'object' || typeof entry.path !== 'string' || !entry.path) {
89
+ errors.push(`runtime.scope.files[${index}].path 必须是非空字符串`)
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
96
+ for (const key of ['removeRows', 'removeDependencies']) {
97
+ if (manifest[key] != null && (!Array.isArray(manifest[key]) || manifest[key].some((v) => typeof v !== 'string'))) {
98
+ errors.push(`${key} 必须是 string[]`)
99
+ }
100
+ }
101
+ if (manifest.rowOverrides != null) {
102
+ if (typeof manifest.rowOverrides !== 'object' || Array.isArray(manifest.rowOverrides)) {
103
+ errors.push('rowOverrides 必须是 object')
104
+ } else for (const [id, override] of Object.entries(manifest.rowOverrides)) {
105
+ if (!override || typeof override !== 'object' || Array.isArray(override)) {
106
+ errors.push(`rowOverrides.${id} 必须是 object`)
107
+ } else if (override.config != null && (typeof override.config !== 'object' || Array.isArray(override.config))) {
108
+ errors.push(`rowOverrides.${id}.config 必须是 object`)
109
+ }
110
+ }
111
+ }
112
+ return { ok: errors.length === 0, errors, warnings }
113
+ }
114
+
115
+ /** 解析 domain → suites → 组合结果。 */
116
+ export function resolveDomain(input) {
117
+ const loaded = loadDomainManifest(input)
118
+ const validation = validateDomainManifest(loaded.manifest)
119
+ if (!validation.ok) throw new Error(`domain 校验失败:\n- ${validation.errors.join('\n- ')}`)
120
+ const suites = loaded.manifest.components.map((component) => {
121
+ const target = path.isAbsolute(component) ? component : path.resolve(loaded.dir, component)
122
+ return loadSuiteManifest(target)
123
+ })
124
+ const composed = composeSuites(suites)
125
+ if (!composed.ok) throw new Error(`domain 组合冲突:\n- ${composed.errors.join('\n- ')}`)
126
+ const overrides = loaded.manifest.rowOverrides || {}
127
+ const rows = composed.rows.map((row) => {
128
+ const override = overrides[row.id]
129
+ if (!override) return row
130
+ return {
131
+ ...row,
132
+ ...override,
133
+ config: override.config !== undefined ? override.config : row.config,
134
+ }
135
+ })
136
+ return { ...loaded, suites, composed: { ...composed, rows } }
137
+ }
138
+
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 嵌入握手协议(docs/suite-interop-standard.md §C.7 双模呈现)。
3
+ *
4
+ * 双模能力:套件既能独立运行(完整 app),也能作为浏览器壳内的子窗口被高层 AI 编排。
5
+ * 关键拆分:控制面不分模式——高层 AI 始终走同一套能力描述符/工具(ppt_export_pptx 同一接口);
6
+ * 模式只是呈现层状态。本模块只定义呈现层的握手与事件转发,不承载控制指令。
7
+ *
8
+ * 子窗口是同源本地地址(workbench 挂 /capyclaw/<ns>),iframe 自有套件不受 X-Frame-Options 限制
9
+ * (那只挡外站)。握手:父窗开子窗传 mode=embedded + sessionId/workId;子窗隐藏 standalone chrome、
10
+ * 报 ready、经 bridge 把产物/确认闸事件转发父窗。
11
+ */
12
+
13
+ export const EMBED_PROTOCOL_VERSION = 1
14
+ export const EMBED_MESSAGE_TYPES = Object.freeze({
15
+ init: 'capyclaw:embed:init',
16
+ ready: 'capyclaw:embed:ready',
17
+ event: 'capyclaw:embed:event',
18
+ })
19
+ export const EMBED_EVENT_KINDS = Object.freeze(['progress', 'artifact', 'confirm', 'login', 'result', 'error'])
20
+
21
+ /** 只信本地同源(127.0.0.1 / localhost),拒绝任意外部 origin 注入握手。 */
22
+ export function isLocalOrigin(origin) {
23
+ return typeof origin === 'string' && /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin)
24
+ }
25
+
26
+ /** 父 → 子:打开子窗口时下发嵌入上下文。 */
27
+ export function makeInitMessage({ sessionId, workId = null, parentOrigin, embedPath = null } = {}) {
28
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('makeInitMessage: sessionId 必填')
29
+ if (!isLocalOrigin(parentOrigin)) throw new Error('makeInitMessage: parentOrigin 必须是本地同源(127.0.0.1/localhost)')
30
+ return Object.freeze({
31
+ type: EMBED_MESSAGE_TYPES.init, protocolVersion: EMBED_PROTOCOL_VERSION,
32
+ mode: 'embedded', sessionId, workId, parentOrigin, embedPath,
33
+ })
34
+ }
35
+
36
+ /** 子 → 父:子窗就绪(已隐藏 standalone chrome,可被编排)。 */
37
+ export function makeReadyMessage({ suite, embedPath, workId = null } = {}) {
38
+ if (typeof suite !== 'string' || !suite) throw new Error('makeReadyMessage: suite 必填')
39
+ if (typeof embedPath !== 'string' || !embedPath.startsWith('/')) throw new Error('makeReadyMessage: embedPath 必须以 / 开头')
40
+ return Object.freeze({
41
+ type: EMBED_MESSAGE_TYPES.ready, protocolVersion: EMBED_PROTOCOL_VERSION,
42
+ suite, embedPath, workId,
43
+ })
44
+ }
45
+
46
+ /** 子 → 父:把统一事件(产物/确认闸/登录/进度)转发给父窗会话视图。 */
47
+ export function makeEventMessage({ event } = {}) {
48
+ if (!event || !EMBED_EVENT_KINDS.includes(event.kind)) {
49
+ throw new Error(`makeEventMessage: event.kind 必须是 ${EMBED_EVENT_KINDS.join('|')}`)
50
+ }
51
+ return Object.freeze({ type: EMBED_MESSAGE_TYPES.event, protocolVersion: EMBED_PROTOCOL_VERSION, event: Object.freeze({ ...event }) })
52
+ }
53
+
54
+ /**
55
+ * 校验一条握手消息。direction: 'to-child'(只收 init)| 'to-parent'(只收 ready/event)。
56
+ * 返回 {ok, errors};调用方还须自行核对 event.origin === 可信本地 origin(isLocalOrigin)。
57
+ */
58
+ export function validateEmbedMessage(msg, { direction } = {}) {
59
+ const errors = []
60
+ if (!msg || typeof msg !== 'object') return { ok: false, errors: ['消息不是对象'] }
61
+ if (msg.protocolVersion !== EMBED_PROTOCOL_VERSION) errors.push(`protocolVersion 必须是 ${EMBED_PROTOCOL_VERSION}`)
62
+ const allowed = direction === 'to-child'
63
+ ? [EMBED_MESSAGE_TYPES.init]
64
+ : direction === 'to-parent'
65
+ ? [EMBED_MESSAGE_TYPES.ready, EMBED_MESSAGE_TYPES.event]
66
+ : null
67
+ if (!allowed) errors.push(`direction 必须是 to-child|to-parent,收到: ${direction}`)
68
+ else if (!allowed.includes(msg.type)) errors.push(`${direction} 方向不接受消息类型 ${msg.type}`)
69
+ if (msg.type === EMBED_MESSAGE_TYPES.init) {
70
+ if (!msg.sessionId) errors.push('init 缺 sessionId')
71
+ if (!isLocalOrigin(msg.parentOrigin)) errors.push('init.parentOrigin 非本地同源')
72
+ }
73
+ if (msg.type === EMBED_MESSAGE_TYPES.ready) {
74
+ if (!msg.suite) errors.push('ready 缺 suite')
75
+ if (typeof msg.embedPath !== 'string' || !msg.embedPath.startsWith('/')) errors.push('ready.embedPath 必须以 / 开头')
76
+ }
77
+ if (msg.type === EMBED_MESSAGE_TYPES.event) {
78
+ if (!msg.event || !EMBED_EVENT_KINDS.includes(msg.event.kind)) errors.push('event.kind 非法')
79
+ }
80
+ return { ok: errors.length === 0, errors }
81
+ }