dsh-coexist-plugin 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.
package/src/patch.js ADDED
@@ -0,0 +1,355 @@
1
+ import { appendFileSync } from 'node:fs'
2
+
3
+ const NAME_LIMIT = 64
4
+ const ROUTER = Symbol('coexist.router')
5
+
6
+ function createLog(logFile) {
7
+ return (message) => {
8
+ if (logFile) {
9
+ try {
10
+ appendFileSync(logFile, `[${new Date().toISOString()}] ${message}\n`)
11
+ } catch {
12
+ // Logging must never break the host.
13
+ }
14
+ }
15
+ console.log(message)
16
+ }
17
+ }
18
+
19
+ /** 原生 register 只在同作用域重名时抛这个错;其他错误必须原样上抛。 */
20
+ function isDuplicateToolError(error, name) {
21
+ const message = error?.message
22
+ return (
23
+ typeof message === 'string' &&
24
+ typeof name === 'string' &&
25
+ message.includes('is already registered') &&
26
+ message.includes(`"${name}"`)
27
+ )
28
+ }
29
+
30
+ function aliasName(name, index) {
31
+ const suffix = `__coexist${index}`
32
+ if (name.length + suffix.length <= NAME_LIMIT) return `${name}${suffix}`
33
+ return `${name.slice(0, NAME_LIMIT - suffix.length)}${suffix}`
34
+ }
35
+
36
+ function sameDefinition(left, right) {
37
+ if (!left || !right) return false
38
+ if (left === right) return true
39
+ if (left.execute !== right.execute) return false
40
+ if (left.description !== right.description) return false
41
+ try {
42
+ return (
43
+ JSON.stringify(left.parameters) === JSON.stringify(right.parameters) &&
44
+ JSON.stringify(left.output?.schema) === JSON.stringify(right.output?.schema)
45
+ )
46
+ } catch {
47
+ return false
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 从运行期的 layers 里找到同名定义(与刚才抛重复错误的作用域一致)。
53
+ * dsh-scope 的 scoped 表是内部结构;任何异常都 fail-open 返回 null。
54
+ */
55
+ function findExistingDefinition(runtime, name) {
56
+ const layers = runtime?.layers
57
+ if (!layers) return null
58
+
59
+ const lookup = (layer) => {
60
+ try {
61
+ return layer?.tools?.get?.(name) ?? null
62
+ } catch {
63
+ return null
64
+ }
65
+ }
66
+
67
+ const globalDefinition = lookup(layers.global)
68
+ if (globalDefinition) return globalDefinition
69
+
70
+ const scoped = layers.scoped
71
+ if (scoped && typeof scoped.values === 'function') {
72
+ for (const layer of scoped.values()) {
73
+ const found = lookup(layer)
74
+ if (found) return found
75
+ }
76
+ }
77
+
78
+ return null
79
+ }
80
+
81
+ function defineRouter(definition, router) {
82
+ try {
83
+ Object.defineProperty(definition, ROUTER, {
84
+ value: router,
85
+ enumerable: false,
86
+ configurable: true,
87
+ })
88
+ } catch {
89
+ // 冻结的定义对象只影响 fallback/route,不影响别名共存。
90
+ }
91
+ }
92
+
93
+ function chooseRoute(rule, args, exec) {
94
+ if (!rule || typeof rule !== 'object') return null
95
+ const decision = {
96
+ target: rule.prefer === 'primary' ? 'primary' : 'backup',
97
+ index: Number.isInteger(rule.index) && rule.index >= 0 ? rule.index : 0,
98
+ }
99
+ const primary = { target: 'primary', index: 0 }
100
+
101
+ if (rule.by === 'agent') {
102
+ const wanted = rule.equals ?? rule.match
103
+ if (wanted == null) return null
104
+ const agent = exec?.agent
105
+ const candidates = [
106
+ agent?.session?.id,
107
+ agent?.id,
108
+ agent?.name,
109
+ agent?.preset,
110
+ agent === undefined ? null : String(agent),
111
+ ]
112
+ .filter((value) => value !== undefined && value !== null)
113
+ .map(String)
114
+ return candidates.includes(String(wanted)) ? decision : primary
115
+ }
116
+
117
+ const match = rule.match && typeof rule.match === 'object' ? rule.match : null
118
+ if (!match) return null
119
+
120
+ for (const [key, expected] of Object.entries(match)) {
121
+ let actual
122
+ try {
123
+ actual = args?.[key]
124
+ } catch {
125
+ return primary
126
+ }
127
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) return primary
128
+ }
129
+
130
+ return decision
131
+ }
132
+
133
+ function runEntry(entry, callArgs) {
134
+ try {
135
+ return entry.execute.apply(entry.definition, callArgs)
136
+ } catch (error) {
137
+ return Promise.reject(error)
138
+ }
139
+ }
140
+
141
+ function wrapForRoute(definition, name, rule, options) {
142
+ const originalExecute = definition.execute
143
+ if (typeof originalExecute !== 'function' || !rule) return definition
144
+
145
+ const router = { primaryDefinition: definition, primary: originalExecute, backups: [] }
146
+ const primaryEntry = { definition, execute: originalExecute }
147
+
148
+ const routed = { ...definition }
149
+ routed.execute = function executeWithRoute(...callArgs) {
150
+ let target = 'primary'
151
+ let index = 0
152
+ let reason = 'default'
153
+
154
+ try {
155
+ const decided = chooseRoute(rule, callArgs[0], callArgs[1])
156
+ if (decided) {
157
+ target = decided.target
158
+ index = decided.index
159
+ reason = rule.by ?? 'rule'
160
+ }
161
+ } catch {
162
+ target = 'primary'
163
+ }
164
+
165
+ if (target === 'backup' && router.backups.length > 0) {
166
+ const chosen = router.backups[Math.min(index, router.backups.length - 1)]
167
+ try {
168
+ options.onRoute?.({ tool: name, target: 'backup', reason, index })
169
+ } catch {
170
+ // 诊断回调不能影响调用。
171
+ }
172
+ return runEntry(chosen, callArgs)
173
+ }
174
+
175
+ return runEntry(primaryEntry, callArgs)
176
+ }
177
+
178
+ defineRouter(routed, router)
179
+ return routed
180
+ }
181
+
182
+ function wrapForFallback(definition, name, options) {
183
+ const originalExecute = definition.execute
184
+ if (typeof originalExecute !== 'function') return definition
185
+
186
+ const router = { primaryDefinition: definition, primary: originalExecute, backups: [] }
187
+ const primaryEntry = { definition, execute: originalExecute }
188
+
189
+ const routed = { ...definition }
190
+ routed.execute = async function executeWithFallback(...callArgs) {
191
+ try {
192
+ return await runEntry(primaryEntry, callArgs)
193
+ } catch (primaryError) {
194
+ let lastError = primaryError
195
+
196
+ for (let index = 0; index < router.backups.length; index += 1) {
197
+ const backup = router.backups[index]
198
+ try {
199
+ const result = await runEntry(backup, callArgs)
200
+ try {
201
+ options.onFallback?.({
202
+ tool: name,
203
+ error: primaryError?.message ?? String(primaryError),
204
+ backup: index,
205
+ })
206
+ } catch {
207
+ // 诊断回调不能影响调用。
208
+ }
209
+ return result
210
+ } catch (error) {
211
+ lastError = error
212
+ }
213
+ }
214
+
215
+ throw lastError
216
+ }
217
+ }
218
+
219
+ defineRouter(routed, router)
220
+ return routed
221
+ }
222
+
223
+ function wrapForAlias(definition, alias, primaryName, options) {
224
+ const originalExecute = definition.execute
225
+ const aliasDefinition = { ...definition, name: alias }
226
+ if (definition.description) {
227
+ aliasDefinition.description = `${definition.description} (coexist alias)`
228
+ }
229
+ if (typeof originalExecute === 'function') {
230
+ aliasDefinition.execute = function executeAlias(...args) {
231
+ try {
232
+ options.onCall?.({ tool: alias, aliasOf: primaryName })
233
+ } catch {
234
+ // 诊断回调不能影响调用。
235
+ }
236
+ return originalExecute.apply(definition, args)
237
+ }
238
+ }
239
+ return aliasDefinition
240
+ }
241
+
242
+ /**
243
+ * 在 ToolRuntime 原型上包一层 register:
244
+ * 1. 相同定义重复注册 → 忽略(一个名字只保留一个实现)。
245
+ * 2. 不同定义重复注册 → 注册成 `<name>__coexistN`,两个都能调用。
246
+ * 3. mode=fallback 时,主实现抛错后显式降级到备份实现,并记录一次 fallback。
247
+ * 4. mode=route 时,按 routes 规则选择主实现或备份实现。
248
+ *
249
+ * @param {Function} ToolService 宿主注册类(桌面版为 ToolRuntime,CLI 版为 ToolsService)。
250
+ * @param {object} options
251
+ * @param {boolean} [options.auto=true] 自动接管所有工具名;false 时只接管 watch 列表。
252
+ * @param {string[]} [options.watch=[]] 需要接管的工具名。
253
+ * @param {'alias'|'fallback'|'route'} [options.mode='alias'] 重名策略。
254
+ * @param {object} [options.routes] mode=route 时的按工具路由规则。
255
+ * @param {(message: string) => void} [options.log] 日志函数。
256
+ * @param {string} [options.logFile] 日志文件路径。
257
+ * @param {(name: string, alias: string) => void} [options.onAlias] 新别名回调。
258
+ * @param {(event: { tool: string, aliasOf: string }) => void} [options.onCall] 别名被调用回调。
259
+ * @param {(event: { tool: string, error: string }) => void} [options.onFallback] 降级回调。
260
+ * @param {(event: { tool: string, target: string, reason: string }) => void} [options.onRoute] 路由回调。
261
+ */
262
+ export function installPrototypePatch(ToolService, options = {}) {
263
+ const watch = Array.isArray(options.watch) ? options.watch.filter(Boolean) : []
264
+ const auto = options.auto !== false && watch.length === 0
265
+ const watchSet = new Set(watch)
266
+ const log = options.log ?? createLog(options.logFile)
267
+ const mode =
268
+ options.mode === 'fallback' ? 'fallback' : options.mode === 'route' ? 'route' : 'alias'
269
+ const fallback = mode === 'fallback'
270
+ const routes = options.routes && typeof options.routes === 'object' ? options.routes : {}
271
+
272
+ if (!ToolService || typeof ToolService.prototype?.register !== 'function') {
273
+ log('[coexist] tools register not found; prototype patch skipped')
274
+ return false
275
+ }
276
+
277
+ if (globalThis.__dshCoexistPrototypePatched) {
278
+ return true
279
+ }
280
+
281
+ const originalRegister = ToolService.prototype.register
282
+
283
+ ToolService.prototype.register = function registerWithCoexist(definition, registerOptions) {
284
+ if (globalThis.__dshCoexistActive === false) {
285
+ return originalRegister.call(this, definition, registerOptions)
286
+ }
287
+
288
+ const name = definition?.name
289
+ const watched = auto || (typeof name === 'string' && watchSet.has(name))
290
+ if (!watched) {
291
+ return originalRegister.call(this, definition, registerOptions)
292
+ }
293
+
294
+ const prepared = fallback
295
+ ? wrapForFallback(definition, name, options)
296
+ : mode === 'route'
297
+ ? wrapForRoute(definition, name, routes[name], options)
298
+ : definition
299
+
300
+ try {
301
+ return originalRegister.call(this, prepared, registerOptions)
302
+ } catch (error) {
303
+ if (!isDuplicateToolError(error, name)) throw error
304
+
305
+ const existing = findExistingDefinition(this, name)
306
+ const existingOriginal = existing?.[ROUTER]?.primaryDefinition ?? existing
307
+
308
+ if (existing && sameDefinition(existingOriginal, definition)) {
309
+ log(`[coexist] identical duplicate ignored: ${name}`)
310
+ return () => {}
311
+ }
312
+
313
+ for (let index = 1; index <= 100; index += 1) {
314
+ const alias = aliasName(name, index)
315
+ const aliasDefinition = wrapForAlias(definition, alias, name, options)
316
+
317
+ try {
318
+ const disposeAlias = originalRegister.call(this, aliasDefinition, registerOptions)
319
+ const router = existing?.[ROUTER]
320
+ let backupEntry = null
321
+
322
+ if (router && typeof definition.execute === 'function') {
323
+ backupEntry = { definition, execute: definition.execute }
324
+ router.backups.push(backupEntry)
325
+ }
326
+
327
+ log(`[coexist] alias ${name} -> ${alias}`)
328
+ try {
329
+ options.onAlias?.(name, alias)
330
+ } catch {
331
+ // 诊断回调不能影响注册。
332
+ }
333
+
334
+ return () => {
335
+ if (router && backupEntry) {
336
+ const position = router.backups.indexOf(backupEntry)
337
+ if (position !== -1) router.backups.splice(position, 1)
338
+ }
339
+ disposeAlias()
340
+ }
341
+ } catch (aliasError) {
342
+ if (!isDuplicateToolError(aliasError, alias)) throw aliasError
343
+ }
344
+ }
345
+
346
+ throw error
347
+ }
348
+ }
349
+
350
+ globalThis.__dshCoexistPrototypePatched = true
351
+ log(
352
+ `[coexist] preload active (${auto ? 'auto' : `watch=${[...watchSet].join(',')}`}, mode=${mode})`,
353
+ )
354
+ return true
355
+ }
@@ -0,0 +1,231 @@
1
+ const PROVIDER_SUFFIX = '__coexist'
2
+
3
+ function isDuplicateAdapterError(error) {
4
+ if (error?.code === 'DUPLICATE_ADAPTER') return true
5
+ return /an adapter for provider ".*" is already registered/.test(String(error?.message ?? ''))
6
+ }
7
+
8
+ function isDuplicateDirectoryError(error) {
9
+ if (error?.code === 'DUPLICATE_DIRECTORY') return true
10
+ return /configurable provider ".*" is already (declared|registered)/.test(String(error?.message ?? ''))
11
+ }
12
+
13
+ function extractProvider(message) {
14
+ const match = /provider "([^"]+)" is already (?:registered|declared)/.exec(String(message ?? ''))
15
+ return match?.[1] ?? null
16
+ }
17
+
18
+ function aliasProvider(provider, index) {
19
+ return `${provider}${PROVIDER_SUFFIX}${index}`
20
+ }
21
+
22
+ function findFreeAlias(provider, used) {
23
+ for (let index = 1; index <= 100; index += 1) {
24
+ const candidate = aliasProvider(provider, index)
25
+ if (!used.has(candidate)) return candidate
26
+ }
27
+ return null
28
+ }
29
+
30
+ /**
31
+ * 代理 adapter:providerInfo 返回别名 id,其余方法在收到别名时自动换回原 provider。
32
+ * 这样插件自己的 adapter 代码不需要知道别名存在。
33
+ */
34
+ function proxyAdapter(adapter, reverse) {
35
+ return new Proxy(adapter, {
36
+ get(target, property) {
37
+ if (property === 'providerInfo') {
38
+ return (provider) => {
39
+ const original = reverse.get(provider) ?? provider
40
+ const info = target.providerInfo(original)
41
+ return { ...info, id: provider }
42
+ }
43
+ }
44
+
45
+ const value = Reflect.get(target, property, target)
46
+ if (typeof value !== 'function') return value
47
+ return (...args) => {
48
+ if (args.length > 0 && typeof args[0] === 'string' && reverse.has(args[0])) {
49
+ args[0] = reverse.get(args[0])
50
+ }
51
+ return value.apply(target, args)
52
+ }
53
+ },
54
+ })
55
+ }
56
+
57
+ function recordAlias(record, options) {
58
+ try {
59
+ options.onAlias?.(record)
60
+ } catch {
61
+ // 诊断回调不能影响宿主。
62
+ }
63
+ }
64
+
65
+ function recordBlocked(record, options) {
66
+ try {
67
+ options.onConflict?.({ ...record, resolution: 'blocked' })
68
+ } catch {
69
+ // 诊断回调不能影响宿主。
70
+ }
71
+ }
72
+
73
+ /**
74
+ * 在 LlmService 原型上包一层 provider 注册:
75
+ * - registerAdapter:provider 已被占用时,把后注册的 route 改成 `<provider>__coexistN`,
76
+ * 并用代理 adapter 在调用时换回原 provider;
77
+ * - registerConfigurableProviders:同样按 provider 别名处理。
78
+ *
79
+ * 别名只在宿主明确抛 DUPLICATE_* 时启用;其它错误原样上抛。
80
+ */
81
+ export function installProviderPatch(LlmService, options = {}) {
82
+ if (!LlmService || typeof LlmService.prototype?.registerAdapter !== 'function') {
83
+ return false
84
+ }
85
+ if (globalThis.__dshCoexistProviderPatched) return true
86
+
87
+ const log = options.log ?? (() => {})
88
+
89
+ const registerAdapter = LlmService.prototype.registerAdapter
90
+ LlmService.prototype.registerAdapter = function registerAdapterWithCoexist(providers, adapter) {
91
+ if (globalThis.__dshCoexistActive === false) {
92
+ return registerAdapter.call(this, providers, adapter)
93
+ }
94
+
95
+ let current = Array.isArray(providers) ? [...providers] : providers
96
+ const reverse = new Map()
97
+ let proxied = adapter
98
+
99
+ for (let attempt = 0; attempt <= 100; attempt += 1) {
100
+ try {
101
+ const dispose = registerAdapter.call(this, current, proxied)
102
+ for (const [alias, original] of reverse) {
103
+ log(`[coexist] provider alias: ${original} -> ${alias}`)
104
+ recordAlias({ kind: 'provider', name: original, alias }, options)
105
+ }
106
+ return dispose
107
+ } catch (error) {
108
+ if (!isDuplicateAdapterError(error)) {
109
+ if (reverse.size > 0) {
110
+ recordBlocked(
111
+ {
112
+ kind: 'provider',
113
+ name: [...reverse.values()].join(','),
114
+ message: error.message,
115
+ code: error.code ?? null,
116
+ },
117
+ options,
118
+ )
119
+ }
120
+ throw error
121
+ }
122
+
123
+ const conflict = extractProvider(error.message)
124
+ if (!conflict || !current.includes(conflict)) {
125
+ recordBlocked(
126
+ { kind: 'provider', name: conflict, message: error.message, code: error.code ?? null },
127
+ options,
128
+ )
129
+ throw error
130
+ }
131
+
132
+ const used = new Set([
133
+ ...current,
134
+ ...(this.adapters instanceof Map ? this.adapters.keys() : []),
135
+ ...reverse.keys(),
136
+ ])
137
+ const alias = findFreeAlias(conflict, used)
138
+ if (!alias) {
139
+ recordBlocked(
140
+ { kind: 'provider', name: conflict, message: 'no free alias', code: error.code ?? null },
141
+ options,
142
+ )
143
+ throw error
144
+ }
145
+
146
+ reverse.set(alias, conflict)
147
+ current = current.map((provider) => (provider === conflict ? alias : provider))
148
+ proxied = proxyAdapter(adapter, reverse)
149
+ }
150
+ }
151
+
152
+ throw new Error('coexist: provider alias attempts exhausted')
153
+ }
154
+
155
+ if (typeof LlmService.prototype.registerConfigurableProviders === 'function') {
156
+ const registerConfigurable = LlmService.prototype.registerConfigurableProviders
157
+ LlmService.prototype.registerConfigurableProviders = function registerConfigurableWithCoexist(
158
+ entries,
159
+ ) {
160
+ if (globalThis.__dshCoexistActive === false) {
161
+ return registerConfigurable.call(this, entries)
162
+ }
163
+
164
+ let current = Array.isArray(entries) ? [...entries] : entries
165
+ const reverse = new Map()
166
+
167
+ for (let attempt = 0; attempt <= 100; attempt += 1) {
168
+ try {
169
+ const dispose = registerConfigurable.call(this, current)
170
+ for (const [alias, original] of reverse) {
171
+ log(`[coexist] provider alias: ${original} -> ${alias}`)
172
+ recordAlias({ kind: 'provider', name: original, alias }, options)
173
+ }
174
+ return dispose
175
+ } catch (error) {
176
+ if (!isDuplicateDirectoryError(error)) {
177
+ if (reverse.size > 0) {
178
+ recordBlocked(
179
+ {
180
+ kind: 'provider',
181
+ name: [...reverse.values()].join(','),
182
+ message: error.message,
183
+ code: error.code ?? null,
184
+ },
185
+ options,
186
+ )
187
+ }
188
+ throw error
189
+ }
190
+
191
+ const conflict = extractProvider(error.message)
192
+ const entry = conflict
193
+ ? current.find((item) => item?.provider === conflict)
194
+ : null
195
+ if (!entry) {
196
+ recordBlocked(
197
+ { kind: 'provider', name: conflict, message: error.message, code: error.code ?? null },
198
+ options,
199
+ )
200
+ throw error
201
+ }
202
+
203
+ const used = new Set([
204
+ ...current.map((item) => item?.provider).filter(Boolean),
205
+ ...(this.directory instanceof Map ? this.directory.keys() : []),
206
+ ...reverse.keys(),
207
+ ])
208
+ const alias = findFreeAlias(conflict, used)
209
+ if (!alias) {
210
+ recordBlocked(
211
+ { kind: 'provider', name: conflict, message: 'no free alias', code: error.code ?? null },
212
+ options,
213
+ )
214
+ throw error
215
+ }
216
+
217
+ reverse.set(alias, conflict)
218
+ current = current.map((item) =>
219
+ item?.provider === conflict ? { ...item, provider: alias } : item,
220
+ )
221
+ }
222
+ }
223
+
224
+ throw new Error('coexist: configurable provider alias attempts exhausted')
225
+ }
226
+ }
227
+
228
+ globalThis.__dshCoexistProviderPatched = true
229
+ log(`[coexist] provider patch active (${LlmService.name ?? 'unknown'})`)
230
+ return true
231
+ }