@sublane/core 0.1.3 → 0.3.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.
package/README.md CHANGED
@@ -7,3 +7,26 @@ Sublane 框架核心——视频字幕翻译能力的宿主契约层。Apache-2.
7
7
  - 总览与 quick start:[Sublane 仓库 README](https://github.com/ai-baymax-dabai/sublane/tree/master/video-subtitle-translation)
8
8
  - 接入指南:[docs/integration.md](https://github.com/ai-baymax-dabai/sublane/blob/master/video-subtitle-translation/docs/integration.md)
9
9
  - 公共 API(semver 承诺):仓库 README "Public API" 节——导出清单被 `release-gates.test.ts` 冻结
10
+
11
+ ## detached 渲染会话(0.2.0,F-27)
12
+
13
+ 把供应商引擎当**可复用渲染器**:在宿主提供的任意 `<video>` 元素上,用宿主注入的字幕轨数据(原文+可选译文)以 vendor 原生 UI 渲染双语字幕——数据面与渲染面解耦(提案:docs/integrations/2026-11-17-replaychannel-proposal.md;裁决:docs/integrations/2026-11-18-replaychannel-adjudication.md)。
14
+
15
+ ```ts
16
+ import { createDetachedSession } from '@sublane/core'
17
+
18
+ const session = await createDetachedSession({
19
+ ctx: { onInvalidated: () => {} }, // 宿主会话生命周期(如 Modal 关闭)
20
+ plugins, // 你的插件数组(与 live 同一批)
21
+ storage: frameworkStoragePort, // 复用同一配置键与车道算法
22
+ video: hostVideoElement, // 宿主提供的任意 video 元素
23
+ source: { getTrack: async () => ({ cues }) },// 注入轨:SubtitleCue[](含可选译文)
24
+ freezeConfig: false, // settings 实时跟随框架键;true=快照冻结
25
+ })
26
+ // session.handles: Map<SupplierId, DetachedHandle>——不支持 detached 的供应商如实缺席(宿主降级)
27
+ // session.dispose(): 会话结束全量卸载
28
+ ```
29
+
30
+ - **信任边界**:注入轨按 `TRACK_LIMITS` 契约默认校验(≤20,000 cues/≤4MB/≤4096 字符每 cue),per-supplier 覆盖经 `limits` 选项;超限拒载报 `REPLAY_TRACK_LIMIT`。
31
+ - **语义要点**:时间权威=宿主 video 的 currentTime(R3);缺译→原文行、无 pending 态(R5);`allowVendorTranslation=false` 不触发 vendor 翻译(N4);detached ctx 的 `emitConfigPatch` 中立化(M1)。
32
+ - **供应商支持矩阵**:read-frog ✅(0.2.0);fluent-read 🚧(P1 进行中)。不支持者缺席于 handles,宿主按 A8 降级。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublane/core",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "exports": {
package/src/contract.ts CHANGED
@@ -28,6 +28,9 @@ export interface VideoSubtitleCapabilities {
28
28
  bilingualDownload: boolean
29
29
  sidebar: boolean
30
30
  manualTimingOffset: boolean
31
+ /** 本版支持 detached 渲染(0.2.0,F-27);宿主 feature-detect 的首选旗标(§7-4),
32
+ * 方法存在性探测仅作兜底。供应商实现 createDetachedInstance 后置位。 */
33
+ detachedRender?: boolean
31
34
  }
32
35
 
33
36
  export type SettingsField =
@@ -60,6 +63,21 @@ export interface VideoSubtitlePluginInstance {
60
63
  mount(): void | Promise<void>
61
64
  unmount(): void | Promise<void>
62
65
  setConfig(config: SupplierRuntimeConfig): void
66
+ /** 0.3.0 可选(F-26, cue 只读数据事件流):订阅本实例的 cue 数据(原文+已得译文)。
67
+ * 语义:订阅即发一次 'reset'(当前已得全量);此后按 vendor 翻译节奏发 'upsert'(增量);
68
+ * 导航/轨重置发 'reset'。只读——宿主不得回写;翻译节奏归 vendor(宿主订阅即可,无按需命令)。
69
+ * provenance:engine 为产出译文的引擎/服务标识(vendor 自述,可缺省)。
70
+ * 不支持时缺席(宿主 feature-detect,同 A8 纪律)。 */
71
+ subscribeCues?(listener: (event: CueStreamEvent) => void): () => void
72
+ }
73
+
74
+ /** cue 数据事件(F-26/0.3.0):'reset' = cues 为当前全量快照;'upsert' = cues 为新增/变更增量。
75
+ * cue 形状复用 SubtitleCue(与 F-27 detached 注入同词汇表——F-26 流出/F-27 流入共用,裁决回函 §四)。 */
76
+ export interface CueStreamEvent {
77
+ type: 'reset' | 'upsert'
78
+ cues: SubtitleCue[]
79
+ /** provenance:本批译文产出引擎(vendor 自述,可缺省) */
80
+ engine?: string
63
81
  }
64
82
 
65
83
  /** 供应商对宿主 manifest 的声明式需求;宿主装配 manifest 时取并集(构建期读取,声明模块必须零浏览器依赖) */
@@ -83,6 +101,17 @@ export interface VideoSubtitlePlugin {
83
101
  matches: string[]
84
102
  }>
85
103
  createInstance(ctx: PluginMountContext): VideoSubtitlePluginInstance
104
+ /** 0.2.0 可选(F-27/P1):在宿主提供的任意 video 元素上创建**独立的**渲染实例。
105
+ * 语义要求:与 live mount 并存(R1,状态零共享);共享 settings 解析/样式注入/布局
106
+ * 代码路径(R2,禁止 detached 专用样式常量);注入轨视为 untrusted(R4,超限拒载);
107
+ * live 行为零变化(N2)。不支持时缺席于 session.handles(宿主按 A8 降级)。
108
+ * ctx.emitConfigPatch 已被编排器中立化(M1)——detached 的 settings 权威在框架键。 */
109
+ createDetachedInstance?(
110
+ ctx: DetachedInstanceContext,
111
+ video: HTMLVideoElement,
112
+ source: TrackSource,
113
+ options?: DetachedMountOptions,
114
+ ): Promise<VideoSubtitlePluginInstance & { detach(): DetachedHandle }>
86
115
  }
87
116
 
88
117
  /** background 侧:一个扩展只有一个 service worker,供应商在此登记私产后端 */
@@ -102,3 +131,54 @@ export interface FrameworkStoragePort {
102
131
  * 等对端 onDisconnect 未必到来)。框架在重试前调用。 */
103
132
  reset?(): void
104
133
  }
