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,912 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ export function defaultReportFile() {
6
+ const home = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
7
+ return (
8
+ process.env.DSH_COEXIST_REPORT ??
9
+ path.join(home, 'coexist', 'report.json')
10
+ )
11
+ }
12
+
13
+ function fiberName(fiber) {
14
+ try {
15
+ return typeof fiber?.name === 'string' ? fiber.name : null
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
21
+ function runtimeSink() {
22
+ return globalThis.__dshCoexistRuntime
23
+ }
24
+
25
+ function coexistActive() {
26
+ return globalThis.__dshCoexistActive !== false
27
+ }
28
+
29
+ /** 把失败原因归类,便于 report/CLI 用人话区分。 */
30
+ export function classifyFailure(message) {
31
+ const text = String(message ?? '')
32
+ if (!text) return 'runtime'
33
+ if (/must declare output|must declare.*schema|must be a function|timeoutMs|JsonSchema|invalid tool|invalid plugin/i.test(text)) {
34
+ return 'contract'
35
+ }
36
+ if (/service ".*" has been registered|is reserved|requires a scoped context/i.test(text)) {
37
+ return 'service'
38
+ }
39
+ if (/peer|ERESOLVE|Cannot find (module|package)|ERR_MODULE_NOT_FOUND/i.test(text)) {
40
+ return 'dependency'
41
+ }
42
+ return 'runtime'
43
+ }
44
+
45
+ function isServiceConflict(error, name) {
46
+ const message = error?.message
47
+ return (
48
+ typeof message === 'string' &&
49
+ message.includes(`service "${name}"`) &&
50
+ message.includes('has been registered')
51
+ )
52
+ }
53
+
54
+ function findImpl(store, name) {
55
+ if (!store || typeof store !== 'object') return null
56
+ // store 的键是 Symbol(每个 service 一个),Object.values 看不到。
57
+ for (const key of Reflect.ownKeys(store)) {
58
+ const impl = store[key]
59
+ if (impl?.name === name) return impl
60
+ }
61
+ return null
62
+ }
63
+
64
+ function isPlainRecord(value) {
65
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
66
+ const proto = Object.getPrototypeOf(value)
67
+ return proto === Object.prototype || proto === null
68
+ }
69
+
70
+ function collectPlainProps(value) {
71
+ const props = new Map()
72
+ for (const key of Object.keys(value)) {
73
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)
74
+ if (!descriptor || !('value' in descriptor)) return null
75
+ const raw = descriptor.value
76
+ props.set(key, typeof raw === 'function' ? raw.bind(value) : raw)
77
+ }
78
+ return props
79
+ }
80
+
81
+ /**
82
+ * 有限 service 代理:双方都必须是普通对象;访问器和类实例一律拒绝。
83
+ * 同名成员默认拒绝,除非显式选择 overlap='first' 或 'last'(不做语义合并)。
84
+ */
85
+ export function bridgeServiceValues(base, additions, options = {}) {
86
+ const overlap =
87
+ options.overlap === 'last' ? 'last' : options.overlap === 'first' ? 'first' : 'reject'
88
+ if (!isPlainRecord(base)) return null
89
+
90
+ const baseProps = collectPlainProps(base)
91
+ if (!baseProps) return null
92
+
93
+ const merged = {}
94
+ const used = new Set()
95
+ for (const [key, value] of baseProps) {
96
+ merged[key] = value
97
+ used.add(key)
98
+ }
99
+
100
+ for (const addition of additions) {
101
+ if (!isPlainRecord(addition)) return null
102
+ const props = collectPlainProps(addition)
103
+ if (!props) return null
104
+ for (const [key, value] of props) {
105
+ if (used.has(key)) {
106
+ if (overlap === 'reject') return null
107
+ if (overlap === 'first') continue
108
+ }
109
+ used.add(key)
110
+ merged[key] = value
111
+ }
112
+ }
113
+
114
+ return merged
115
+ }
116
+
117
+ /**
118
+ * 包住 ReflectService.provide:
119
+ * - 默认只记录 service 冲突,然后原样上抛;
120
+ * - serviceBridge=true 时,若双方都是属性不重叠的普通对象,则合并成一个代理,
121
+ * 第二个插件不再失败。其他情况仍然上抛。
122
+ */
123
+ export function installServiceProbe(ctx, options = {}) {
124
+ if (globalThis.__dshCoexistServiceProbeInstalled) return false
125
+
126
+ let reflect
127
+ try {
128
+ reflect = ctx.reflect
129
+ } catch {
130
+ return false
131
+ }
132
+ if (!reflect) return false
133
+
134
+ const ReflectService = Object.getPrototypeOf(reflect)?.constructor
135
+ if (!ReflectService || typeof ReflectService.prototype?.provide !== 'function') {
136
+ return false
137
+ }
138
+
139
+ const bridges = new Map()
140
+ let bridgeSequence = 0
141
+
142
+ const servicePolicies =
143
+ options.servicePolicies && typeof options.servicePolicies === 'object'
144
+ ? options.servicePolicies
145
+ : {}
146
+ const serviceMerge =
147
+ options.serviceMerge && typeof options.serviceMerge === 'object'
148
+ ? options.serviceMerge
149
+ : {}
150
+
151
+ const strategyFor = (name) => {
152
+ const entry = servicePolicies[name]
153
+ const strategy = typeof entry === 'string' ? entry : entry?.strategy
154
+ return strategy === 'bridge' || strategy === 'isolate' || strategy === 'block'
155
+ ? strategy
156
+ : null
157
+ }
158
+ const allowBridge = (name) =>
159
+ strategyFor(name) === 'bridge' ||
160
+ (strategyFor(name) === null && options.serviceBridge === true)
161
+ const allowIsolate = (name) =>
162
+ strategyFor(name) === 'isolate' ||
163
+ (strategyFor(name) === null && options.serviceIsolate === true)
164
+ const overlapFor = (name) =>
165
+ serviceMerge[name]?.overlap === 'first' || serviceMerge[name]?.overlap === 'last'
166
+ ? serviceMerge[name].overlap
167
+ : 'reject'
168
+
169
+ const notifyConflict = (conflict) => {
170
+ try {
171
+ options.onConflict?.(conflict)
172
+ } catch {
173
+ // 诊断回调不能影响宿主。
174
+ }
175
+ try {
176
+ runtimeSink()?.onServiceConflict?.(conflict)
177
+ } catch {
178
+ // 诊断回调不能影响宿主。
179
+ }
180
+ }
181
+
182
+ const original = ReflectService.prototype.provide
183
+
184
+ ReflectService.prototype.provide = function provideWithProbe(name, value, check) {
185
+ if (!coexistActive()) return original.call(this, name, value, check)
186
+
187
+ try {
188
+ return original.call(this, name, value, check)
189
+ } catch (error) {
190
+ try {
191
+ if (isServiceConflict(error, name)) {
192
+ const existing = findImpl(this.store, name)
193
+ const incomingOwner = fiberName(this.ctx?.fiber)
194
+ const existingOwner = fiberName(existing?.ctx?.fiber ?? existing?.fiber)
195
+
196
+ if (allowBridge(name) && existing) {
197
+ let record = bridges.get(name)
198
+ if (!record) {
199
+ record = { impl: existing, original: existing.value, layers: new Map() }
200
+ bridges.set(name, record)
201
+ }
202
+
203
+ const merged = bridgeServiceValues(
204
+ record.original,
205
+ [...record.layers.values(), value],
206
+ { overlap: overlapFor(name) },
207
+ )
208
+
209
+ if (merged) {
210
+ bridgeSequence += 1
211
+ const layerKey = `${incomingOwner ?? 'unknown'}#${bridgeSequence}`
212
+ record.layers.set(layerKey, value)
213
+ record.impl.value = merged
214
+ notifyConflict({
215
+ service: name,
216
+ existing: existingOwner,
217
+ incoming: incomingOwner,
218
+ message: error.message,
219
+ resolution: 'bridged',
220
+ })
221
+ options.log?.(
222
+ `[coexist] service bridged: ${name} (${existingOwner ?? '?'} + ${incomingOwner ?? '?'})`,
223
+ )
224
+ let cleaned = false
225
+ const cleanup = () => {
226
+ if (cleaned) return
227
+ cleaned = true
228
+ record.layers.delete(layerKey)
229
+ const rebuilt = bridgeServiceValues(
230
+ record.original,
231
+ [...record.layers.values()],
232
+ { overlap: overlapFor(name) },
233
+ )
234
+ record.impl.value = rebuilt ?? record.original
235
+ }
236
+
237
+ try {
238
+ this.ctx?.fiber?.effect?.(() => cleanup)
239
+ } catch {
240
+ // 没有 fiber.effect 时至少返回 disposer。
241
+ }
242
+ return cleanup
243
+ }
244
+ }
245
+
246
+ if (allowIsolate(name) && existing) {
247
+ const isolateSymbol = Symbol.for('cordis.isolate')
248
+ const ownerContext = this.ctx
249
+ const previousMap = ownerContext?.[isolateSymbol]
250
+
251
+ try {
252
+ const nextMap = Object.create(previousMap ?? null)
253
+ nextMap[name] = Symbol(`coexist:${name}:${incomingOwner ?? 'plugin'}`)
254
+ ownerContext[isolateSymbol] = nextMap
255
+ options.log?.(
256
+ `[coexist] service isolate attempt: ${name} for ${incomingOwner ?? '?'} (own=${Object.hasOwn(ownerContext ?? {}, isolateSymbol)})`,
257
+ )
258
+
259
+ const isolateDispose = original.call(this, name, value, check)
260
+ notifyConflict({
261
+ service: name,
262
+ existing: existingOwner,
263
+ incoming: incomingOwner,
264
+ message: error.message,
265
+ resolution: 'isolated',
266
+ })
267
+ options.log?.(
268
+ `[coexist] service isolated: ${name} for ${incomingOwner ?? '?'}`,
269
+ )
270
+ return isolateDispose
271
+ } catch (retryError) {
272
+ try {
273
+ ownerContext[isolateSymbol] = previousMap
274
+ } catch {
275
+ // 恢复失败时保持原样,继续按 blocked 处理。
276
+ }
277
+ options.log?.(`[coexist] service isolate failed: ${retryError.message}`)
278
+ }
279
+ }
280
+
281
+ notifyConflict({
282
+ service: name,
283
+ existing: existingOwner,
284
+ incoming: incomingOwner,
285
+ message: error.message,
286
+ resolution: 'blocked',
287
+ suggestion: `在 config.json 设置 services["${name}"].strategy 为 "bridge" 或 "isolate",或停用其中一个插件`,
288
+ })
289
+ }
290
+ } catch {
291
+ // 诊断本身永远不能影响宿主。
292
+ }
293
+ throw error
294
+ }
295
+ }
296
+
297
+ globalThis.__dshCoexistServiceProbeInstalled = true
298
+ options.log?.(
299
+ `[coexist] service probe active (${ReflectService.name}, bridge=${options.serviceBridge === true}, isolate=${options.serviceIsolate === true}, policies=${Object.keys(servicePolicies).length})`,
300
+ )
301
+ return true
302
+ }
303
+
304
+ /**
305
+ * 插件 apply 可能早于 coexist 的 apply,那一次 provide 冲突不会经过探针。
306
+ * 但失败 fiber 的错误消息里带着双方名字,可以直接还原。
307
+ */
308
+ export function deriveServiceConflicts(failures) {
309
+ const conflicts = []
310
+ for (const failure of failures ?? []) {
311
+ const match = /service "(.+?)" has been registered at <(.+?)>/.exec(failure?.error ?? '')
312
+ if (!match) continue
313
+ conflicts.push({
314
+ service: match[1],
315
+ existing: match[2],
316
+ incoming: failure.plugin ?? null,
317
+ message: failure.error,
318
+ })
319
+ }
320
+ return conflicts
321
+ }
322
+
323
+ function mergeServiceConflicts(primary, derived) {
324
+ const merged = [...primary]
325
+ for (const conflict of derived) {
326
+ const duplicate = merged.some(
327
+ (item) =>
328
+ item.service === conflict.service &&
329
+ item.existing === conflict.existing &&
330
+ item.incoming === conflict.incoming,
331
+ )
332
+ if (!duplicate) merged.push(conflict)
333
+ }
334
+ return merged
335
+ }
336
+
337
+ function missingServices(fiber) {
338
+ const inject = fiber?.inject && typeof fiber.inject === 'object' ? fiber.inject : null
339
+ if (!inject) return []
340
+ const store = fiber?._store && typeof fiber._store === 'object' ? fiber._store : {}
341
+ return Object.keys(inject).filter((name) => !store[name])
342
+ }
343
+
344
+ function failureSuggestion(kind, plugin, message) {
345
+ if (kind === 'service') {
346
+ return `在 config.json 设置 services 策略(bridge/isolate),或停用 ${plugin} 与其冲突的一方`
347
+ }
348
+ if (kind === 'dependency') {
349
+ return '对齐依赖版本,或使用 dsh-coexist apply --allow-peer-override 写入受控 override'
350
+ }
351
+ if (kind === 'contract') {
352
+ return '插件与当前 DSH 契约不兼容;运行 dsh-coexist matrix 检查版本,或停用该插件'
353
+ }
354
+ return message ? '查看 report.json 中的完整错误并对照宿主日志' : null
355
+ }
356
+
357
+ /** 扫描所有 fiber:失败(state 3)和卡住(state 0/1)的插件。 */
358
+ export function scanFibers(ctx) {
359
+ const failures = []
360
+ const pending = []
361
+ const seenFailures = new Set()
362
+ const seenPending = new Map()
363
+
364
+ let registry
365
+ try {
366
+ registry = ctx.registry
367
+ } catch {
368
+ return { failures, pending }
369
+ }
370
+ if (!registry || typeof registry.values !== 'function') {
371
+ return { failures, pending }
372
+ }
373
+
374
+ for (const runtime of registry.values()) {
375
+ const fibers = runtime?.fibers ?? []
376
+ for (const fiber of fibers) {
377
+ if (!fiber || fiber.uid === 0 || fiber.uid == null) continue
378
+ const plugin = fiberName(fiber)
379
+ if (!plugin) continue
380
+
381
+ if (fiber.state === 3) {
382
+ if (seenFailures.has(plugin)) continue
383
+ seenFailures.add(plugin)
384
+ const kind = classifyFailure(fiber._error?.message)
385
+ failures.push({
386
+ plugin,
387
+ state: 'failed',
388
+ kind,
389
+ error: fiber._error?.message ?? null,
390
+ suggestion: failureSuggestion(kind, plugin, fiber._error?.message),
391
+ })
392
+ continue
393
+ }
394
+
395
+ if (fiber.state === 0 || fiber.state === 1) {
396
+ const missing = missingServices(fiber)
397
+ const existing = seenPending.get(plugin)
398
+ if (existing) {
399
+ for (const name of missing) {
400
+ if (!existing.missing.includes(name)) existing.missing.push(name)
401
+ }
402
+ continue
403
+ }
404
+ const entry = {
405
+ plugin,
406
+ state: fiber.state === 1 ? 'loading' : 'pending',
407
+ missing,
408
+ suggestion:
409
+ missing.length > 0
410
+ ? `安装/启用提供 ${missing.join(', ')} 的 bundle,或给该插件配置 services 策略`
411
+ : null,
412
+ }
413
+ seenPending.set(plugin, entry)
414
+ pending.push(entry)
415
+ }
416
+ }
417
+ }
418
+
419
+ return { failures, pending }
420
+ }
421
+
422
+ const HOOK_RISK = [
423
+ {
424
+ re: /^tools\/pre-execute$/,
425
+ risk: 'high',
426
+ reason: '多个门禁监听器都可能拒绝调用,后注册者可能改变最终结果',
427
+ },
428
+ {
429
+ re: /^tools\/post-execute$/,
430
+ risk: 'high',
431
+ reason: '多个监听器都可能改写 content/value,后注册者可能覆盖前面的处理',
432
+ },
433
+ {
434
+ re: /^agent\/pre-step$/,
435
+ risk: 'high',
436
+ reason: '多个监听器都可能注入上下文或修改消息,容易重复注入',
437
+ },
438
+ {
439
+ re: /^(agent\/turn-stopping|agent\/request-error|session\/event)$/,
440
+ risk: 'medium',
441
+ reason: '多个监听器会按注册顺序全部执行,行为可能叠加',
442
+ },
443
+ ]
444
+
445
+ function hookRisk(event, listeners, prepend) {
446
+ const rule = HOOK_RISK.find((item) => item.re.test(event))
447
+ if (rule) {
448
+ return { risk: rule.risk, reason: rule.reason }
449
+ }
450
+ if (prepend > 0) {
451
+ return { risk: 'medium', reason: '存在 prepend 监听器,顺序与注册顺序相反' }
452
+ }
453
+ if (listeners > 3) {
454
+ return { risk: 'medium', reason: `${listeners} 个监听器共享同一事件,行为可能叠加` }
455
+ }
456
+ return { risk: 'low', reason: null }
457
+ }
458
+
459
+ /** 列出被多个插件监听的公开事件,并给出风险等级与配置建议。 */
460
+ export function scanEventHooks(ctx) {
461
+ let hooks
462
+ try {
463
+ hooks = ctx.events?._hooks
464
+ } catch {
465
+ return []
466
+ }
467
+ if (!hooks || typeof hooks !== 'object') return []
468
+
469
+ const result = []
470
+ for (const [event, list] of Object.entries(hooks)) {
471
+ if (event.startsWith('internal/')) continue
472
+ if (!Array.isArray(list) || list.length === 0) continue
473
+
474
+ const owners = [
475
+ ...new Set(
476
+ list
477
+ .map((hook) => fiberName(hook?.ctx?.fiber))
478
+ .filter((owner) => owner && owner !== 'coexist'),
479
+ ),
480
+ ]
481
+ if (owners.length < 2) continue
482
+
483
+ const prepend = list.filter((hook) => hook?.prepend === true).length
484
+ const judgement = hookRisk(event, list.length, prepend)
485
+ result.push({
486
+ event,
487
+ owners,
488
+ listeners: list.length,
489
+ prepend,
490
+ risk: judgement.risk,
491
+ reason: judgement.reason,
492
+ suggestion: `hooks["${event}"].order / disable`,
493
+ })
494
+ }
495
+
496
+ return result
497
+ }
498
+
499
+ function hookOwner(hook) {
500
+ return fiberName(hook?.ctx?.fiber)
501
+ }
502
+
503
+ /**
504
+ * 按配置对指定事件的监听器做排序/禁用:
505
+ * hooks: { "agent/pre-step": { order: ["plugin-a"], disable: ["plugin-b"] } }
506
+ * 只影响列出的公开事件;没有配置时不安装。
507
+ */
508
+ export function installHookPolicy(ctx, options = {}) {
509
+ if (globalThis.__dshCoexistHookPolicyInstalled) return false
510
+
511
+ let events
512
+ try {
513
+ events = ctx.events
514
+ } catch {
515
+ return false
516
+ }
517
+ const EventsService = events ? Object.getPrototypeOf(events)?.constructor : null
518
+ if (!EventsService || typeof EventsService.prototype?.dispatch !== 'function') {
519
+ return false
520
+ }
521
+
522
+ if (options.hooks && typeof options.hooks === 'object') {
523
+ globalThis.__dshCoexistHookPolicies = options.hooks
524
+ }
525
+
526
+ const original = EventsService.prototype.dispatch
527
+
528
+ EventsService.prototype.dispatch = function dispatchWithHookPolicy(type, args) {
529
+ const policies = globalThis.__dshCoexistHookPolicies ?? {}
530
+ const name =
531
+ typeof args[0] === 'object' || typeof args[0] === 'function' ? args[1] : args[0]
532
+ const policy = policies[name]
533
+ const hooks = this._hooks?.[name]
534
+
535
+ if (!policy || !Array.isArray(hooks)) return original.call(this, type, args)
536
+
537
+ const current = hooks.slice()
538
+ let next = current
539
+
540
+ if (Array.isArray(policy.disable) && policy.disable.length > 0) {
541
+ const disabled = new Set(policy.disable)
542
+ next = next.filter((hook) => !disabled.has(hookOwner(hook)))
543
+ }
544
+
545
+ if (Array.isArray(policy.order) && policy.order.length > 0) {
546
+ const rank = new Map(policy.order.map((owner, index) => [owner, index]))
547
+ next = [...next].sort((left, right) => {
548
+ const leftRank = rank.has(hookOwner(left))
549
+ ? rank.get(hookOwner(left))
550
+ : Number.MAX_SAFE_INTEGER
551
+ const rightRank = rank.has(hookOwner(right))
552
+ ? rank.get(hookOwner(right))
553
+ : Number.MAX_SAFE_INTEGER
554
+ return leftRank - rightRank
555
+ })
556
+ }
557
+
558
+ if (next.length === current.length && next.every((hook, index) => hook === current[index])) {
559
+ return original.call(this, type, args)
560
+ }
561
+
562
+ this._hooks[name] = next
563
+ try {
564
+ return original.call(this, type, args)
565
+ } finally {
566
+ this._hooks[name] = current
567
+ }
568
+ }
569
+
570
+ globalThis.__dshCoexistHookPolicyInstalled = true
571
+ const initial = options.hooks && typeof options.hooks === 'object' ? Object.keys(options.hooks) : []
572
+ if (initial.length > 0) {
573
+ options.log?.(`[coexist] hook policy active (${initial.join(', ')})`)
574
+ }
575
+ return true
576
+ }
577
+
578
+ /**
579
+ * 创建运行期诊断:service 冲突、失败/卡住的插件、多插件监听的事件。
580
+ * 报告写入 $DSH_HOME/coexist/report.json,默认启动 8 秒后写一次。
581
+ */
582
+ export function createDiagnostics(ctx, options = {}) {
583
+ const log = options.log ?? (() => {})
584
+ const reportFile = options.reportFile ?? defaultReportFile()
585
+ const delayMs = Number(options.delayMs ?? process.env.DSH_COEXIST_REPORT_DELAY_MS ?? 8000)
586
+ const mode =
587
+ options.mode === 'fallback' ? 'fallback' : options.mode === 'route' ? 'route' : 'alias'
588
+ const serviceBridge = options.serviceBridge === true
589
+ const serviceIsolate = options.serviceIsolate === true
590
+
591
+ const state = {
592
+ aliases: [],
593
+ fallbacks: [],
594
+ routes: [],
595
+ routeLogged: new Set(),
596
+ serviceConflicts: [],
597
+ commandAliases: [],
598
+ providerAliases: [],
599
+ providerConflicts: [],
600
+ toolCalls: [],
601
+ toolStats: {},
602
+ recoveries: [],
603
+ }
604
+
605
+ let timer = null
606
+ let initialTimer = null
607
+
608
+ const write = () => {
609
+ try {
610
+ const scan = scanFibers(ctx)
611
+ const serviceConflicts = mergeServiceConflicts(
612
+ state.serviceConflicts,
613
+ deriveServiceConflicts(scan.failures),
614
+ )
615
+ const report = {
616
+ generatedAt: new Date().toISOString(),
617
+ pid: process.pid,
618
+ mode,
619
+ tools: {
620
+ aliases: state.aliases,
621
+ fallbacks: state.fallbacks,
622
+ routes: state.routes,
623
+ calls: state.toolCalls,
624
+ stats: state.toolStats,
625
+ },
626
+ commands: { aliases: state.commandAliases },
627
+ providers: { aliases: state.providerAliases, conflicts: state.providerConflicts },
628
+ plan: options.plan ?? null,
629
+ capabilities: { ...(globalThis.__dshCoexistCapabilities ?? {}) },
630
+ recoveries: state.recoveries,
631
+ serviceConflicts,
632
+ failures: scan.failures,
633
+ pending: scan.pending,
634
+ eventHooks: scanEventHooks(ctx),
635
+ }
636
+
637
+ mkdirSync(path.dirname(reportFile), { recursive: true })
638
+ writeFileSync(reportFile, `${JSON.stringify(report, null, 2)}\n`)
639
+ log(
640
+ `[coexist] report: aliases=${report.tools.aliases.length} fallbacks=${report.tools.fallbacks.length} routes=${report.tools.routes.length} commandAliases=${report.commands.aliases.length} providerAliases=${report.providers.aliases.length} providerConflicts=${report.providers.conflicts.length} serviceConflicts=${report.serviceConflicts.length} failures=${report.failures.length} pending=${report.pending.length} eventHooks=${report.eventHooks.length} -> ${reportFile}`,
641
+ )
642
+ } catch (error) {
643
+ log(`[coexist] report failed: ${error.message}`)
644
+ }
645
+ }
646
+
647
+ const schedule = (delay = 2000) => {
648
+ if (timer || !reportFile) return
649
+ timer = setTimeout(() => {
650
+ timer = null
651
+ write()
652
+ }, delay)
653
+ timer.unref?.()
654
+ }
655
+
656
+ const recordServiceConflict = (conflict) => {
657
+ const duplicate = state.serviceConflicts.some(
658
+ (item) =>
659
+ item.service === conflict.service &&
660
+ item.existing === conflict.existing &&
661
+ item.incoming === conflict.incoming &&
662
+ item.resolution === conflict.resolution,
663
+ )
664
+ if (duplicate) return
665
+ state.serviceConflicts.push(conflict)
666
+ log(
667
+ `[coexist] service conflict: "${conflict.service}" already owned by ${conflict.existing ?? 'unknown'}, ${
668
+ conflict.resolution === 'bridged'
669
+ ? 'bridged with'
670
+ : conflict.resolution === 'isolated'
671
+ ? 'isolated for'
672
+ : 'rejected'
673
+ } ${conflict.incoming ?? 'unknown'}`,
674
+ )
675
+ schedule()
676
+ }
677
+
678
+ const recordAlias = (name, alias) => {
679
+ if (state.aliases.some((item) => item.name === name && item.alias === alias)) return
680
+ state.aliases.push({ name, alias })
681
+ schedule()
682
+ }
683
+
684
+ const recordAliasCall = (event) => {
685
+ const entry = state.aliases.find((item) => item.alias === event?.tool)
686
+ if (!entry) return
687
+ entry.calls = (entry.calls ?? 0) + 1
688
+ if (entry.calls === 1) {
689
+ log(`[coexist] alias call: ${entry.alias} (for ${entry.name})`)
690
+ }
691
+ schedule()
692
+ }
693
+
694
+ const recordFallback = (event) => {
695
+ state.fallbacks.push({
696
+ tool: event?.tool ?? null,
697
+ error: event?.error ?? null,
698
+ at: new Date().toISOString(),
699
+ })
700
+ if (state.fallbacks.length > 50) state.fallbacks.shift()
701
+ log(`[coexist] fallback: ${event?.tool ?? 'unknown'} -> backup (${event?.error ?? ''})`)
702
+ schedule()
703
+ }
704
+
705
+ const recordRoute = (event) => {
706
+ const entry = {
707
+ tool: event?.tool ?? null,
708
+ target: event?.target ?? null,
709
+ reason: event?.reason ?? null,
710
+ at: new Date().toISOString(),
711
+ }
712
+ state.routes.push(entry)
713
+ if (state.routes.length > 50) state.routes.shift()
714
+
715
+ const key = `${entry.tool}:${entry.target}`
716
+ if (!state.routeLogged.has(key)) {
717
+ state.routeLogged.add(key)
718
+ log(`[coexist] route: ${entry.tool} -> ${entry.target} (${entry.reason ?? 'rule'})`)
719
+ }
720
+ schedule()
721
+ }
722
+
723
+ const recordCommandAlias = (event) => {
724
+ if (!event?.name || !event?.alias) return
725
+ if (state.commandAliases.some((item) => item.name === event.name && item.alias === event.alias)) {
726
+ return
727
+ }
728
+ state.commandAliases.push({ name: event.name, alias: event.alias })
729
+ log(`[coexist] command alias recorded: /${event.name} -> /${event.alias}`)
730
+ schedule()
731
+ }
732
+
733
+ const recordProviderAlias = (event) => {
734
+ if (!event?.name || !event?.alias) return
735
+ if (state.providerAliases.some((item) => item.name === event.name && item.alias === event.alias)) {
736
+ return
737
+ }
738
+ state.providerAliases.push({ name: event.name, alias: event.alias })
739
+ log(`[coexist] provider alias recorded: ${event.name} -> ${event.alias}`)
740
+ schedule()
741
+ }
742
+
743
+ const recordProviderConflict = (event) => {
744
+ if (!event?.name) return
745
+ const duplicate = state.providerConflicts.some(
746
+ (item) => item.name === event.name && item.message === event.message,
747
+ )
748
+ if (duplicate) return
749
+ state.providerConflicts.push({
750
+ name: event.name,
751
+ message: event.message ?? null,
752
+ code: event.code ?? null,
753
+ resolution: event.resolution ?? 'blocked',
754
+ })
755
+ log(`[coexist] provider conflict: "${event.name}" (${event.resolution ?? 'blocked'})`)
756
+ schedule()
757
+ }
758
+
759
+ const recordToolCall = (event) => {
760
+ if (!event?.tool) return
761
+ const tool = String(event.tool)
762
+ const stat = state.toolStats[tool] ?? { calls: 0, errors: 0, blocked: 0, totalMs: 0 }
763
+ stat.calls += 1
764
+ stat.totalMs += Number(event.durationMs ?? 0)
765
+ if (event.error) stat.errors += 1
766
+ if (event.blocked) stat.blocked += 1
767
+ state.toolStats[tool] = stat
768
+
769
+ state.toolCalls.push({
770
+ tool,
771
+ agent: event.agent ?? null,
772
+ durationMs: Number(event.durationMs ?? 0),
773
+ blocked: event.blocked === true,
774
+ error: event.error ?? null,
775
+ at: new Date().toISOString(),
776
+ })
777
+ if (state.toolCalls.length > 50) state.toolCalls.shift()
778
+ schedule()
779
+ }
780
+
781
+ const recoverAttempted = new Set()
782
+
783
+ /**
784
+ * 可选:对失败的 fiber 各重试一次(opt-in,避免无限循环)。
785
+ * service 隔离/合并开启时,自动重试 service 冲突失败的插件:
786
+ * 插件并发加载时,冲突可能发生在探针安装之前,重试让隔离策略有机会生效。
787
+ */
788
+ const recoverNow = async () => {
789
+ const autoServiceRecover =
790
+ serviceBridge ||
791
+ serviceIsolate ||
792
+ Object.keys(options.servicePolicies ?? {}).length > 0
793
+ if (options.recover !== true && !autoServiceRecover) return []
794
+ let registry
795
+ try {
796
+ registry = ctx.registry
797
+ } catch {
798
+ return []
799
+ }
800
+ if (!registry || typeof registry.values !== 'function') return []
801
+
802
+ const retried = []
803
+ for (const runtime of registry.values()) {
804
+ for (const fiber of [...(runtime?.fibers ?? [])]) {
805
+ if (!fiber || fiber.state !== 3) continue
806
+ const plugin = fiberName(fiber)
807
+ if (!plugin || recoverAttempted.has(plugin)) continue
808
+ if (
809
+ options.recover !== true &&
810
+ !/service ".*" has been registered/.test(fiber._error?.message ?? '')
811
+ ) {
812
+ continue
813
+ }
814
+
815
+ recoverAttempted.add(plugin)
816
+ try {
817
+ // 启动失败后 fiber 已不再运行。释放它让 loader 重新初始化同一条 entry:
818
+ // 此时探针已装好,冲突会按 serviceBridge / serviceIsolate 策略处理。
819
+ // 没有 dispose 的宿主退化到 restart()。
820
+ if (fiber.uid !== null && fiber.uid !== 0 && typeof fiber.dispose === 'function') {
821
+ await fiber.dispose()
822
+ } else if (typeof fiber.restart === 'function') {
823
+ const result = fiber.restart()
824
+ if (result && typeof result.then === 'function') {
825
+ result.then(() => schedule(2000), () => schedule(2000))
826
+ }
827
+ }
828
+ state.recoveries.push({
829
+ plugin,
830
+ state: 'restarted',
831
+ at: new Date().toISOString(),
832
+ })
833
+ retried.push(plugin)
834
+ log(`[coexist] restarted failed plugin: ${plugin}`)
835
+ } catch (error) {
836
+ state.recoveries.push({
837
+ plugin,
838
+ state: 'retry-failed',
839
+ error: error?.message ?? String(error),
840
+ at: new Date().toISOString(),
841
+ })
842
+ }
843
+ }
844
+ }
845
+ if (retried.length > 0) schedule()
846
+ return retried
847
+ }
848
+
849
+ const sink = {
850
+ onAlias: recordAlias,
851
+ onAliasCall: recordAliasCall,
852
+ onFallback: recordFallback,
853
+ onRoute: recordRoute,
854
+ onServiceConflict: recordServiceConflict,
855
+ onCommandAlias: recordCommandAlias,
856
+ onProviderAlias: recordProviderAlias,
857
+ onProviderConflict: recordProviderConflict,
858
+ onToolCall: recordToolCall,
859
+ }
860
+
861
+ const hookPolicies =
862
+ options.hooks && typeof options.hooks === 'object' ? options.hooks : {}
863
+
864
+ globalThis.__dshCoexistActive = true
865
+ globalThis.__dshCoexistRuntime = sink
866
+ globalThis.__dshCoexistHookPolicies = hookPolicies
867
+
868
+ installServiceProbe(ctx, { log, serviceBridge, serviceIsolate })
869
+
870
+ try {
871
+ ctx.on('internal/status', () => schedule(2000))
872
+ } catch {
873
+ // 事件服务不可用时只保留定时报告。
874
+ }
875
+
876
+ installHookPolicy(ctx, { hooks: hookPolicies, log })
877
+
878
+ initialTimer = setTimeout(async () => {
879
+ write()
880
+ await recoverNow()
881
+ }, Math.max(1000, delayMs))
882
+ initialTimer.unref?.()
883
+
884
+ return {
885
+ reportFile,
886
+ write,
887
+ recordAlias,
888
+ recordAliasCall,
889
+ recordFallback,
890
+ recordRoute,
891
+ recordCommandAlias,
892
+ recordProviderAlias,
893
+ recordProviderConflict,
894
+ recordToolCall,
895
+ recoverNow,
896
+ dispose() {
897
+ if (timer) clearTimeout(timer)
898
+ if (initialTimer) clearTimeout(initialTimer)
899
+ timer = null
900
+ initialTimer = null
901
+
902
+ if (globalThis.__dshCoexistRuntime === sink) {
903
+ delete globalThis.__dshCoexistRuntime
904
+ globalThis.__dshCoexistActive = false
905
+ }
906
+ if (globalThis.__dshCoexistHookPolicies === hookPolicies) {
907
+ delete globalThis.__dshCoexistHookPolicies
908
+ }
909
+ delete globalThis.__dshCoexistCapabilities
910
+ },
911
+ }
912
+ }