@twinsearth/dsh-fang 3.1.21 → 3.1.22

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 (113) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/src/compose.mjs +67 -0
  20. package/src/src/contract/client.js +86 -0
  21. package/src/src/contract/constants.js +79 -0
  22. package/src/src/contract/envelope.js +83 -0
  23. package/src/src/contract/index.js +19 -0
  24. package/src/src/contract/negotiate.js +106 -0
  25. package/src/src/contract/server.js +77 -0
  26. package/src/src/contract/transports.js +301 -0
  27. package/src/src/index.mjs +11 -0
  28. package/src/src/kernel/core.mjs +100 -0
  29. package/src/src/kernel/extensions.mjs +61 -0
  30. package/src/src/kernel/fsx.mjs +349 -0
  31. package/src/src/kernel/index.mjs +21 -0
  32. package/src/src/kernel/ledger.mjs +94 -0
  33. package/src/src/kernel/paths.mjs +182 -0
  34. package/src/src/kernel/role.mjs +68 -0
  35. package/src/src/kernel/rounds.mjs +172 -0
  36. package/src/src/kernel/schema.mjs +5 -0
  37. package/src/src/kernel/types.mjs +264 -0
  38. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  39. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  40. package/src/src/lib/adapter-client.mjs +383 -0
  41. package/src/src/lib/adapter-protocol.mjs +243 -0
  42. package/src/src/lib/ai-secret-store.mjs +202 -0
  43. package/src/src/lib/boot-guard.mjs +182 -0
  44. package/src/src/lib/branch-store.mjs +84 -0
  45. package/src/src/lib/branch.mjs +74 -0
  46. package/src/src/lib/bridge-client.mjs +133 -0
  47. package/src/src/lib/broker-adapter.mjs +67 -0
  48. package/src/src/lib/broker.mjs +45 -0
  49. package/src/src/lib/business-producers.mjs +109 -0
  50. package/src/src/lib/command-cache.mjs +209 -0
  51. package/src/src/lib/compat.mjs +170 -0
  52. package/src/src/lib/composer-journal.mjs +128 -0
  53. package/src/src/lib/container/index.mjs +806 -0
  54. package/src/src/lib/decision-events.mjs +129 -0
  55. package/src/src/lib/decision-ingest-client.mjs +41 -0
  56. package/src/src/lib/decision-outbox.mjs +129 -0
  57. package/src/src/lib/default-essence.mjs +61 -0
  58. package/src/src/lib/desktop-launch.mjs +138 -0
  59. package/src/src/lib/essence.mjs +1211 -0
  60. package/src/src/lib/fork-client.mjs +410 -0
  61. package/src/src/lib/fork-config-lock.mjs +153 -0
  62. package/src/src/lib/fork-seed.mjs +304 -0
  63. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  64. package/src/src/lib/fork-supervisor.mjs +122 -0
  65. package/src/src/lib/fs-guard.mjs +28 -0
  66. package/src/src/lib/http-auth.mjs +162 -0
  67. package/src/src/lib/idle-audit.mjs +178 -0
  68. package/src/src/lib/interaction-poke.mjs +61 -0
  69. package/src/src/lib/mirror-etag.mjs +92 -0
  70. package/src/src/lib/mirror-official-source.mjs +93 -0
  71. package/src/src/lib/mirror.mjs +478 -0
  72. package/src/src/lib/mother-link.mjs +156 -0
  73. package/src/src/lib/mutex.mjs +31 -0
  74. package/src/src/lib/permissions.mjs +115 -0
  75. package/src/src/lib/pnpm-store.mjs +189 -0
  76. package/src/src/lib/preferences.mjs +212 -0
  77. package/src/src/lib/producer-contract.mjs +162 -0
  78. package/src/src/lib/reflow.mjs +41 -0
  79. package/src/src/lib/remote.mjs +408 -0
  80. package/src/src/lib/restart-contract.mjs +650 -0
  81. package/src/src/lib/roots.mjs +30 -0
  82. package/src/src/lib/rule-registry.mjs +1101 -0
  83. package/src/src/lib/runtime-capture.mjs +307 -0
  84. package/src/src/lib/semaphore.mjs +34 -0
  85. package/src/src/lib/session-bundle.mjs +138 -0
  86. package/src/src/lib/session-format.mjs +658 -0
  87. package/src/src/lib/sse-parser.mjs +102 -0
  88. package/src/src/lib/ssrf-guard.mjs +170 -0
  89. package/src/src/lib/status-store.mjs +257 -0
  90. package/src/src/lib/task-handle.mjs +622 -0
  91. package/src/src/lib/ui-actions.mjs +55 -0
  92. package/src/src/lib/umbrella.mjs +1661 -0
  93. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  94. package/src/src/lib/upgrade-status.mjs +43 -0
  95. package/src/src/plugins/adapter.mjs +1468 -0
  96. package/src/src/plugins/approver.mjs +1210 -0
  97. package/src/src/plugins/auditor.mjs +330 -0
  98. package/src/src/plugins/buffer-keeper.mjs +522 -0
  99. package/src/src/plugins/decision-center.mjs +2265 -0
  100. package/src/src/plugins/forker.mjs +1594 -0
  101. package/src/src/plugins/healer.mjs +664 -0
  102. package/src/src/plugins/hot-reloader.mjs +274 -0
  103. package/src/src/plugins/imports.mjs +247 -0
  104. package/src/src/plugins/orchestrator.mjs +3806 -0
  105. package/src/src/plugins/restart-guard.mjs +948 -0
  106. package/src/src/plugins/router.mjs +714 -0
  107. package/src/src/plugins/scorer.mjs +624 -0
  108. package/src/src/plugins/session-bridge.mjs +166 -0
  109. package/src/src/plugins/session-catalog.mjs +771 -0
  110. package/src/src/plugins/session-router.mjs +125 -0
  111. package/src/src/plugins/session-sync.mjs +171 -0
  112. package/src/src/plugins/umbrella.mjs +419 -0
  113. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,115 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // dsh-Fang v3.0.4 — 三层产品形态的权限契约(fail-closed)。