134
+
135
+ // ── detached 渲染会话契约(0.2.0,F-27,ReplayChannel P0)──────────────────
136
+ // 设计文档:docs/integrations/2026-11-17-replaychannel-proposal.md;裁决回函:
137
+ // docs/integrations/2026-11-18-replaychannel-adjudication.md(Q1-Q8 裁决 + M1/M2 修订 + Q9)。
138
+
139
+ /** 注入轨的标准 cue 形状(P0)。时间语义:活跃区间 = [tsMs, tsMs + durationMs);
140
+ * durationMs 缺省按下一条 tsMs 推断,末条视为播到轨终点。与 fluent
141
+ * VideoSubtitleCue{startMs,durationMs,text} 和 read-frog
142
+ * SubtitlesFragment{text,start,end,translation?} 可无损互转(契约测试夹具义务)。 */
143
+ export interface SubtitleCue {
144
+ tsMs: number
145
+ durationMs?: number
146
+ original: string
147
+ /** 按 SupplierId 的译文;缺项/null = 该家未译(detached 渲染降级为原文行,无 pending 态,R5) */
148
+ translations?: Partial<Record<SupplierId, string | null>>
149
+ }
150
+
151
+ /** 数据注入源(P0)。宿主实现;vendor 消费。getTrack 可返回 null(暂无轨 = 空渲染);
152
+ * onUpdate 用于流式补译/追加(返回取消监听函数)。 */
153
+ export interface TrackSource {
154
+ getTrack(): Promise<{ cues: SubtitleCue[] } | null>
155
+ onUpdate?(cb: (track: { cues: SubtitleCue[] }) => void): () => void
156
+ /** 默认 false:注入轨自带译文即渲染,不触发 vendor 翻译请求(N4,防隐性调用量) */
157
+ allowVendorTranslation?: boolean
158
+ }
159
+
160
+ export interface DetachedMountOptions {
161
+ /** injected-only(默认):纯注入数据渲染;hybrid 远期(P2 后另议,Q7 裁决不入 0.2.0) */
162
+ dataMode?: 'injected-only'
163
+ /** 宿主侧取消信号(如 Modal 关闭);abort 即全量卸载 */
164
+ signal?: AbortSignal
165
+ }
166
+
167
+ /** detached 会话对宿主暴露的生命周期句柄;unmount 与 setSource 均不重挂 DOM 之外的对象 */
168
+ export interface DetachedHandle {
169
+ unmount(): void | Promise<void>
170
+ /** 替换数据源(如切换 Clip 区间);不重挂 DOM */
171
+ setSource(source: TrackSource): void
172
+ }
173
+
174
+ /** detached 会话上下文:与 live PluginMountContext 同形,但编排器已将 emitConfigPatch
175
+ * 中立化为空实现(M1)——detached 的 settings 权威在框架键,实例不得回写(防污染 live)。 */
176
+ export interface DetachedInstanceContext extends PluginMountContext {}
177
+
178
+ /** 信任边界上限(R4):契约默认沿用 fluent 页面注入既有上限(≤20,000 cues / ≤4MB / ≤4096 字符每 cue);
179
+ * per-supplier 覆盖经 createDetachedSession 的 limits 选项(M3/Q9) */
180
+ export interface TrackLimits {
181
+ maxCues: number
182
+ maxTotalBytes: number
183
+ maxCharsPerCue: number
184
+ }
package/src/runtime.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * 模块边界:零 DOM、零字幕业务逻辑(宪法 NO-3);只编排实例生命周期,渲染/翻译/抓取全部归供应商。
7
7
  */
