@capyclaw/capyclaw 0.0.0-stage → 0.2.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.
Files changed (81) hide show
  1. package/README.md +22 -2
  2. package/cordis.patch.yml +5 -0
  3. package/icon.svg +5 -0
  4. package/index.js +178 -0
  5. package/lib/environment.mjs +122 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/manifest.js +18 -0
  9. package/node_modules/@capyclaw/foundation/README.md +51 -0
  10. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  11. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  12. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  13. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  14. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  15. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  16. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  17. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  18. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  19. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  20. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  21. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  22. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  34. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  39. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  40. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  41. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  45. package/node_modules/@capyclaw/foundation/package.json +53 -0
  46. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  47. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  48. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  49. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  50. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  78. package/package.json +71 -4
  79. package/test/environment.test.mjs +68 -0
  80. package/test/package.test.mjs +24 -0
  81. package/test/plugin.test.mjs +101 -0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 宿主运行时入口:给 dsh 之外的宿主装配插件用。
3
+ *
4
+ * 适用:独立技能服务、构建工具、e2e 夹具。
5
+ * 不适用:应用插件。应用插件只允许 import `./abi` 与 `./kit`,
6
+ * 由准入闸(scripts/checks/check-foundation-only.mjs)强制。
7
+ *
8
+ * 宿主的职责与 dsh 相同:提供 ctx 里真实存在的服务,内核据此探测能力表。
9
+ */
10
+ export {
11
+ createKernel,
12
+ detectCapabilities,
13
+ BASE_CAPABILITIES,
14
+ KERNEL_VERSION,
15
+ ABI_VERSION,
16
+ } from '../lib/kernel.mjs'
17
+ export { assertHostContract } from '../lib/host/contract.mjs'
18
+ export { createMemoryHost } from '../lib/host/memory.mjs'
19
+ export { createDshHost } from '../lib/host/dsh.mjs'
20
+ export * from '../abi/index.mjs'
@@ -0,0 +1,100 @@
1
+ # 新插件稳定接入清单
2
+
3
+ > 新插件优先使用公共插件:`@capyclaw/service-host`、`@capyclaw/tool-host`、`@capyclaw/asset-service`、`@capyclaw/editor-host`。
4
+ > 本文件只描述底层 kit 的接入方式,供公共插件实现或旧插件维护使用。
5
+
6
+ ## 1. 包结构
7
+
8
+ ```text
9
+ my-plugin/
10
+ ├─ package.json # dsh.bundle.patch + dsh.suite(可选)
11
+ ├─ cordis.patch.yml # 只放插件行;不内联大段业务配置
12
+ ├─ lib/host.mjs # 只负责生命周期,不写业务
13
+ ├─ server/
14
+ │ ├─ relay.mjs # 路由/生命周期:/healthz /metrics /mcp
15
+ │ ├─ store.mjs # 业务状态(可扩展 JournalStore)
16
+ │ ├─ tools.mjs # 工具 schema + 分派
17
+ │ ├─ impl.mjs # 业务实现
18
+ │ └─ infra/ # 构建期从 @capyclaw/plugin-kit 拷贝的稳定快照
19
+ └─ editor/ # 浏览器端(可选)
20
+ ```
21
+
22
+ ## 2. 必须实现的基础协议
23
+
24
+ | 项 | 要求 |
25
+ |---|---|
26
+ | `GET /healthz` | `{ ok:true, name, version, contractVersion, uptimeSec, ...业务状态 }` |
27
+ | `GET /metrics` | Prometheus 文本;至少 `*_up`、`*_uptime_seconds` |
28
+ | `/mcp` | 使用 `createMcpHandler`,所有工具调用先 `validateToolArguments` |
29
+ | 绑定地址 | 只绑定 `127.0.0.1`,不要 `0.0.0.0` |
30
+ | 单实例 | 由 service-host 内置实例锁承担(锁文件/复用探测/残留接管一体);不要自建第二套 |
31
+ | 状态落盘 | 每次变更原子写;journal + checkpoint 可选但推荐 |
32
+ | 编辑器 | 显示即连接;心跳用 Worker;lease TTL 与心跳间隔匹配 |
33
+ | 关闭 | `server.close` + `closeAllConnections`,释放锁和 discovery 文件 |
34
+
35
+ ## 3. kit 快照
36
+
37
+ ```bash
38
+ node C/packages/capyclaw-plugin-kit/bin/sync.mjs --out <plugin>/server/infra --force
39
+ ```
40
+
41
+ 生成 `INFRA_MANIFEST.json`;插件导入示例:
42
+
43
+ ```js
44
+ import { listen, send, sendText, readBody } from './infra/service/http.mjs'
45
+ import { createMcpHandler } from './infra/service/mcp-http.mjs'
46
+ ```
47
+
48
+ ## 4. 工具接入
49
+
50
+ 1. 工具 schema 放在独立 `schema` 模块或 `tools.mjs`;
51
+ 2. 实现按领域分组(`impl-*.mjs`),由 `index.mjs` 汇合;
52
+ 3. 每个工具都有稳定的 name / inputSchema / 返回形状;
53
+ 4. 参数超限必须返回 `isError`,不能进入实现;
54
+ 5. 契约版本和工具清单通过一个只读 `*_capabilities` 工具暴露;
55
+ 6. 大参数工具必须在 schema 里限制 `maxItems` / `maxLength`。
56
+
57
+ ## 5. 技能接入
58
+
59
+ ```js
60
+ import { createSkillProvider } from '@capyclaw/plugin-kit/skills/provider'
61
+
62
+ const provider = createSkillProvider({
63
+ assetRoot,
64
+ skillDirs: ['my-router', 'my-edit'],
65
+ providerName: 'dsh-my-plugin',
66
+ contractRoot,
67
+ contractFile: 'my-contract.json',
68
+ })
69
+ ctx.skills.registerProvider(() => provider)
70
+ ```
71
+
72
+ 技能正文只写 instructions;运行时能力通过工具名/契约引用,不复制工具实现。
73
+
74
+ ## 6. 领域接入
75
+
76
+ - 用 `dsh-suite.json` 描述组件与能力;
77
+ - 用 `dsh-domain.json` 选择领域所需组件;
78
+ - 新插件先 `dsh-suite validate`,再 `dsh-domain stage`,最后 `dsh-domain launch`;
79
+ - 不要自定义 profile 结构,统一用 `@capyclaw/suite-kit` 生成。
80
+
81
+ ## 7. 稳定性验收
82
+
83
+ - `@capyclaw/plugin-kit` 单测通过;
84
+ - 插件自身契约测试通过;
85
+ - MCP E2E:capabilities / tools / 错误路径 / 恢复;
86
+ - 压测:并发读、并发写、非法参数、超大参数、截图/长任务;
87
+ - 进程重启后 `state.json` / journal / checkpoint 可恢复;
88
+ - 两个 profile 同时启动可复用 bridge 或使用独立端口。
89
+
90
+ ## 8. Runtime / Content Store 接入
91
+
92
+ - 插件启动时 `runtimeContextFromConfig(config)` 读取 `runtime.json`,拿
93
+ `ports.content`、`paths.contentState`、`store.root`、`store.token`;
94
+ - 用 `createRuntimeStoreClient(context)` 得到 scoped `WorkspaceClient`;
95
+ - 插件状态用 `WorkspaceBackend` 映射到对象仓库(state/journal/checkpoint);
96
+ - 不要硬编码任何固定端口(历史上有插件写死过,后来端口变了就全线连不上)、`~/.dsh-ppt-bridge` 或全局锁文件;
97
+ - `BlobStore` 只存对象;work 归属、版本 CAS、catalog 和生命周期由
98
+ `WorkspaceManager` 中间层负责;
99
+ - 多 runtime 同时运行时,每个 runtime 的 `harness` / `content` 端口和
100
+ namespace token 都不同,不能复用其他 runtime 的端口或 store token。
@@ -0,0 +1,70 @@
1
+ # @capyclaw/plugin-kit(插件底层协议库)
2
+
3
+ > 运行时公共服务已经拆到 `@capyclaw/service-host`、`@capyclaw/tool-host`、`@capyclaw/asset-service`、`@capyclaw/editor-host`。
4
+ > 新插件优先使用这些公共插件(`ctx.*`),或用 `@capyclaw/*` 包直接 import;`server/shared/` 只是零拷贝转发,不要当作快照副本。
5
+ > 本包只保留纯函数/传输/存储算法,供公共插件和旧插件使用。
6
+
7
+ 后续插件不要各自重复实现这些机制。按本包的接口接入,PPT 只是第一个消费者,新的 `plugin-development` 脚手架是第二个消费者。
8
+
9
+ ## 提供什么
10
+
11
+ | 模块 | 能力 |
12
+ |---|---|
13
+ | `service/http` | 安全响应头、JSON/text 响应、body 上限、query 解析、loopback 监听(可挂 handler) |
14
+ | `service/mcp-http` | 通用 MCP Streamable HTTP 处理器(initialize/ping/tools/list/tools/call) |
15
+ | `tools/validate` | inputSchema 子集校验(required/type/enum/maxLength/maxItems/additionalProperties) |
16
+ | `skills/provider` | 扫描 `skills/*/SKILL.md`,按需加载,自动 frontmatter 校验 |
17
+ | `editor/transport` | 浏览器 → 本机服务的 fetch/JSON 封装 |
18
+ | `editor/lease` | “显示即连接”的编辑器租约与自动挂接 |
19
+ | `editor/heartbeat-worker.js` | 不受标签页节流的心跳 Worker |
20
+ | `store/journal-store` | 原子 JSON 状态、append-only journal、命名 checkpoint |
21
+ | `store/blob-store` | 纯内容仓库:按 sha256 存不可变对象,不关心文件关系 |
22
+ | `workspace/manager` | 中间层:work manifest、文件归属、版本 CAS、catalog、生命周期 |
23
+ | `runtime/context` | 读取当前 runtime 的端口、目录、namespace,并创建 scoped WorkspaceClient |
24
+
25
+ ## 职责边界
26
+
27
+ - 编排中间层在 `@capyclaw/suite-kit`:打包插件、分配端口、创建 runtime、校验
28
+ `requires`、声明 work 的文件范围、维护 catalog 和生命周期。
29
+ - `BlobStore` 只接收字节,按内容 hash 存储;它不知道文件名、作品、runtime。
30
+ - `WorkspaceManager` 是中间层的 workspace 实现:解释“哪些对象属于同一个 work、
31
+ 谁能改、版本是多少”,并把可展示的目录写到 `catalog/works.json`。
32
+ - 插件通过 `WorkspaceClient` 访问自己的 namespace;新文件自动进入当前 work
33
+ 的 manifest,不会串到别的 runtime。
34
+ - `WorkspaceBackend` 把 state/journal/checkpoint 映射到对象仓库;可选 `journalPath` 把 append-only journal 写到 runtime 自己的 logs,避免 O(n²) 对象重写。PPT 已接入。
35
+
36
+ ## 使用方式
37
+
38
+ ```js
39
+ import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/http'
40
+ import { createMcpHandler } from '@capyclaw/plugin-kit/service/mcp-http'
41
+ import { createSkillProvider } from '@capyclaw/plugin-kit/skills/provider'
42
+ import { createEditorLease } from '@capyclaw/plugin-kit/editor/lease'
43
+ import { JournalStore } from '@capyclaw/plugin-kit/store/journal-store'
44
+ import { BlobStore, WorkspaceManager, WorkspaceClient, WorkspaceBackend } from '@capyclaw/plugin-kit'
45
+ import { runtimeContextFromConfig, createRuntimeStoreClient } from '@capyclaw/plugin-kit/runtime/context'
46
+ ```
47
+
48
+ 本地插件包可以在构建期把 kit 源码快照进自己的包(`server/infra/`),这样插件仍然可以独立分发:
49
+
50
+ ```bash
51
+ node C/packages/capyclaw-plugin-kit/bin/sync.mjs --out <plugin>/server/infra --force
52
+ ```
53
+
54
+ 快照会写 `INFRA_MANIFEST.json`(版本、hash、文件清单),升级 kit 后重新同步并提交。
55
+
56
+ ## 兼容性契约
57
+
58
+ - kit minor 版本只新增导出,不改变已有函数签名;
59
+ - breaking change 必须 major;
60
+ - 插件包应锁定 kit 的精确版本/快照,不要跨 major 混用;
61
+ - 任何插件暴露的 `/healthz` 至少返回 `{ ok, version, contractVersion }`;
62
+ - 任何插件暴露的 `/metrics` 使用稳定的指标名;
63
+ - 任何 MCP 工具调用前必须经过 `validateToolArguments`。
64
+
65
+ ## 测试
66
+
67
+ ```bash
68
+ cd C/packages/capyclaw-plugin-kit
69
+ npm test
70
+ ```
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 把 @capyclaw/plugin-kit 源码快照到插件包的 server/infra/。
4
+ *
5
+ * 用法:
6
+ * node packages/@capyclaw/plugin-kit/bin/sync.mjs --out <plugin>/server/infra
7
+ * node packages/@capyclaw/plugin-kit/bin/sync.mjs --out <plugin>/server/infra --force
8
+ */
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { createHash } from 'node:crypto'
13
+
14
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
15
+ const KIT_ROOT = path.resolve(HERE, '..')
16
+ const KIT_SRC = path.join(KIT_ROOT, 'src')
17
+
18
+ function parseArgs(argv) {
19
+ const options = { out: '', force: false }
20
+ for (let i = 0; i < argv.length; i++) {
21
+ const arg = argv[i]
22
+ if (arg === '--out' || arg === '-o') options.out = argv[++i]
23
+ else if (arg.startsWith('--out=')) options.out = arg.slice('--out='.length)
24
+ else if (arg === '--force' || arg === '-f') options.force = true
25
+ else if (arg === '--help' || arg === '-h') options.help = true
26
+ else throw new Error(`未知参数: ${arg}`)
27
+ }
28
+ return options
29
+ }
30
+
31
+ function listFiles(dir, base = dir) {
32
+ const out = []
33
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
34
+ const full = path.join(dir, entry.name)
35
+ if (entry.isDirectory()) out.push(...listFiles(full, base))
36
+ else if (entry.isFile()) out.push(path.relative(base, full).replace(/\\/g, '/'))
37
+ }
38
+ return out.sort()
39
+ }
40
+
41
+ function hashFiles(root, files) {
42
+ const hash = createHash('sha256')
43
+ for (const file of files) {
44
+ hash.update(file)
45
+ hash.update(fs.readFileSync(path.join(root, file)))
46
+ }
47
+ return hash.digest('hex')
48
+ }
49
+
50
+ export function syncKit({ outDir, force = false } = {}) {
51
+ if (!outDir) throw new Error('syncKit: outDir 必填')
52
+ const target = path.resolve(outDir)
53
+ if (fs.existsSync(target)) {
54
+ const entries = fs.readdirSync(target)
55
+ if (!force && entries.length > 0 && !entries.includes('INFRA_MANIFEST.json')) {
56
+ throw new Error(`目标目录非空且不是 kit 快照: ${target}(使用 --force 覆盖)`)
57
+ }
58
+ fs.rmSync(target, { recursive: true, force: true })
59
+ }
60
+
61
+ const pkg = JSON.parse(fs.readFileSync(path.join(KIT_ROOT, 'package.json'), 'utf8'))
62
+ const files = listFiles(KIT_SRC)
63
+ fs.mkdirSync(target, { recursive: true })
64
+ for (const file of files) {
65
+ const dest = path.join(target, file)
66
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
67
+ fs.copyFileSync(path.join(KIT_SRC, file), dest)
68
+ }
69
+
70
+ const manifest = {
71
+ name: pkg.name,
72
+ version: pkg.version,
73
+ source: 'packages/@capyclaw/plugin-kit/src',
74
+ syncedAt: new Date().toISOString(),
75
+ hash: hashFiles(KIT_SRC, files),
76
+ files,
77
+ }
78
+ fs.writeFileSync(path.join(target, 'INFRA_MANIFEST.json'), JSON.stringify(manifest, null, 2) + '\n')
79
+ return { target, manifest }
80
+ }
81
+
82
+ function main() {
83
+ let options
84
+ try {
85
+ options = parseArgs(process.argv.slice(2))
86
+ } catch (error) {
87
+ console.error(`✗ ${error.message}`)
88
+ process.exit(1)
89
+ }
90
+ if (options.help || !options.out) {
91
+ console.log('用法: node packages/@capyclaw/plugin-kit/bin/sync.mjs --out <plugin>/server/infra [--force]')
92
+ process.exit(options.help ? 0 : 1)
93
+ }
94
+ try {
95
+ const result = syncKit({ outDir: options.out, force: options.force })
96
+ console.log(`✓ kit ${result.manifest.version} 已同步到 ${result.target}(${result.manifest.files.length} 个文件)`)
97
+ } catch (error) {
98
+ console.error(`✗ ${error.message}`)
99
+ process.exit(1)
100
+ }
101
+ }
102
+
103
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main()
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@capyclaw/plugin-kit",
3
+ "version": "0.2.7",
4
+ "description": "DSH 插件基础设施标准件:HTTP/MCP、单实例锁、参数校验、技能 provider、journal 存储、编辑器传输与租约。",
5
+ "type": "module",
6
+ "main": "./src/index.mjs",
7
+ "exports": {
8
+ ".": "./src/index.mjs",
9
+ "./service/http": "./src/service/http.mjs",
10
+ "./service/mcp-http": "./src/service/mcp-http.mjs",
11
+ "./service/server": "./src/service/server.mjs",
12
+ "./service/api": "./src/service/api.mjs",
13
+ "./service/static": "./src/service/static.mjs",
14
+ "./tools/validate": "./src/tools/validate.mjs",
15
+ "./tools/result": "./src/tools/result.mjs",
16
+ "./skills/provider": "./src/skills/provider.mjs",
17
+ "./editor/transport": "./src/editor/transport.js",
18
+ "./editor/lease": "./src/editor/lease.mjs",
19
+ "./editor/heartbeat": "./src/editor/heartbeat.mjs",
20
+ "./editor/shadow": "./src/editor/shadow.mjs",
21
+ "./store/journal-store": "./src/store/journal-store.mjs",
22
+ "./store/blob-store": "./src/store/blob-store.mjs",
23
+ "./store/content-store": "./src/store/content-store.mjs",
24
+ "./workspace/manager": "./src/workspace/manager.mjs",
25
+ "./runtime/context": "./src/runtime/context.mjs",
26
+ "./packaging/pack": "./src/pack.mjs",
27
+ "./packaging/zip": "./src/zip.mjs",
28
+ "./packaging/self-contained": "./src/self-contained.mjs",
29
+ "./cli": "./src/cli.mjs",
30
+ "./package.json": "./package.json",
31
+ "./config": "./src/config.mjs",
32
+ "./tuning": "./src/tuning.mjs",
33
+ "./util/fs-lock": "./src/util/fs-lock.mjs",
34
+ "./util/http": "./src/util/http.mjs",
35
+ "./editor/heartbeat-worker": "./src/editor/heartbeat-worker.js"
36
+ },
37
+ "bin": {
38
+ "@capyclaw/plugin-kit-sync": "./bin/sync.mjs"
39
+ },
40
+ "files": [
41
+ "bin/",
42
+ "src/",
43
+ "README.md",
44
+ "INTEGRATION.md"
45
+ ],
46
+ "scripts": {
47
+ "test": "node --test \"test/*.test.mjs\""
48
+ },
49
+ "engines": {
50
+ "node": ">=18"
51
+ },
52
+ "license": "MIT",
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/Maple496/capyclaw.git",
59
+ "directory": "C/packages/capyclaw-plugin-kit"
60
+ },
61
+ "keywords": [
62
+ "dsh",
63
+ "dsh-plugin",
64
+ "cordis",
65
+ "plugin-sdk"
66
+ ],
67
+ "bugs": {
68
+ "url": "https://github.com/Maple496/capyclaw/issues"
69
+ },
70
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-plugin-kit#readme"
71
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * CLI 脚手架(纯函数,无副作用)。
3
+ *
4
+ * 全仓 8+ 个 bin 脚本各自手写参数解析/导入守卫/失败退出——这里收敛为一套:
5
+ * 新的 bin 只需要写「命令表 + 用法文本 + 业务逻辑」,解析与守卫交给本模块。
6
+ *
7
+ * import { parseArgs, isMain, fail } from '@capyclaw/plugin-kit'
8
+ *
9
+ * const commands = { async do(arg, flags) { … } }
10
+ * if (isMain(import.meta.url)) { … dispatch & print usage … }
11
+ */
12
+ import { resolve } from 'node:path'
13
+ import { pathToFileURL } from 'node:url'
14
+
15
+ /**
16
+ * 解析命令行:位置参数与 `--flag`/`--flag value` 混排。
17
+ * @param {string[]} argv - 不含 node 与脚本路径的原始参数
18
+ * @returns {{ positional: string[], flags: Record<string, string|boolean> }}
19
+ * `--flag value` → 字符串;`--flag`(后随缺失或另一个 -- 项)→ true;`--flag=x` → 字符串
20
+ */
21
+ export function parseArgs(argv) {
22
+ const positional = []
23
+ const flags = {}
24
+ for (let i = 0; i < argv.length; i++) {
25
+ const arg = argv[i]
26
+ if (arg.startsWith('--')) {
27
+ const eq = arg.indexOf('=')
28
+ if (eq > 2) {
29
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1)
30
+ continue
31
+ }
32
+ const key = arg.slice(2)
33
+ const next = argv[i + 1]
34
+ if (next !== undefined && !next.startsWith('--')) { flags[key] = next; i++ }
35
+ else flags[key] = true
36
+ } else {
37
+ positional.push(arg)
38
+ }
39
+ }
40
+ return { positional, flags }
41
+ }
42
+
43
+ /**
44
+ * 导入守卫:仅当本模块被直接执行(而非被测试/其他模块 import)时为 true。
45
+ * @param {string} importMetaUrl - 调用方的 import.meta.url
46
+ */
47
+ export function isMain(importMetaUrl, argv = process.argv) {
48
+ const entry = argv[1] ? pathToFileURL(resolve(argv[1])).href : ''
49
+ return importMetaUrl === entry
50
+ }
51
+
52
+ /** 统一失败出口:打印 ✗ 后以非零码退出。 */
53
+ export function fail(message) {
54
+ console.error(`✗ ${message}`)
55
+ process.exit(1)
56
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 插件配置解析(统一入口)。
3
+ *
4
+ * 目的:让插件不把端口/URL/路径写死在代码或 cordis.patch.yml 里,
5
+ * 而是遵循一条可预测的优先级链:
6
+ *
7
+ * ctx config(由 stack / profile patch 注入的运行时配置)
8
+ * → 环境变量(逐字段,如 DSH_LAUNCHPAD_PORT)
9
+ * → defaults(安全默认值)
10
+ *
11
+ * 所有取值都带上来源,便于 doctor / 日志说明「这个值是哪来的」。
12
+ *
13
+ * 用法:
14
+ * import { resolveConfig } from '@capyclaw/plugin-kit/config'
15
+ *
16
+ * export function apply(ctx, config = {}) {
17
+ * const cfg = resolveConfig(config, {
18
+ * envPrefix: 'DSH_PPT',
19
+ * 不写端口默认值:端口由基建的 runtime.json / env 注入(见 INTEGRATION.md)。
20
+ * defaults: { host: '127.0.0.1' },
21
+ * fields: {
22
+ * port: { env: 'PORT', type: 'port' },
23
+ * host: { env: 'HOST' },
24
+ * backendUrl: { env: 'BACKEND_URL', type: 'url' },
25
+ * },
26
+ * })
27
+ * cfg.value.port // 解析后的值
28
+ * cfg.source.port // 'config' | 'env:DSH_PPT_PORT' | 'default'
29
+ * }
30
+ */
31
+
32
+ const TYPE_CHECKS = {
33
+ port(value) {
34
+ const n = Number(value)
35
+ return Number.isInteger(n) && n > 0 && n < 65536 ? n : null
36
+ },
37
+ number(value) {
38
+ const n = Number(value)
39
+ return Number.isFinite(n) ? n : null
40
+ },
41
+ boolean(value) {
42
+ if (typeof value === 'boolean') return value
43
+ const s = String(value).trim().toLowerCase()
44
+ if (['1', 'true', 'yes', 'on'].includes(s)) return true
45
+ if (['0', 'false', 'no', 'off'].includes(s)) return false
46
+ return null
47
+ },
48
+ url(value) {
49
+ const s = String(value).trim()
50
+ try {
51
+ const u = new URL(s)
52
+ return u.protocol === 'http:' || u.protocol === 'https:' ? s : null
53
+ } catch {
54
+ return null
55
+ }
56
+ },
57
+ string(value) {
58
+ const s = String(value)
59
+ return s.length ? s : null
60
+ },
61
+ }
62
+
63
+ function coerce(raw, type) {
64
+ if (raw === undefined || raw === null || raw === '') return { ok: false }
65
+ const check = TYPE_CHECKS[type] || TYPE_CHECKS.string
66
+ const value = check(raw)
67
+ return value === null ? { ok: false } : { ok: true, value }
68
+ }
69
+
70
+ /**
71
+ * @param {object} config dsh 传给 apply() 的 config(来自 cordis.patch.yml / stack configs)
72
+ * @param {object} options
73
+ * @param {string} [options.envPrefix] 环境变量前缀,如 'DSH_PPT'
74
+ * @param {object} [options.defaults] 默认值表
75
+ * @param {object} [options.fields] { 字段名: { env?: string, type?: 'port'|'number'|'boolean'|'url'|'string' } }
76
+ * @param {(msg:string)=>void} [options.onInvalid] 无效值回调(默认收集到 issues)
77
+ * @returns {{ value: object, source: object, issues: string[] }}
78
+ */
79
+ export function resolveConfig(config = {}, options = {}) {
80
+ const { envPrefix = '', defaults = {}, fields = {}, env = process.env } = options
81
+ const value = {}
82
+ const source = {}
83
+ const issues = []
84
+
85
+ const keys = new Set([...Object.keys(defaults), ...Object.keys(fields)])
86
+
87
+ for (const key of keys) {
88
+ const field = fields[key] || {}
89
+ const type = field.type || inferType(defaults[key])
90
+ const envName = field.env
91
+ ? (envPrefix ? `${envPrefix}_${field.env}` : field.env)
92
+ : (envPrefix ? `${envPrefix}_${key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()}` : '')
93
+
94
+ // 1) ctx config
95
+ const fromConfig = coerce(config?.[key], type)
96
+ if (fromConfig.ok) {
97
+ value[key] = fromConfig.value
98
+ source[key] = 'config'
99
+ continue
100
+ }
101
+ if (config?.[key] !== undefined && config?.[key] !== null && config?.[key] !== '') {
102
+ issues.push(`${key}: config 值无效(期望 ${type}): ${JSON.stringify(config[key])},已降级到下一来源`)
103
+ }
104
+
105
+ // 2) 环境变量
106
+ if (envName && env?.[envName] !== undefined) {
107
+ const fromEnv = coerce(env[envName], type)
108
+ if (fromEnv.ok) {
109
+ value[key] = fromEnv.value
110
+ source[key] = `env:${envName}`
111
+ continue
112
+ }
113
+ issues.push(`${key}: 环境变量 ${envName} 值无效(期望 ${type}): ${JSON.stringify(env[envName])},已降级到默认值`)
114
+ }
115
+
116
+ // 3) 默认值
117
+ if (defaults[key] !== undefined) {
118
+ value[key] = defaults[key]
119
+ source[key] = 'default'
120
+ continue
121
+ }
122
+
123
+ // 无默认值且没解析到 → 不写入,交给调用方判断是否必填
124
+ source[key] = 'unset'
125
+ }
126
+
127
+ return { value, source, issues }
128
+ }
129
+
130
+ function inferType(sample) {
131
+ if (typeof sample === 'boolean') return 'boolean'
132
+ if (typeof sample === 'number') return 'number'
133
+ if (typeof sample === 'string' && /^https?:\/\//.test(sample)) return 'url'
134
+ return 'string'
135
+ }
136
+
137
+ /** 便于在 apply() 里打一条可读的配置来源日志。 */
138
+ export function describeConfig({ value, source }) {
139
+ return Object.entries(value)
140
+ .map(([k, v]) => `${k}=${JSON.stringify(v)} (${source[k] || 'unknown'})`)
141
+ .join(', ')
142
+ }