3
+ //
4
+ // 母体版 Mirror:只有官方插件,不能开会话/任务;
5
+ // 原身版 Essence:可装第三方插件,不能开会话/任务;
6
+ // 分身版 Derived:不能装插件,可开会话/任务。
7
+ //
8
+ // 说明:真正的硬隔离靠“profile 里装不装对应插件”(第一道门);
9
+ // 本模块是宿主/Adapter 侧的第二道门(防止直连 API 绕过 UI)。
10
+
11
+ export const ENV_TYPE = Object.freeze({
12
+ MIRROR: 'mirror',
13
+ ESSENCE: 'essence',
14
+ DERIVED: 'derived',
15
+ })
16
+
17
+ export const ENV_TYPES = Object.freeze(Object.values(ENV_TYPE))
18
+
19
+ /** @type {Record<string, {installPlugins:boolean, openSessions:boolean}>} */
20
+ export const PERMISSION_RULES = Object.freeze({
21
+ mirror: Object.freeze({ installPlugins: false, openSessions: false }),
22
+ essence: Object.freeze({ installPlugins: true, openSessions: false }),
23
+ derived: Object.freeze({ installPlugins: false, openSessions: true }),
24
+ })
25
+
26
+ export const ACTION_GROUPS = Object.freeze({
27
+ installPlugins: Object.freeze(['plugin-install', 'plugin-uninstall', 'plugin-update', 'plugin-set']),
28
+ openSessions: Object.freeze(['session-create', 'task-enqueue', 'agent-run', 'chat-send']),
29
+ })
30
+
31
+ export const PERMISSION_DENIED = 'permission-denied'
32
+
33
+ /**
34
+ * 规范化环境类型;未知值一律视为 unknown(后续 fail-closed 拒绝)。
35
+ * @param {unknown} value
36
+ * @returns {'mirror'|'essence'|'derived'|'unknown'}
37
+ */
38
+ export function resolveEnvType(value) {
39
+ const text = String(value ?? '')
40
+ return ENV_TYPES.includes(text) ? text : 'unknown'
41
+ }
42
+
43
+ /**
44
+ * 检查某个动作在某环境下是否允许。
45
+ * 未知环境 / 未知动作 → 拒绝(fail-closed)。
46
+ * @param {unknown} envType
47
+ * @param {string} action
48
+ * @returns {{allowed:boolean, envType:string, action:string, code?:string, message?:string}}
49
+ */
50
+ export function checkPermission(envType, action) {
51
+ const env = resolveEnvType(envType)
52
+ const name = String(action ?? '')
53
+ const rule = PERMISSION_RULES[env]
54
+ if (rule === undefined) {
55
+ return {
56
+ allowed: false, envType: env, action: name, code: PERMISSION_DENIED,
57
+ message: `未知环境类型:${String(envType)}(fail-closed)`,
58
+ }
59
+ }
60
+ const group = Object.keys(ACTION_GROUPS).find(key => ACTION_GROUPS[key].includes(name))
61
+ if (group === undefined) {
62
+ return {
63
+ allowed: false, envType: env, action: name, code: PERMISSION_DENIED,
64
+ message: `未知动作:${name}(fail-closed)`,
65
+ }
66
+ }
67
+ if (rule[group] !== true) {
68
+ const label = group === 'installPlugins' ? '安装/修改插件' : '开启会话或任务'
69
+ const envLabel = { mirror: '母体版', essence: '原身版', derived: '分身版' }[env]
70
+ return {
71
+ allowed: false, envType: env, action: name, code: PERMISSION_DENIED,
72
+ message: `[权限拒绝] ${envLabel} 不支持${label}`,
73
+ }
74
+ }
75
+ return { allowed: true, envType: env, action: name }
76
+ }
77
+
78
+ /** 权限拒绝错误(Adapter/Guard 抛出用)。 */
79
+ export class PermissionDeniedError extends Error {
80
+ constructor(decision) {
81
+ super(decision?.message ?? 'permission denied')
82
+ this.name = 'PermissionDeniedError'
83
+ this.code = PERMISSION_DENIED
84
+ this.envType = decision?.envType ?? 'unknown'
85
+ this.action = decision?.action ?? ''
86
+ }
87
+ }
88
+
89
+ /**
90
+ * 创建一个绑定环境的守卫:返回 decision;`assert` 形式抛错。
91
+ * @param {unknown} envType
92
+ */
93
+ export function createEnvironmentGuard(envType) {
94
+ const env = resolveEnvType(envType)
95
+ const decide = (action) => checkPermission(env, action)
96
+ return {
97
+ envType: env,
98
+ can: (action) => decide(action).allowed,
99
+ check: decide,
100
+ assert(action) {
101
+ const decision = decide(action)
102
+ if (!decision.allowed) throw new PermissionDeniedError(decision)
103
+ return decision
104
+ },
105
+ }
106
+ }
107
+
108
+ /** 供 UI 展示的能力摘要。 */
109
+ export function describePermissions(envType) {
110
+ const env = resolveEnvType(envType)
111
+ const rule = PERMISSION_RULES[env]
112
+ return rule === undefined
113
+ ? { envType: env, installPlugins: false, openSessions: false, known: false }
114
+ : { envType: env, installPlugins: rule.installPlugins, openSessions: rule.openSessions, known: true }
115
+ }
@@ -0,0 +1,189 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang lib — pnpm settings for the essence runtime profile.
4
+ //
5
+ // DSH 0.2.2-rc.1 bundles pnpm 11, and pnpm 11 no longer reads non-auth settings
6
+ // (`store-dir`, `package-import-method`, …) from a project `.npmrc`: only auth and
7
+ // network keys are read from that file, the rest moved to `pnpm-workspace.yaml`
8
+ // (camelCase). Fang used to write only `.npmrc`, so every pnpm operation inside an
9
+ // essence runtime picked the per-drive default store (`D:\.pnpm-store\v11` on a D:
10
+ // project) while the module tree recorded the mother's C: store, and pnpm failed with
11
+ // [ERR_PNPM_UNEXPECTED_STORE] Unexpected store location ...
12
+ // Before removing/updating any plugin (v3.1.8 report).
13
+ //
14
+ // This module writes the settings in the form pnpm 11 actually reads, keeps the legacy
15
+ // `.npmrc` for older pnpm/npm, and aligns the modules manifest so pnpm's compatibility
16
+ // check accepts the shared module tree: the store must match and the virtual store must
17
+ // be this project's own `node_modules/.pnpm` (the copied manifest still named the
18
+ // mother's virtual store).
19
+ import fs from 'node:fs'
20
+ import path from 'node:path'
21
+
22
+ /** The project settings file pnpm 11 reads (non-auth settings). */
23
+ export const PNPM_WORKSPACE_FILE = 'pnpm-workspace.yaml'
24
+ /** Legacy npm/pnpm config file; still written for older toolchains. */
25
+ export const NPMRC_FILE = '.npmrc'
26
+ /** The modules manifest pnpm writes into `node_modules`. */
27
+ export const MODULES_MANIFEST_FILE = '.modules.yaml'
28
+
29
+ function readText(file, fallback = '') {
30
+ try { return fs.readFileSync(file, 'utf8') } catch { return fallback }
31
+ }
32
+
33
+ function readJson(file, fallback = null) {
34
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return fallback }
35
+ }
36
+
37
+ function writeText(file, text) {
38
+ fs.mkdirSync(path.dirname(file), { recursive: true })
39
+ fs.writeFileSync(file, text, 'utf8')
40
+ }
41
+
42
+ /**
43
+ * Read the store + virtual store recorded for a module tree.
44
+ * @param {string} modulesDir `node_modules` directory (its `.modules.yaml` is read).
45
+ * @returns {{storeDir:string, virtualStoreDir:string|null, layoutVersion:number|null, file:string}|null}
46
+ */
47
+ export function readModulesManifest(modulesDir) {
48
+ const file = path.join(String(modulesDir ?? ''), MODULES_MANIFEST_FILE)
49
+ const manifest = readJson(file, null)
50
+ if (!manifest || typeof manifest !== 'object') return null
51
+ return {
52
+ storeDir: typeof manifest.storeDir === 'string' ? manifest.storeDir : '',
53
+ virtualStoreDir: typeof manifest.virtualStoreDir === 'string' ? manifest.virtualStoreDir : null,
54
+ layoutVersion: Number.isFinite(manifest.layoutVersion) ? manifest.layoutVersion : null,
55
+ file,
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The linker an existing module tree was laid out with, from the profile that owns it.
61
+ * DSH's desktop profile declares `nodeLinker: hoisted`; a runtime profile cloned from it
62
+ * must keep the same linker or pnpm would want to rebuild the modules directory.
63
+ * @param {string} profileDir Profile directory whose pnpm-workspace.yaml is read.
64
+ * @param {string} [fallback='hoisted'] Value used when the file has no nodeLinker.
65
+ * @returns {string}
66
+ */
67
+ export function readNodeLinker(profileDir, fallback = 'hoisted') {
68
+ const text = readText(path.join(String(profileDir ?? ''), PNPM_WORKSPACE_FILE))
69
+ const match = /^nodeLinker:\s*([A-Za-z-]+)\s*$/m.exec(text)
70
+ return match ? match[1] : fallback
71
+ }
72
+
73
+ /**
74
+ * Upsert top-level keys in a pnpm settings YAML file, preserving every other line
75
+ * (settings, comments, order). The values written here are machine paths and simple
76
+ * scalars, so a line-oriented upsert is enough and keeps the file readable.
77
+ * @param {string} file pnpm-workspace.yaml path.
78
+ * @param {Record<string,string>} settings Keys to write (camelCase).
79
+ * @returns {string[]} Keys written.
80
+ */
81
+ export function upsertPnpmWorkspaceSettings(file, settings = {}) {
82
+ const entries = Object.entries(settings).filter(([, value]) => typeof value === 'string' && value !== '')
83
+ if (entries.length === 0) return []
84
+ const keys = new Set(entries.map(([key]) => key))
85
+ const original = readText(file)
86
+ const kept = original.split(/\r?\n/).filter((line) => {
87
+ const match = /^([A-Za-z][A-Za-z0-9_]*):/.exec(line)
88
+ return !(match && keys.has(match[1]))
89
+ })
90
+ const trimmed = kept.join('\n').replace(/[ \t]+$/gm, '').replace(/^\n+|\n+$/g, '')
91
+ const appended = entries.map(([key, value]) => `${key}: ${value}`).join('\n')
92
+ writeText(file, `${trimmed ? `${trimmed}\n` : ''}${appended}\n`)
93
+ return entries.map(([key]) => key)
94
+ }
95
+
96
+ /**
97
+ * Upsert legacy `.npmrc` keys. pnpm 11 ignores these, but npm and older pnpm honor
98
+ * them and the runtime profile may outlive a DSH downgrade.
99
+ * @param {string} profileDir Profile directory.
100
+ * @param {{storeDir:string, packageImportMethod:string}} options
101
+ * @returns {string[]}
102
+ */
103
+ export function upsertNpmrc(profileDir, { storeDir, packageImportMethod = 'copy' } = {}) {
104
+ const file = path.join(String(profileDir ?? ''), NPMRC_FILE)
105
+ const pairs = [
106
+ ['store-dir', storeDir],
107
+ ['package-import-method', packageImportMethod],
108
+ ].filter(([, value]) => typeof value === 'string' && value !== '')
109
+ if (pairs.length === 0) return []
110
+ const written = []
111
+ let text = readText(file)
112
+ for (const [key, value] of pairs) {
113
+ const re = new RegExp(`^${key}=.*$`, 'm')
114
+ if (re.test(text)) text = text.replace(re, `${key}=${value}`)
115
+ else text = `${text && !text.endsWith('\n') ? `${text}\n` : text}${key}=${value}\n`
116
+ written.push(key)
117
+ }
118
+ writeText(file, text.replace(/^\n+/, ''))
119
+ return written
120
+ }
121
+
122
+ /**
123
+ * Align a modules manifest with the store and virtual store pnpm will compute for this
124
+ * project. pnpm's `checkCompatibility` refuses a modules directory whose recorded store
125
+ * differs from the chosen store, or whose recorded `virtualStoreDir` differs from the
126
+ * project's own — the runtime tree was copied from the mother, so it names the mother's
127
+ * virtual store. Both become this project's values; the rest of the manifest is kept.
128
+ * @param {string} modulesDir `node_modules` directory.
129
+ * @param {{storeDir:string, virtualStoreDir:string}} options
130
+ * @returns {{changed:boolean, storeDir?:string, virtualStoreDir?:string, error?:string}}
131
+ */
132
+ export function patchModulesManifest(modulesDir, { storeDir, virtualStoreDir } = {}) {
133
+ const manifest = readModulesManifest(modulesDir)
134
+ if (!manifest) return { changed: false, error: 'modules-manifest-missing' }
135
+ if (!storeDir || !virtualStoreDir) return { changed: false, error: 'store-or-virtual-store-missing' }
136
+ const raw = readJson(manifest.file, null)
137
+ if (!raw) return { changed: false, error: 'modules-manifest-unreadable' }
138
+ const sameStore = raw.storeDir === storeDir
139
+ const sameVirtual = raw.virtualStoreDir === virtualStoreDir
140
+ if (sameStore && sameVirtual) return { changed: false, storeDir, virtualStoreDir }
141
+ raw.storeDir = storeDir
142
+ raw.virtualStoreDir = virtualStoreDir
143
+ writeText(manifest.file, `${JSON.stringify(raw, null, 2)}\n`)
144
+ return { changed: true, storeDir, virtualStoreDir }
145
+ }
146
+
147
+ /**
148
+ * Make an essence runtime profile's pnpm operations work off the shared module tree.
149
+ *
150
+ * Writes the settings pnpm 11 reads (`pnpm-workspace.yaml`), refreshes the legacy
151
+ * `.npmrc`, and aligns `node_modules/.modules.yaml` with the store and this project's
152
+ * virtual store. The store location is taken from the module tree's own manifest, so the
153
+ * chosen store always matches what the installed packages were linked from.
154
+ * @param {{profileDir:string, modulesDir:string, sourceModulesDir?:string, nodeLinker?:string}} options
155
+ * @returns {{ok:boolean, storeDir?:string, virtualStoreDir?:string, nodeLinker?:string, settings?:string[], npmrc?:string[], manifest?:object, error?:string}}
156
+ */
157
+ export function ensureEssenceRuntimePnpmConfig({ profileDir, modulesDir, sourceModulesDir = '', nodeLinker = 'hoisted' } = {}) {
158
+ const profile = String(profileDir ?? '')
159
+ const modules = String(modulesDir ?? '')
160
+ if (!profile || !modules) return { ok: false, error: 'profile-or-modules-missing' }
161
+ const source = String(sourceModulesDir ?? '') || modules
162
+ const manifest = readModulesManifest(source) ?? readModulesManifest(modules)
163
+ if (!manifest) return { ok: false, error: 'modules-manifest-missing' }
164
+ const storeDir = manifest.storeDir
165
+ if (!storeDir) return { ok: false, error: 'store-dir-unknown' }
166
+ const virtualStoreDir = path.join(modules, '.pnpm')
167
+ const settings = upsertPnpmWorkspaceSettings(path.join(profile, PNPM_WORKSPACE_FILE), {
168
+ nodeLinker,
169
+ storeDir,
170
+ packageImportMethod: 'copy',
171
+ // v3.1.11:元宝运行态是“用户显式更新插件”的交互场景,pnpm 11 默认的
172
+ // minimumReleaseAge(供应链观察期)会把刚发布的自家插件判为过新:
173
+ // ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION(3.1.10 / queue-journal 0.1.4 实测)。
174
+ // 母体的供应链策略不在这里改动;只在运行态关闭观察期,保证插件更新/卸载可用。
175
+ minimumReleaseAge: '0',
176
+ })
177
+ const npmrc = upsertNpmrc(profile, { storeDir, packageImportMethod: 'copy' })
178
+ const patched = patchModulesManifest(modules, { storeDir, virtualStoreDir })
179
+ return {
180
+ ok: patched.error === undefined,
181
+ storeDir,
182
+ virtualStoreDir,
183
+ nodeLinker,
184
+ settings,
185
+ npmrc,
186
+ manifest: patched,
187
+ ...(patched.error === undefined ? {} : { error: patched.error }),
188
+ }
189
+ }
@@ -0,0 +1,212 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // dsh-Fang v3.0.8 — schema 驱动的镜像偏好存储(零依赖)。
3
+ //
4
+ // 一个字段 = 一条 schema 描述符(kind/default/min/max/step/options/migrate);
5
+ // PreferencesStore 只做通用的“读文件 → 逐字段迁移+校验 → 补默认值 → 需要时写回”。
6
+ // 新增字段只改 PREFERENCES_SCHEMA;UI 可基于 schema 声明式渲染。
7
+ //
8
+ // 向后兼容:
9
+ // * 旧文件缺失的新字段自动补默认值并写回;
10
+ // * 旧值经 migrate/coerce 修正后写回,并报告 migrated 字段;
11
+ // * 未知字段被丢弃并报告 droppedUnknown;
12
+ // * 损坏 JSON 不覆盖原文件(保留证据),返回默认值。
13
+
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+
17
+ import { ensureDir, readJson, writeJsonAtomic } from '../kernel/index.mjs'
18
+ /** @typedef {{kind:'number', defaultValue:number, min:number, max:number, step:number, unit?:string, migrate?:Function}} NumberField */
19
+ /** @typedef {{kind:'enum', defaultValue:string, options:Array<{value:string,label:string}>, migrate?:Function}} EnumField */
20
+ /** @typedef {{kind:'boolean', defaultValue:boolean, migrate?:Function}} BooleanField */
21
+
22
+ export const PREFERENCES_SCHEMA = Object.freeze({
23
+ activeIdleTimeoutMs: Object.freeze({
24
+ kind: 'number', label: '对话框交互超时', unit: 'ms',
25
+ description: '无交互超过此时长后降低状态轮询频率',
26
+ defaultValue: 30_000, min: 5_000, max: 300_000, step: 5_000,
27
+ // 旧版本只接受 15/30/60s;其他值视为无效 → 用默认值
28
+ migrate: (raw) => ([15_000, 30_000, 60_000].includes(raw) ? raw : undefined),
29
+ }),
30
+ pollIntervalMs: Object.freeze({
31
+ kind: 'number', label: '活跃轮询间隔', unit: 'ms',
32
+ description: '对话框打开时的状态刷新频率',
33
+ defaultValue: 5_000, min: 1_000, max: 60_000, step: 1_000,
34
+ }),
35
+ idlePollIntervalMs: Object.freeze({
36
+ kind: 'number', label: '空闲轮询间隔', unit: 'ms',
37
+ description: '无交互时的状态刷新频率',
38
+ defaultValue: 60_000, min: 30_000, max: 600_000, step: 10_000,
39
+ }),
40
+ backupRetentionDays: Object.freeze({
41
+ kind: 'number', label: '备份保留天数', unit: 'day',
42
+ description: '超过此天数的自动备份会被清理;手动恢复点不受影响',
43
+ defaultValue: 30, min: 1, max: 365, step: 1,
44
+ }),
45
+ idleDowngradeNotification: Object.freeze({
46
+ kind: 'enum', label: '空闲降级提示',
47
+ description: '用户离开后是否显示提示',
48
+ defaultValue: 'silent',
49
+ options: Object.freeze([
50
+ { value: 'silent', label: '静默' },
51
+ { value: 'toast', label: '轻提示' },
52
+ { value: 'banner', label: '横幅' },
53
+ ]),
54
+ }),
55
+ strictConflictMode: Object.freeze({
56
+ kind: 'boolean', label: '严格冲突模式',
57
+ description: '开启后任何原身冲突都会阻止派生,而不是自动跳过',
58
+ defaultValue: false,
59
+ }),
60
+ syncIntervalHours: Object.freeze({
61
+ kind: 'enum', label: '母体自动同步间隔',
62
+ description: '每隔多久从本机母体 profile 克隆到镜像(off = 关闭;同步前自动备份)',
63
+ defaultValue: 'off',
64
+ options: Object.freeze([
65
+ { value: 'off', label: '关闭' },
66
+ { value: '6', label: '6 小时' },
67
+ { value: '12', label: '12 小时' },
68
+ { value: '24', label: '24 小时' },
69
+ ]),
70
+ }),
71
+ })
72
+
73
+ export const PREFERENCES_KEYS = Object.freeze(Object.keys(PREFERENCES_SCHEMA))
74
+
75
+ /** 由 schema 生成默认偏好(新字段自动出现在这里)。 */
76
+ export function buildDefaultPreferences(schema = PREFERENCES_SCHEMA) {
77
+ const out = {}
78
+ for (const [key, field] of Object.entries(schema)) out[key] = field.defaultValue
79
+ return out
80
+ }
81
+
82
+ /**
83
+ * 校验/对齐单个字段;非法返回 undefined。
84
+ * @param {NumberField|EnumField|BooleanField} field
85
+ * @param {unknown} value
86
+ */
87
+ export function coerceField(field, value) {
88
+ if (field.kind === 'number') {
89
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
90
+ if (value < field.min || value > field.max) return undefined
91
+ return Math.round((value - field.min) / field.step) * field.step + field.min
92
+ }
93
+ if (field.kind === 'enum') {
94
+ if (typeof value !== 'string') return undefined
95
+ return field.options.some(option => option.value === value) ? value : undefined
96
+ }
97
+ if (field.kind === 'boolean') return typeof value === 'boolean' ? value : undefined
98
+ return undefined
99
+ }
100
+
101
+ /**
102
+ * 纯函数:把任意 raw 规范成完整偏好。测试可直接调用。
103
+ * @param {unknown} raw
104
+ * @param {Record<string, NumberField|EnumField|BooleanField>} [schema]
105
+ * @returns {{preferences:Record<string, unknown>, existed:boolean, migrated:string[], droppedUnknown:string[]}}
106
+ */
107
+ export function normalizePreferences(raw, schema = PREFERENCES_SCHEMA) {
108
+ const preferences = buildDefaultPreferences(schema)
109
+ const migrated = []
110
+ const droppedUnknown = []
111
+ const missing = []
112
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
113
+ return { preferences, existed: false, migrated, droppedUnknown, missing: Object.keys(schema) }
114
+ }
115
+ for (const [key, value] of Object.entries(raw)) {
116
+ const field = schema[key]
117
+ if (field === undefined) { droppedUnknown.push(key); continue }
118
+ let next = value
119
+ if (typeof field.migrate === 'function') {
120
+ next = field.migrate(value)
121
+ if (next === undefined) { migrated.push(key); continue }
122
+ }
123
+ const coerced = coerceField(field, next)
124
+ if (coerced === undefined) { migrated.push(key); continue }
125
+ preferences[key] = coerced
126
+ if (coerced !== value) migrated.push(key)
127
+ }
128
+ for (const key of Object.keys(schema)) {
129
+ if (!(key in raw)) missing.push(key)
130
+ }
131
+ return { preferences, existed: true, migrated, droppedUnknown, missing }
132
+ }
133
+
134
+ export class PreferencesStore {
135
+ /**
136
+ * @param {{mirrorRoot: string, logger?: {warn?: Function},
137
+ * schema?: Record<string, NumberField|EnumField|BooleanField>}} options
138
+ */
139
+ constructor(options) {
140
+ this.mirrorRoot = String(options?.mirrorRoot ?? '')
141
+ if (this.mirrorRoot.length === 0) throw new Error('PreferencesStore: mirrorRoot required')
142
+ this.logger = options.logger ?? {}
143
+ this.schema = options.schema ?? PREFERENCES_SCHEMA
144
+ this.current = buildDefaultPreferences(this.schema)
145
+ this.loaded = false
146
+ }
147
+
148
+ filePath() {
149
+ return path.join(this.mirrorRoot, 'preferences.json')
150
+ }
151
+
152
+ /** 读取并规范偏好;缺失/迁移时写回;损坏文件保持原样(保留证据)。 */
153
+ load() {
154
+ this.loaded = true
155
+ const file = this.filePath()
156
+ const existed = fs.existsSync(file)
157
+ let raw = null
158
+ let corrupt = false
159
+ if (existed) {
160
+ try { raw = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { corrupt = true }
161
+ }
162
+ const report = normalizePreferences(raw, this.schema)
163
+ this.current = report.preferences
164
+ if (corrupt) {
165
+ this.logger.warn?.('[preferences] corrupt preferences.json; using defaults without overwrite')
166
+ return this.get()
167
+ }
168
+ const shouldPersist = !existed || report.migrated.length > 0
169
+ || report.droppedUnknown.length > 0 || report.missing.length > 0
170
+ if (shouldPersist) this.persist()
171
+ if (report.migrated.length > 0 || report.droppedUnknown.length > 0) {
172
+ this.logger.warn?.('[preferences] normalized', {
173
+ migrated: report.migrated, droppedUnknown: report.droppedUnknown,
174
+ })
175
+ }
176
+ return this.get()
177
+ }
178
+
179
+ /** 最近一次 load 的迁移报告(供诊断/测试)。 */
180
+ lastReport() {
181
+ return { migrated: [], droppedUnknown: [], existed: true }
182
+ }
183
+
184
+ get() {
185
+ return { ...this.current }
186
+ }
187
+
188
+ /**
189
+ * 增量更新:按 schema 校验,非法值抛错且不改内存状态;未知字段忽略。
190
+ * @param {Record<string, unknown>} patch
191
+ */
192
+ update(patch = {}) {
193
+ const next = { ...this.current }
194
+ for (const [key, value] of Object.entries(patch ?? {})) {
195
+ const field = this.schema[key]
196
+ if (field === undefined) continue
197
+ const coerced = coerceField(field, value)
198
+ if (coerced === undefined) {
199
+ throw new RangeError(`invalid value for ${key}: ${JSON.stringify(value)}`)
200
+ }
201
+ next[key] = coerced
202
+ }
203
+ this.current = next
204
+ this.persist()
205
+ return this.get()
206
+ }
207
+
208
+ persist() {
209
+ ensureDir(this.mirrorRoot)
210
+ writeJsonAtomic(this.filePath(), this.get())
211
+ }
212
+ }
@@ -0,0 +1,162 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // producer-contract — 业务生产者 → 决策中心的统一调用契约(v1)。
5
+ //
6
+ // 这五个系统本体不在本仓:本模块只定义「它们该怎么调用」,并提供:
7
+ // * normalizeProducerPayload(input) 字段校验 + 默认值 + 稳定 dedupeKey
8
+ // * createProducerSubmitter({submit}) 统一提交封装(返回统一 envelope)
9
+ // * producerCatalog() 机器可读契约目录(UI/外部系统可发现)
10
+ import { nowMs } from '../kernel/index.mjs'
11
+
12
+ export const PRODUCER_CONTRACT_VERSION = 1
13
+ export const PRODUCER_LEVELS = Object.freeze(['red', 'yellow', 'blue', 'green'])
14
+ export const PRODUCER_NAMES = Object.freeze(['HarnessMM', 'PluginUpdater', 'SuperAgent', 'PJM', 'Worker'])
15
+
16
+ export const PRODUCER_CONTRACTS = Object.freeze({
17
+ HarnessMM: Object.freeze({
18
+ kinds: ['harnessmm-suggestion'],
19
+ defaultLevel: 'blue',
20
+ sourceRole: 'worker',
21
+ required: ['title'],
22
+ defaultActions: [
23
+ { id: 'accept', label: '采纳', type: 'default' },
24
+ { id: 'ignore', label: '忽略', type: 'default' },
25
+ ],
26
+ }),
27
+ PluginUpdater: Object.freeze({
28
+ kinds: ['plugin-updater-backup'],
29
+ defaultLevel: 'green',
30
+ sourceRole: 'worker',
31
+ required: ['title'],
32
+ defaultActions: [],
33
+ }),
34
+ SuperAgent: Object.freeze({
35
+ kinds: ['superagent-completion'],
36
+ defaultLevel: 'green',
37
+ sourceRole: 'worker',
38
+ required: ['title'],
39
+ defaultActions: [],
40
+ }),
41
+ PJM: Object.freeze({
42
+ kinds: ['pjm-timeout', 'pjm-fatal'],
43
+ defaultLevel: 'yellow',
44
+ sourceRole: 'pjm',
45
+ required: ['title'],
46
+ defaultActions: [
47
+ { id: 'retry', label: '重试', type: 'primary' },
48
+ { id: 'abandon', label: '放弃', type: 'default' },
49
+ ],
50
+ }),
51
+ Worker: Object.freeze({
52
+ kinds: ['worker-deviation'],
53
+ defaultLevel: 'yellow',
54
+ sourceRole: 'worker',
55
+ required: ['title'],
56
+ defaultActions: [
57
+ { id: 'review', label: '查看', type: 'primary' },
58
+ { id: 'ignore', label: '忽略', type: 'default' },
59
+ ],
60
+ }),
61
+ })
62
+
63
+ const fail = (code, extra = {}) => ({ ok: false, code, ...extra })
64
+
65
+ /** 稳定默认 dedupeKey:调用方显式传优先,否则用常见业务 id 派生。 */
66
+ function deriveDedupeKey(producer, kind, raw) {
67
+ if (raw.dedupeKey !== undefined && raw.dedupeKey !== null && String(raw.dedupeKey).trim()) return String(raw.dedupeKey).trim().slice(0, 200)
68
+ const ref = raw.id ?? raw.backupId ?? raw.suggestionId ?? raw.taskId ?? raw.projectId ?? raw.workerId
69
+ if (ref === undefined || ref === null || String(ref).trim() === '') return undefined
70
+ return `${producer}:${kind}:${String(ref).trim()}`.slice(0, 200)
71
+ }
72
+
73
+ /**
74
+ * 校验并补全统一 payload。成功返回 { ok:true, payload };失败返回 { ok:false, code, errors }。
75
+ * 不写盘、不提交。
76
+ */
77
+ export function normalizeProducerPayload(input = {}) {
78
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return fail('invalid-payload')
79
+ const producer = String(input.producer ?? '').trim()
80
+ const contract = PRODUCER_CONTRACTS[producer]
81
+ if (!contract) return fail('unknown-producer', { allowedProducers: [...PRODUCER_NAMES] })
82
+ const kind = String(input.kind ?? contract.kinds[0]).trim()
83
+ if (!contract.kinds.includes(kind)) {
84
+ return fail('unknown-kind', { producer, allowedKinds: [...contract.kinds] })
85
+ }
86
+ const level = input.level === undefined || input.level === null ? contract.defaultLevel : String(input.level).trim().toLowerCase()
87
+ if (!PRODUCER_LEVELS.includes(level)) return fail('bad-level', { allowedLevels: [...PRODUCER_LEVELS] })
88
+ const title = String(input.title ?? '').trim()
89
+ if (!title) return fail('title-required')
90
+ const actions = Array.isArray(input.actions) ? input.actions.slice(0, 12)
91
+ : (Array.isArray(contract.defaultActions) && contract.defaultActions.length > 0 ? contract.defaultActions.map((item) => ({ ...item })) : undefined)
92
+ const options = Array.isArray(input.options) ? input.options.slice(0, 12) : undefined
93
+ if (level !== 'green' && !(actions?.length) && !(options?.length)) {
94
+ return fail('options-or-actions-required', { level })
95
+ }
96
+ const timeoutMinutes = Number.isFinite(Number(input.timeoutMinutes))
97
+ ? Math.max(0, Number(input.timeoutMinutes))
98
+ : kind === 'pjm-timeout' ? 5 : undefined
99
+ const payload = {
100
+ producer,
101
+ kind,
102
+ level,
103
+ title: title.slice(0, 500),
104
+ context: String(input.context ?? input.description ?? `${producer}/${kind}`).slice(0, 12000),
105
+ ...(actions ? { actions } : {}),
106
+ ...(options ? { options } : {}),
107
+ ...(timeoutMinutes === undefined ? {} : { timeoutMinutes }),
108
+ ...(deriveDedupeKey(producer, kind, input) ? { dedupeKey: deriveDedupeKey(producer, kind, input) } : {}),
109
+ sourceRole: String(input.sourceRole ?? contract.sourceRole),
110
+ ...(input.sessionId ? { sessionId: String(input.sessionId).slice(0, 200) } : {}),
111
+ ...(input.metadata && typeof input.metadata === 'object' ? { metadata: input.metadata } : {}),
112
+ producerContractVersion: PRODUCER_CONTRACT_VERSION,
113
+ at: nowMs(),
114
+ }
115
+ return { ok: true, payload }
116
+ }
117
+
118
+ /** 统一提交封装:返回固定 envelope,外部系统不需要理解 decision-center 内部形状。 */
119
+ export function createProducerSubmitter({ submit } = {}) {
120
+ if (typeof submit !== 'function') throw new TypeError('createProducerSubmitter: submit required')
121
+ return async function submitProducerEvent(input = {}) {
122
+ const normalized = normalizeProducerPayload(input)
123
+ if (!normalized.ok) {
124
+ return { ok: false, code: normalized.code, errors: normalized.errors ?? null, ...normalized }
125
+ }
126
+ let out = null
127
+ try {
128
+ out = await submit(normalized.payload)
129
+ } catch (error) {
130
+ return { ok: false, code: 'submit-failed', error: String(error?.message ?? error).slice(0, 500) }
131
+ }
132
+ return {
133
+ ok: out?.ok !== false,
134
+ producer: normalized.payload.producer,
135
+ kind: normalized.payload.kind,
136
+ level: normalized.payload.level,
137
+ ticketId: out?.ticket?.id ?? null,
138
+ deduped: out?.deduped === true,
139
+ queued: out?.queued === true,
140
+ outboxId: out?.outboxId ?? null,
141
+ reason: out?.reason ?? null,
142
+ }
143
+ }
144
+ }
145
+
146
+ export function producerCatalog() {
147
+ return {
148
+ ok: true,
149
+ version: PRODUCER_CONTRACT_VERSION,
150
+ producers: PRODUCER_NAMES.map((producer) => {
151
+ const contract = PRODUCER_CONTRACTS[producer]
152
+ return {
153
+ producer,
154
+ kinds: [...contract.kinds],
155
+ defaultLevel: contract.defaultLevel,
156
+ sourceRole: contract.sourceRole,
157
+ required: [...contract.required],
158
+ payload: ['producer', 'kind', 'level?', 'title', 'context', 'actions|options', 'timeoutMinutes?', 'dedupeKey?', 'sourceRole?', 'sessionId?'],
159
+ }
160
+ }),
161
+ }
162
+ }