8
8
  import type {
9
- FrameworkStoragePort, PluginMountContext, SupplierRuntimeConfig,
9
+ FrameworkStoragePort, PluginMountContext, SupplierRuntimeConfig, LaneAssignment,
10
10
  VideoSubtitlePlugin, VideoSubtitlePluginInstance,
11
+ SubtitleCue, TrackSource, DetachedMountOptions, DetachedHandle, DetachedInstanceContext, TrackLimits,
11
12
  } from './contract.ts'
12
13
 
13
14
  export const FRAMEWORK_STORAGE_KEY = 'sublane:plugins.videoSubtitle'
@@ -43,6 +44,46 @@ export function unionMatches(plugins: Array<Pick<VideoSubtitlePlugin, 'capabilit
43
44
  return [...matches]
44
45
  }
45
46
 
47
+ /** 诊断标记:仅浏览器环境写 dataset(框架零 DOM 约束;node:test 无 document)。
48
+ * 作用域在模块层:live 框架与 detached 会话(F-27)共用;曾定义在 readConfig 体内,
49
+ * 降级自愈越作用域引用即 ReferenceError 崩死(0.1.3 修复 F-25)——提升至此杜绝复发。 */
50
+ function makeBootMarker(): (name: string) => void {
51
+ return (name: string) => {
52
+ if (typeof document === 'undefined') return
53
+ const el = document.documentElement
54
+ el.dataset.sublaneBoot = `${el.dataset.sublaneBoot ?? ''}|rc:${name}`.slice(-400)
55
+ }
56
+ }
57
+
58
+ /** 框架配置读取:重试/降级逻辑(live 框架与 detached 会话共用,F-27/0.2.0)。 */
59
+ async function readFrameworkConfig(storage: FrameworkStoragePort, mark: (name: string) => void): Promise<{ config: FrameworkConfig; degraded: boolean }> {
60
+ mark('get-begin')
61
+ // 存储端口是可靠性单点(中继 Port 可能因 SW 冷启动/休眠变僵尸:请求无应答且不触发
62
+ // onDisconnect;或 SW 断线瞬间请求在途被 reject)。单次读取限时 1.5s,超时或拒绝均
63
+ // reset() 立即重建通道再重试,共 3 次——拒绝若逃逸会经 onChange→applyConfig 路径变
64
+ // uncaught(真机 Errors 页实证),此处按可重试吸收;最坏 ~4.5s 内拿到配置或判空继续,
65
+ // storagePort.onChange 在端口恢复后仍会触发 applyConfig 补挂载(鲁棒:不信任任何未验证假设)。
66
+ for (let attempt = 1; attempt <= 3; attempt += 1) {
67
+ const saved = (await Promise.race([
68
+ storage.get(FRAMEWORK_STORAGE_KEY).catch((error: Error) => {
69
+ mark(`get-rejected:${attempt}:${error?.message?.slice(0, 24) ?? 'unknown'}`)
70
+ return 'REJECTED' as const
71
+ }),
72
+ new Promise<'TIMEOUT'>((resolve) => setTimeout(() => resolve('TIMEOUT'), 1500)),
73
+ ])) as FrameworkConfig | 'TIMEOUT' | 'REJECTED' | undefined
74
+ if (saved === 'TIMEOUT' || saved === 'REJECTED') {
75
+ if (saved === 'TIMEOUT') mark(`get-timeout:${attempt}`)
76
+ storage.reset?.()
77
+ continue
78
+ }
79
+ mark(`get-done:${saved ? Object.keys(saved.suppliers ?? {}).join('+') || 'empty' : 'null'}`)
80
+ if (!saved || typeof saved !== 'object') return { config: { version: 1, suppliers: {} }, degraded: false }
81
+ return { config: saved, degraded: false }
82
+ }
83
+ mark('get-exhausted')
84
+ return { config: { version: 1, suppliers: {} }, degraded: true }
85
+ }
86
+
46
87
  export interface CreateFrameworkOptions {
47
88
  ctx: { onInvalidated(cb: () => void): void }
48
89
  plugins: VideoSubtitlePlugin[]
@@ -57,43 +98,12 @@ export function createVideoSubtitleFramework({ ctx, plugins, storage: storagePor
57
98
  * 只能靠存储变更事件才恢复——而卡死场景恰恰没有事件。降阶后有限退避重读,SW 恢复
58
99
  * 即自动点亮,无需用户刷新)。 */
59
100
  let readDegraded = false
60
- // 诊断标记:仅浏览器环境写 dataset(框架零 DOM 约束;node:test 无 document)。
61
- // 作用域必须在工厂体:recoverDegradedRead 亦引用之——曾定义在 readConfig 体内,
62
- // 自愈首轮即 ReferenceError 崩死(空配置永久化,VA 真机实证),0.1.3 修复。
63
- const mark = (name: string) => {
64
- if (typeof document === 'undefined') return
65
- const el = document.documentElement
66
- el.dataset.sublaneBoot = `${el.dataset.sublaneBoot ?? ''}|rc:${name}`.slice(-400)
67
- }
101
+ const mark = makeBootMarker()
68
102
 
69
103
  async function readConfig(): Promise<FrameworkConfig> {
70
- mark('get-begin')
71
- // 存储端口是可靠性单点(中继 Port 可能因 SW 冷启动/休眠变僵尸:请求无应答且不触发
72
- // onDisconnect;或 SW 断线瞬间请求在途被 reject)。单次读取限时 1.5s,超时或拒绝均
73
- // reset() 立即重建通道再重试,共 3 次——拒绝若逃逸会经 onChange→applyConfig 路径变
74
- // uncaught(真机 Errors 页实证),此处按可重试吸收;最坏 ~4.5s 内拿到配置或判空继续,
75
- // storagePort.onChange 在端口恢复后仍会触发 applyConfig 补挂载(鲁棒:不信任任何未验证假设)。
76
- for (let attempt = 1; attempt <= 3; attempt += 1) {
77
- const saved = (await Promise.race([
78
- storagePort.get(FRAMEWORK_STORAGE_KEY).catch((error: Error) => {
79
- mark(`get-rejected:${attempt}:${error?.message?.slice(0, 24) ?? 'unknown'}`)
80
- return 'REJECTED' as const
81
- }),
82
- new Promise<'TIMEOUT'>((resolve) => setTimeout(() => resolve('TIMEOUT'), 1500)),
83
- ])) as FrameworkConfig | 'TIMEOUT' | 'REJECTED' | undefined
84
- if (saved === 'TIMEOUT' || saved === 'REJECTED') {
85
- if (saved === 'TIMEOUT') mark(`get-timeout:${attempt}`)
86
- storagePort.reset?.()
87
- continue
88
- }
89
- mark(`get-done:${saved ? Object.keys(saved.suppliers ?? {}).join('+') || 'empty' : 'null'}`)
90
- readDegraded = false
91
- if (!saved || typeof saved !== 'object') return { version: 1, suppliers: {} }
92
- return saved
93
- }
94
- mark('get-exhausted')
95
- readDegraded = true
96
- return { version: 1, suppliers: {} }
104
+ const { config, degraded } = await readFrameworkConfig(storagePort, mark)
105
+ readDegraded = degraded
106
+ return config
97
107
  }
98
108
 
99
109
  function mountInstance(plugin: VideoSubtitlePlugin, config: SupplierRuntimeConfig) {
@@ -182,3 +192,137 @@ export function createVideoSubtitleFramework({ ctx, plugins, storage: storagePor
182
192
  },
183
193
  }
184
194
  }
195
+
196
+ // ── detached 渲染会话(0.2.0,F-27,ReplayChannel P0)─────────────────────────
197
+ // 裁决回函:docs/integrations/2026-11-18-replaychannel-adjudication.md(Q1-Q8 裁决 + M1/M2 修订 + Q9)。
198
+ // 宪法边界:本节零 DOM(video 元素由宿主传入)、零字幕业务逻辑;编排=配置读取+车道分配+实例装配+生命周期。
199
+
200
+ /** 契约默认信任边界(R4,沿用 fluent 页面注入既有上限);per-supplier 覆盖经 limits 选项(M3/Q9) */
201
+ export const TRACK_LIMITS: TrackLimits = { maxCues: 20_000, maxTotalBytes: 4 * 1024 * 1024, maxCharsPerCue: 4096 }
202
+
203
+ /** 超限错误:code 恒为 'REPLAY_TRACK_LIMIT',消费方按 code 判别(勿依赖类型链)。
204
+ * 注意:本仓测试走 node --experimental-strip-types(strip-only),禁用参数属性等不可擦除语法。 */
205
+ export class ReplayTrackLimitError extends Error {
206
+ override name = 'ReplayTrackLimitError'
207
+ readonly code = 'REPLAY_TRACK_LIMIT' as const
208
+ readonly axis: keyof TrackLimits
209
+ readonly limit: number
210
+ readonly actual: number
211
+ constructor(axis: keyof TrackLimits, limit: number, actual: number) {
212
+ super(`REPLAY_TRACK_LIMIT: ${axis} 实际 ${actual} 超限 ${limit}`)
213
+ this.axis = axis
214
+ this.limit = limit
215
+ this.actual = actual
216
+ }
217
+ }
218
+
219
+ /** 信任边界校验(R4):注入 cue 视为 untrusted,三轴判超限,超限抛 ReplayTrackLimitError */
220
+ export function validateTrackCues(cues: SubtitleCue[], limits: Partial<TrackLimits> = {}): void {
221
+ const lim: TrackLimits = { ...TRACK_LIMITS, ...limits }
222
+ if (cues.length > lim.maxCues) throw new ReplayTrackLimitError('maxCues', lim.maxCues, cues.length)
223
+ const enc = new TextEncoder()
224
+ let totalBytes = 0
225
+ for (const cue of cues) {
226
+ if (cue.original.length > lim.maxCharsPerCue) throw new ReplayTrackLimitError('maxCharsPerCue', lim.maxCharsPerCue, cue.original.length)
227
+ totalBytes += enc.encode(cue.original).length
228
+ if (cue.translations) for (const t of Object.values(cue.translations)) if (t != null) totalBytes += enc.encode(t).length
229
+ if (totalBytes > lim.maxTotalBytes) throw new ReplayTrackLimitError('maxTotalBytes', lim.maxTotalBytes, totalBytes)
230
+ }
231
+ }
232
+
233
+ export interface CreateDetachedSessionOptions {
234
+ ctx: { onInvalidated(cb: () => void): void }
235
+ plugins: VideoSubtitlePlugin[]
236
+ storage: FrameworkStoragePort
237
+ video: HTMLVideoElement
238
+ source: TrackSource
239
+ options?: DetachedMountOptions
240
+ /** true = 挂载时快照 settings 并冻结;false/缺省 = 实时跟随框架键(onChange→setConfig,与 live 一致) */
241
+ freezeConfig?: boolean
242
+ /** per-supplier 信任边界覆盖(M3/Q9):缺省用 TRACK_LIMITS;超限者拒载(缺席 handles),他者不受影响 */
243
+ limits?: Partial<Record<string, Partial<TrackLimits>>>
244
+ log?: (msg: string) => void
245
+ }
246
+
247
+ export interface DetachedSession {
248
+ /** 仅含 enabled 且支持 createDetachedInstance 且信任边界通过者的句柄;其余如实缺席(A8/R7) */
249
+ handles: Map<string, DetachedHandle>
250
+ dispose(): Promise<void>
251
+ }
252
+
253
+ /** detached 渲染会话编排器(F-27/P0):「配置读取+车道分配+实例装配+生命周期」在宿主注入场景的重放。
254
+ * 零 DOM(video 由宿主传入);settings 权威在框架键(Q2);车道按 detached 参与者分配(G4),热更不重排(M2/Q3)。 */
255
+ export async function createDetachedSession(opts: CreateDetachedSessionOptions): Promise<DetachedSession> {
256
+ const { ctx, plugins, storage, video, source, options, freezeConfig = false, limits = {}, log = () => {} } = opts
257
+ const mark = makeBootMarker()
258
+ const records: Array<{ id: string; instance: VideoSubtitlePluginInstance; handle: DetachedHandle; lane: LaneAssignment }> = []
259
+ const handles = new Map<string, DetachedHandle>()
260
+ let offChange: (() => void) | null = null
261
+ let disposed = false
262
+ const dispose = async (): Promise<void> => {
263
+ if (disposed) return
264
+ disposed = true
265
+ offChange?.()
266
+ for (const r of records) {
267
+ await Promise.resolve(r.handle.unmount()).catch((error: unknown) => log(`[${r.id}] detached unmount 失败:${error instanceof Error ? error.message : error}`))
268
+ }
269
+ records.length = 0
270
+ handles.clear()
271
+ }
272
+
273
+ // 配置读取:复用 live 同款重试/降级逻辑。降级 → suppliers 空 → handles 空(如实上报宿主,
274
+ // 宿主可重建会话重试);detached 会话生命周期短(如 Modal),不挂 live 的自愈循环。
275
+ const { config: frameworkConfig, degraded } = await readFrameworkConfig(storage, mark)
276
+ if (degraded) log('detached 会话:框架配置读取降级——handles 为空,请重建会话重试')
277
+ const enabledIds = new Set(Object.entries(frameworkConfig.suppliers ?? {}).filter(([, e]) => e.enabled).map(([id]) => id))
278
+ // feature-detect(A8):enabled 且实现 createDetachedInstance 者参与;其余如实缺席不抛
279
+ const capable = plugins.filter((p): p is VideoSubtitlePlugin & { createDetachedInstance: NonNullable<VideoSubtitlePlugin['createDetachedInstance']> } => enabledIds.has(p.id) && typeof p.createDetachedInstance === 'function')
280
+
281
+ // pass 1 信任边界预检(R4/M3):per-supplier 限额,超限者拒载(缺席+日志),他者不受影响(R7/A7)
282
+ const admitted: typeof capable = []
283
+ for (const plugin of capable) {
284
+ try {
285
+ const track = await source.getTrack()
286
+ if (track) validateTrackCues(track.cues, limits[plugin.id])
287
+ admitted.push(plugin)
288
+ } catch (error) {
289
+ const code = error instanceof ReplayTrackLimitError ? 'REPLAY_TRACK_LIMIT' : 'GET_TRACK_FAILED'
290
+ log(`[${plugin.id}] detached 预检失败(${code}):${error instanceof Error ? error.message : error}——该家拒载,其余不受影响`)
291
+ }
292
+ }
293
+
294
+ // pass 2 车道分配(算法同 applyConfig:133-139)+ 实例创建
295
+ for (const [index, plugin] of admitted.entries()) {
296
+ const lane = { index, count: admitted.length }
297
+ const ctxForDetached: DetachedInstanceContext = {
298
+ contentScript: ctx,
299
+ config: { enabled: true, lane, settings: frameworkConfig.suppliers[plugin.id]?.settings ?? {} },
300
+ emitConfigPatch: () => {}, // M1:中立化——detached 的 settings 权威在框架键,实例不得回写
301
+ }
302
+ const instance = await plugin.createDetachedInstance(ctxForDetached, video, source, options)
303
+ await Promise.resolve(instance.mount()).catch((error: unknown) => log(`[${plugin.id}] detached mount 失败:${error instanceof Error ? error.message : error}`))
304
+ const handle = instance.detach()
305
+ records.push({ id: plugin.id, instance, handle, lane })
306
+ handles.set(plugin.id, handle)
307
+ }
308
+
309
+ // 热更(Q2 默认跟随 + M2 lane 保留):onChange → 仅替换 settings,lane 以 detached 分配为准(Q3:重排靠重建会话)
310
+ if (!freezeConfig && admitted.length > 0) {
311
+ offChange = storage.onChange((key) => {
312
+ if (key !== FRAMEWORK_STORAGE_KEY || disposed) return
313
+ void (async () => {
314
+ const { config: next } = await readFrameworkConfig(storage, mark)
315
+ for (const r of records) {
316
+ const entry = next.suppliers[r.id]
317
+ if (!entry?.enabled) { log(`[${r.id}] detached 会话内 disabled——忽略(变更参与集请重建会话,Q3)`); continue }
318
+ r.instance.setConfig({ enabled: true, lane: r.lane, settings: entry.settings ?? {} })
319
+ }
320
+ })().catch((error: unknown) => log(`detached 热更失败:${error instanceof Error ? error.message : error}`))
321
+ })
322
+ }
323
+
324
+ ctx.onInvalidated(() => { void dispose() })
325
+ options?.signal?.addEventListener('abort', () => { void dispose() }, { once: true })
326
+ if (options?.signal?.aborted) void dispose()
327
+ return { handles, dispose }
328
+ }