dsh-coexist-plugin 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ const RESERVED_TOOL_NAMES = new Set(['run_code'])
2
+ const DEFAULT_MAX_ALIAS_LENGTH = 64
3
+
4
+ function normalizeConfig(config = {}) {
5
+ const envWatch = (process.env.DSH_COEXIST_WATCH ?? '')
6
+ .split(',')
7
+ .map((name) => name.trim())
8
+ .filter(Boolean)
9
+ const watch = Array.isArray(config.watch) && config.watch.length > 0 ? config.watch : envWatch
10
+ const ignore = new Set([...(config.ignore ?? []), ...RESERVED_TOOL_NAMES])
11
+ return {
12
+ mode: config.mode ?? 'alias',
13
+ watch,
14
+ ignore,
15
+ prefix: config.prefix ?? 'coexist',
16
+ maxAliasLength: config.maxAliasLength ?? DEFAULT_MAX_ALIAS_LENGTH,
17
+ debug: config.debug === true,
18
+ }
19
+ }
20
+
21
+ function matchesWatch(name, watch) {
22
+ return watch.includes('*') || watch.includes(name)
23
+ }
24
+
25
+ function sanitize(value) {
26
+ return String(value)
27
+ .replace(/[^A-Za-z0-9_-]/g, '-')
28
+ .replace(/-+/g, '-')
29
+ .replace(/^-|-$/g, '')
30
+ }
31
+
32
+ function cloneWithName(def, name) {
33
+ const description = def.description
34
+ ? `${def.description} (coexist alias)`
35
+ : 'coexist alias for a duplicate tool name'
36
+ return { ...def, name, description }
37
+ }
38
+
39
+ function log(ctx, level, message, extra) {
40
+ const logger = ctx?.logger
41
+ const fn = logger?.[level]
42
+ if (typeof fn === 'function') {
43
+ fn.call(logger, message, extra)
44
+ return
45
+ }
46
+ if (level === 'warn' || level === 'error') {
47
+ console.warn(message, extra ?? '')
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 包装 ctx.tools.register:同名工具不再抛错,而是注册成一个稳定的别名,
53
+ * 避免第二个插件因为重名而整块加载失败。
54
+ *
55
+ * @param {object} ctx Cordis 上下文(或带 tools/effect/logger 的测试替身)。
56
+ * @param {object} config
57
+ * @param {'alias'|'off'} [config.mode='alias'] 共存模式;当前只支持 alias。
58
+ * @param {string[]} [config.watch=[]] 要接管的工具名;为空时不启用共存。
59
+ * @param {string[]} [config.ignore=[]] 保持原生行为的工具名。
60
+ * @param {string} [config.prefix='coexist'] 别名后缀前缀。
61
+ * @param {number} [config.maxAliasLength=64] 别名最大长度(DeepSeek 工具名限制)。
62
+ */
63
+ export function installToolAliasing(ctx, config = {}) {
64
+ const options = normalizeConfig(config)
65
+ const tools = ctx?.tools
66
+
67
+ if (!tools || typeof tools.register !== 'function') {
68
+ return { installed: false, reason: 'ctx.tools.register is not available' }
69
+ }
70
+ if (options.watch.length === 0) {
71
+ return { installed: false, reason: 'watch list is empty; coexistence disabled' }
72
+ }
73
+ if (options.mode === 'off') {
74
+ return { installed: false, reason: 'mode=off' }
75
+ }
76
+ if (options.mode !== 'alias') {
77
+ return { installed: false, reason: `unsupported mode: ${options.mode}` }
78
+ }
79
+
80
+ const originalRegister = tools.register.bind(tools)
81
+ const registry = new Map()
82
+ let sequence = 0
83
+
84
+ const makeAlias = (name) => {
85
+ const base = sanitize(name) || 'tool'
86
+ for (;;) {
87
+ sequence += 1
88
+ const suffix = `__${options.prefix}${sequence}`
89
+ const room = Math.max(1, options.maxAliasLength - suffix.length)
90
+ const alias = `${base.slice(0, room)}${suffix}`
91
+ if (!registry.has(alias) && alias !== name) return alias
92
+ }
93
+ }
94
+
95
+ const wrappedRegister = (def) => {
96
+ const toolName = def?.name
97
+ if (typeof toolName !== 'string' || toolName.length === 0) {
98
+ return originalRegister(def)
99
+ }
100
+ if (options.ignore.has(toolName) || !matchesWatch(toolName, options.watch)) {
101
+ return originalRegister(def)
102
+ }
103
+
104
+ const entries = registry.get(toolName)
105
+
106
+ if (!entries || entries.length === 0) {
107
+ const dispose = originalRegister(def)
108
+ const entry = { name: toolName, alias: toolName, def, dispose, primary: true }
109
+ registry.set(toolName, [entry])
110
+ return () => {
111
+ const current = registry.get(toolName) ?? []
112
+ const next = current.filter((item) => item !== entry)
113
+ if (next.length === 0) registry.delete(toolName)
114
+ else registry.set(toolName, next)
115
+ entry.dispose()
116
+ }
117
+ }
118
+
119
+ let alias
120
+ try {
121
+ alias = makeAlias(toolName)
122
+ const aliasDef = cloneWithName(def, alias)
123
+ const dispose = originalRegister(aliasDef)
124
+ const entry = { name: toolName, alias, def, dispose, primary: false }
125
+ entries.push(entry)
126
+ registry.set(toolName, entries)
127
+ log(ctx, 'info', `[coexist] "${toolName}" already registered; mounted alias "${alias}"`)
128
+ return () => {
129
+ const current = registry.get(toolName) ?? []
130
+ const next = current.filter((item) => item !== entry)
131
+ if (next.length === 0) registry.delete(toolName)
132
+ else registry.set(toolName, next)
133
+ entry.dispose()
134
+ }
135
+ } catch (err) {
136
+ // fail-open:保留宿主的原生行为。第二个插件可能仍然失败,
137
+ // 但兼容层不能把事情变得更糟。
138
+ log(ctx, 'warn', `[coexist] alias registration failed for "${toolName}"; falling back to native behavior`, err)
139
+ return originalRegister(def)
140
+ }
141
+ }
142
+
143
+ let patched = false
144
+ try {
145
+ tools.register = wrappedRegister
146
+ patched = tools.register === wrappedRegister
147
+ } catch {
148
+ patched = false
149
+ }
150
+
151
+ if (!patched) {
152
+ try {
153
+ Object.defineProperty(tools, 'register', {
154
+ configurable: true,
155
+ writable: true,
156
+ value: wrappedRegister,
157
+ })
158
+ patched = tools.register === wrappedRegister
159
+ } catch {
160
+ patched = false
161
+ }
162
+ }
163
+
164
+ if (!patched) {
165
+ if (options.debug) {
166
+ try {
167
+ const proto = Object.getPrototypeOf(tools)
168
+ const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, 'register') : undefined
169
+ log(ctx, 'warn', `[coexist] diagnostics: ${JSON.stringify({
170
+ extensible: Object.isExtensible(tools),
171
+ frozen: Object.isFrozen(tools),
172
+ protoFrozen: proto ? Object.isFrozen(proto) : null,
173
+ descriptor: descriptor
174
+ ? { writable: descriptor.writable, configurable: descriptor.configurable }
175
+ : null,
176
+ })}`)
177
+ console.log('[coexist] diagnostics', JSON.stringify({
178
+ extensible: Object.isExtensible(tools),
179
+ frozen: Object.isFrozen(tools),
180
+ protoFrozen: proto ? Object.isFrozen(proto) : null,
181
+ descriptor: descriptor
182
+ ? { writable: descriptor.writable, configurable: descriptor.configurable }
183
+ : null,
184
+ }))
185
+ } catch (err) {
186
+ log(ctx, 'warn', `[coexist] diagnostics failed: ${err.message}`)
187
+ }
188
+ }
189
+ log(ctx, 'warn', '[coexist] ctx.tools.register is not writable; coexistence disabled for this session')
190
+ return { installed: false, reason: 'ctx.tools.register is not writable' }
191
+ }
192
+
193
+ const restore = () => {
194
+ try {
195
+ tools.register = originalRegister
196
+ } catch {
197
+ // 服务可能在启动后被冻结;此时没有别的清理动作可做。
198
+ }
199
+ }
200
+
201
+ if (typeof ctx.effect === 'function') {
202
+ ctx.effect(() => restore)
203
+ }
204
+
205
+ log(ctx, 'info', `[coexist] duplicate tool aliasing enabled (watch=${options.watch.join(',')})`)
206
+
207
+ return {
208
+ installed: true,
209
+ registry,
210
+ restore,
211
+ originalRegister,
212
+ wrappedRegister,
213
+ }
214
+ }
package/src/cleanup.js ADDED
@@ -0,0 +1,207 @@
1
+ import fs from 'node:fs'
2
+ import fsp from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { createRequire } from 'node:module'
5
+ import { pathToFileURL } from 'node:url'
6
+ import { detectProfile } from './ui.js'
7
+
8
+ const requireFromCleanup = createRequire(import.meta.url)
9
+ const PLUGIN_NAME = 'dsh-coexist-plugin'
10
+ const CLI_PACKAGE = 'dsh-coexist-cli'
11
+
12
+ async function exists(file) {
13
+ try {
14
+ await fsp.access(file)
15
+ return true
16
+ } catch {
17
+ return false
18
+ }
19
+ }
20
+
21
+ async function removeIfEmpty(dir) {
22
+ try {
23
+ const entries = await fsp.readdir(dir)
24
+ if (entries.length === 0) await fsp.rmdir(dir)
25
+ } catch {
26
+ // 不存在或非空都无需处理。
27
+ }
28
+ }
29
+
30
+ function readJson(file) {
31
+ try {
32
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
33
+ } catch {
34
+ return null
35
+ }
36
+ }
37
+
38
+ /** 直接调用 CLI 的 desktop.js:它不依赖 yaml,分阶段副本里也能加载。 */
39
+ async function loadDesktopModule(profileDir) {
40
+ const candidates = [path.join(profileDir, '.dsh-coexist', 'plugins', CLI_PACKAGE, 'src', 'desktop.js')]
41
+ try {
42
+ const pkgPath = requireFromCleanup.resolve('dsh-coexist-cli/package.json')
43
+ candidates.push(path.join(path.dirname(pkgPath), 'src', 'desktop.js'))
44
+ } catch {
45
+ // 没有依赖副本时只用分阶段副本。
46
+ }
47
+ for (const file of candidates) {
48
+ if (!(await exists(file))) continue
49
+ try {
50
+ return await import(pathToFileURL(file).href)
51
+ } catch {
52
+ // 继续尝试下一个候选。
53
+ }
54
+ }
55
+ return null
56
+ }
57
+
58
+ /**
59
+ * 宿主插件页卸载不会调用 dsh-coexist CLI,因此这里补一套同样的磁盘清理。
60
+ * 只清安装产物,不动 ~/.dsh/coexist 里的备份/报告(那需要 --purge)。
61
+ */
62
+ export async function cleanupSelf(home, profileDir, options = {}) {
63
+ const cleaned = []
64
+ const stagedRoot = path.join(profileDir, '.dsh-coexist', 'plugins')
65
+ const legacy = path.join(home, 'coexist', 'desktop')
66
+
67
+ // 旧版快捷方式启动器先恢复,再删目录;恢复失败就保留,避免留下坏快捷方式。
68
+ if (await exists(legacy)) {
69
+ const manifest = path.join(legacy, 'manifest.json')
70
+ let restored = false
71
+ if (await exists(manifest)) {
72
+ try {
73
+ const desktop = await loadDesktopModule(profileDir)
74
+ if (desktop?.restoreDesktop) {
75
+ await desktop.restoreDesktop({ home })
76
+ restored = true
77
+ }
78
+ } catch (error) {
79
+ options.log?.(`[coexist] desktop restore failed, keeping launcher: ${error.message}`)
80
+ }
81
+ }
82
+ if (!(await exists(manifest)) || restored) {
83
+ await fsp.rm(legacy, { recursive: true, force: true })
84
+ cleaned.push(legacy)
85
+ }
86
+ }
87
+
88
+ for (const name of [PLUGIN_NAME, CLI_PACKAGE]) {
89
+ const dir = path.join(stagedRoot, name)
90
+ if (!(await exists(dir))) continue
91
+ await fsp.rm(dir, { recursive: true, force: true })
92
+ cleaned.push(dir)
93
+ }
94
+
95
+ await removeIfEmpty(stagedRoot)
96
+ await removeIfEmpty(path.join(profileDir, '.dsh-coexist'))
97
+ return cleaned
98
+ }
99
+
100
+ /**
101
+ * 包装宿主 `pluginManager.removeBundle`:卸载共存插件成功后清理安装产物。
102
+ * 更新流程内部也会调用 removeBundle,用 updateBundle 的计数避开。
103
+ */
104
+ export function installUninstallCleanup(ctx, options = {}) {
105
+ const { home, profile } = detectProfile(ctx, options)
106
+ const profileDir = path.join(home, 'profiles', profile)
107
+ const patched = new WeakSet()
108
+ const restorers = []
109
+ let updating = 0
110
+
111
+ const patch = (service) => {
112
+ if (!service || patched.has(service)) return
113
+ const proto = Object.getPrototypeOf(service)
114
+ const target = proto && typeof proto.removeBundle === 'function' ? proto : service
115
+ if (typeof target.removeBundle !== 'function' || target.__coexistUninstallHook) return
116
+
117
+ const originalRemove = target.removeBundle
118
+ const originalUpdate = target.updateBundle
119
+
120
+ const wrappedRemove = async function (...args) {
121
+ const result = await originalRemove.apply(this, args)
122
+ const name = typeof args[0] === 'string' ? args[0] : args[0]?.name
123
+ const failed = result?.application === 'failed' || result?.application === 'cancelled'
124
+ if (name !== PLUGIN_NAME || updating > 0 || failed) return result
125
+
126
+ const manifest = readJson(path.join(profileDir, 'package.json'))
127
+ const stillReferenced =
128
+ (manifest?.dsh?.profile?.bundles ?? []).includes(PLUGIN_NAME) ||
129
+ Object.hasOwn(manifest?.dependencies ?? {}, PLUGIN_NAME)
130
+ if (stillReferenced) return result
131
+
132
+ try {
133
+ const cleaned = await cleanupSelf(home, profileDir, options)
134
+ options.log?.(`[coexist] host uninstall cleanup: ${cleaned.join(', ') || 'nothing to clean'}`)
135
+ } catch (error) {
136
+ options.log?.(`[coexist] host uninstall cleanup failed: ${error.message}`)
137
+ }
138
+ return result
139
+ }
140
+
141
+ let wrappedUpdate = null
142
+ if (typeof originalUpdate === 'function') {
143
+ wrappedUpdate = async function (...args) {
144
+ updating += 1
145
+ try {
146
+ return await originalUpdate.apply(this, args)
147
+ } finally {
148
+ updating -= 1
149
+ }
150
+ }
151
+ }
152
+
153
+ const apply = (holder) => {
154
+ holder.removeBundle = wrappedRemove
155
+ if (wrappedUpdate) holder.updateBundle = wrappedUpdate
156
+ }
157
+
158
+ try {
159
+ apply(target)
160
+ } catch {
161
+ try {
162
+ apply(service)
163
+ } catch {
164
+ return
165
+ }
166
+ }
167
+
168
+ patched.add(service)
169
+ target.__coexistUninstallHook = true
170
+ options.log?.('[coexist] host uninstall hook active')
171
+ restorers.push(() => {
172
+ try {
173
+ target.removeBundle = originalRemove
174
+ if (originalUpdate) target.updateBundle = originalUpdate
175
+ delete target.__coexistUninstallHook
176
+ } catch {
177
+ // 宿主已经销毁时无需恢复。
178
+ }
179
+ })
180
+ }
181
+
182
+ try {
183
+ patch(typeof ctx.get === 'function' ? ctx.get('pluginManager') : ctx.pluginManager)
184
+ } catch {
185
+ // pluginManager 还没就绪时等下面的事件。
186
+ }
187
+
188
+ try {
189
+ ctx.on('internal/service', (name, service) => {
190
+ if (name === 'pluginManager') patch(service)
191
+ })
192
+ } catch {
193
+ // 没有事件服务时只能依赖 apply 时的 pluginManager。
194
+ }
195
+
196
+ try {
197
+ ctx.effect(
198
+ () => () => {
199
+ for (const restore of restorers.splice(0)) restore()
200
+ },
201
+ 'coexist: host uninstall cleanup',
202
+ )
203
+ } catch {
204
+ // 清理钩子失败不影响插件本身。
205
+ }
206
+ return true
207
+ }
@@ -0,0 +1,78 @@
1
+ const COMMAND_SUFFIX = '__coexist'
2
+
3
+ function isDuplicateCommandError(error, name) {
4
+ const message = error?.message
5
+ return (
6
+ typeof message === 'string' &&
7
+ typeof name === 'string' &&
8
+ message.includes(`command "${name}" is already registered`)
9
+ )
10
+ }
11
+
12
+ function aliasCommandName(name, index) {
13
+ return `${name}${COMMAND_SUFFIX}${index}`
14
+ }
15
+
16
+ function aliasDescription(description) {
17
+ if (typeof description !== 'string' || description.trim().length === 0) return 'coexist alias'
18
+ return `${description} (coexist alias)`
19
+ }
20
+
21
+ /**
22
+ * 在 CommandRuntime 原型上包一层 register:
23
+ * 同名命令冲突时,把后注册的命令改成 `<name>__coexistN`,两个命令都保留。
24
+ *
25
+ * 命令名规则是 /^[a-z][a-z0-9_-]*$/,下划线合法,因此别名不需要额外转义。
26
+ * 只处理宿主明确抛出的 "command ... is already registered";其它错误原样上抛。
27
+ */
28
+ export function installCommandPatch(CommandService, options = {}) {
29
+ if (!CommandService || typeof CommandService.prototype?.register !== 'function') {
30
+ return false
31
+ }
32
+ if (globalThis.__dshCoexistCommandPatched) return true
33
+
34
+ const log = options.log ?? (() => {})
35
+ const original = CommandService.prototype.register
36
+
37
+ CommandService.prototype.register = function registerWithCoexist(definition, ...rest) {
38
+ if (globalThis.__dshCoexistActive === false) {
39
+ return original.call(this, definition, ...rest)
40
+ }
41
+
42
+ const name = definition?.name
43
+ try {
44
+ return original.call(this, definition, ...rest)
45
+ } catch (error) {
46
+ if (!isDuplicateCommandError(error, name)) throw error
47
+
48
+ for (let index = 1; index <= 100; index += 1) {
49
+ const alias = aliasCommandName(name, index)
50
+ const aliasDefinition = {
51
+ ...definition,
52
+ name: alias,
53
+ description: aliasDescription(definition?.description),
54
+ }
55
+
56
+ try {
57
+ const dispose = original.call(this, aliasDefinition, ...rest)
58
+ log(`[coexist] command alias: /${name} -> /${alias}`)
59
+ try {
60
+ options.onAlias?.({ name, alias, kind: 'command' })
61
+ } catch {
62
+ // 诊断回调不能影响宿主。
63
+ }
64
+ return dispose
65
+ } catch (retryError) {
66
+ if (isDuplicateCommandError(retryError, alias)) continue
67
+ throw retryError
68
+ }
69
+ }
70
+
71
+ throw error
72
+ }
73
+ }
74
+
75
+ globalThis.__dshCoexistCommandPatched = true
76
+ log(`[coexist] command patch active (${CommandService.name ?? 'unknown'})`)
77
+ return true
78
+ }
package/src/config.js ADDED
@@ -0,0 +1,49 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ export function coexistConfigFile() {
6
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
7
+ return process.env.DSH_COEXIST_CONFIG ?? path.join(home, 'coexist', 'config.json')
8
+ }
9
+
10
+ export function coexistStateDir() {
11
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
12
+ return path.join(home, 'coexist')
13
+ }
14
+
15
+ function readJsonFile(file) {
16
+ try {
17
+ return JSON.parse(readFileSync(file, 'utf8'))
18
+ } catch {
19
+ return null
20
+ }
21
+ }
22
+
23
+ /** 读取最近一次 check/plan 写入的 state 和 plan,供运行期参考。 */
24
+ export function loadRuntimePlan() {
25
+ const dir = coexistStateDir()
26
+ const state = readJsonFile(path.join(dir, 'state.json'))
27
+ if (!state) return { state: null, plan: null }
28
+ const id = state?.plan?.id
29
+ const plan = id ? readJsonFile(path.join(dir, 'plans', `${id}.json`)) : null
30
+ return { state, plan }
31
+ }
32
+
33
+ /**
34
+ * 读取 ~/.dsh/coexist/config.json:
35
+ * {
36
+ * "hooks": { "agent/pre-step": { "order": ["plugin-a"], "disable": ["plugin-b"] } },
37
+ * "routes": { "memory_search": { "by": "args", "match": { "scope": "code" } } }
38
+ * }
39
+ * 文件不存在或格式错误时返回空配置,不影响宿主。
40
+ */
41
+ export function loadCoexistConfig() {
42
+ const file = coexistConfigFile()
43
+ try {
44
+ const value = JSON.parse(readFileSync(file, 'utf8'))
45
+ return { file, exists: true, value: value && typeof value === 'object' ? value : {} }
46
+ } catch {
47
+ return { file, exists: false, value: {} }
48
+ }
49
+ }