@lokvis/runtime 0.2.2 → 0.4.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.
Files changed (125) hide show
  1. package/dist/asset-store.d.ts +13 -0
  2. package/dist/asset-store.d.ts.map +1 -1
  3. package/dist/asset-store.js +15 -2
  4. package/dist/asset-store.js.map +1 -1
  5. package/dist/batch-processor.d.ts +32 -161
  6. package/dist/batch-processor.d.ts.map +1 -1
  7. package/dist/batch-processor.js +107 -333
  8. package/dist/batch-processor.js.map +1 -1
  9. package/dist/batch-progress.d.ts +94 -0
  10. package/dist/batch-progress.d.ts.map +1 -0
  11. package/dist/batch-progress.js +128 -0
  12. package/dist/batch-progress.js.map +1 -0
  13. package/dist/batch-scheduler.d.ts +70 -0
  14. package/dist/batch-scheduler.d.ts.map +1 -0
  15. package/dist/batch-scheduler.js +147 -0
  16. package/dist/batch-scheduler.js.map +1 -0
  17. package/dist/browser-detect.d.ts +115 -0
  18. package/dist/browser-detect.d.ts.map +1 -0
  19. package/dist/browser-detect.js +160 -0
  20. package/dist/browser-detect.js.map +1 -0
  21. package/dist/concurrency-controller.d.ts +31 -0
  22. package/dist/concurrency-controller.d.ts.map +1 -0
  23. package/dist/concurrency-controller.js +33 -0
  24. package/dist/concurrency-controller.js.map +1 -0
  25. package/dist/errors.d.ts +51 -0
  26. package/dist/errors.d.ts.map +1 -0
  27. package/dist/errors.js +74 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/executor.d.ts +9 -0
  30. package/dist/executor.d.ts.map +1 -1
  31. package/dist/executor.js +87 -48
  32. package/dist/executor.js.map +1 -1
  33. package/dist/history.d.ts.map +1 -1
  34. package/dist/history.js +3 -2
  35. package/dist/history.js.map +1 -1
  36. package/dist/idb-asset-store.d.ts.map +1 -1
  37. package/dist/idb-asset-store.js +6 -1
  38. package/dist/idb-asset-store.js.map +1 -1
  39. package/dist/index.d.ts +17 -15
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +20 -15
  42. package/dist/index.js.map +1 -1
  43. package/dist/managers/asset-manager.d.ts +114 -0
  44. package/dist/managers/asset-manager.d.ts.map +1 -0
  45. package/dist/managers/asset-manager.js +238 -0
  46. package/dist/managers/asset-manager.js.map +1 -0
  47. package/dist/managers/history-manager.d.ts +100 -0
  48. package/dist/managers/history-manager.d.ts.map +1 -0
  49. package/dist/managers/history-manager.js +296 -0
  50. package/dist/managers/history-manager.js.map +1 -0
  51. package/dist/managers/mcp-manifest-builder.d.ts +18 -0
  52. package/dist/managers/mcp-manifest-builder.d.ts.map +1 -0
  53. package/dist/managers/mcp-manifest-builder.js +99 -0
  54. package/dist/managers/mcp-manifest-builder.js.map +1 -0
  55. package/dist/managers/quota-manager.d.ts +42 -0
  56. package/dist/managers/quota-manager.d.ts.map +1 -0
  57. package/dist/managers/quota-manager.js +126 -0
  58. package/dist/managers/quota-manager.js.map +1 -0
  59. package/dist/managers/workflow-coordinator.d.ts +62 -0
  60. package/dist/managers/workflow-coordinator.d.ts.map +1 -0
  61. package/dist/managers/workflow-coordinator.js +125 -0
  62. package/dist/managers/workflow-coordinator.js.map +1 -0
  63. package/dist/opfs-asset-store.d.ts.map +1 -1
  64. package/dist/opfs-asset-store.js +12 -2
  65. package/dist/opfs-asset-store.js.map +1 -1
  66. package/dist/plugin-context.d.ts +35 -0
  67. package/dist/plugin-context.d.ts.map +1 -0
  68. package/dist/plugin-context.js +62 -0
  69. package/dist/plugin-context.js.map +1 -0
  70. package/dist/plugin-permissions.d.ts +99 -0
  71. package/dist/plugin-permissions.d.ts.map +1 -0
  72. package/dist/plugin-permissions.js +205 -0
  73. package/dist/plugin-permissions.js.map +1 -0
  74. package/dist/runtime-impl.d.ts +116 -0
  75. package/dist/runtime-impl.d.ts.map +1 -0
  76. package/dist/runtime-impl.js +270 -0
  77. package/dist/runtime-impl.js.map +1 -0
  78. package/dist/runtime.d.ts +10 -233
  79. package/dist/runtime.d.ts.map +1 -1
  80. package/dist/runtime.js +12 -978
  81. package/dist/runtime.js.map +1 -1
  82. package/dist/test-utils/fakes.d.ts +35 -0
  83. package/dist/test-utils/fakes.d.ts.map +1 -0
  84. package/dist/test-utils/fakes.js +60 -0
  85. package/dist/test-utils/fakes.js.map +1 -0
  86. package/dist/types.d.ts +113 -1
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/worker-host.d.ts.map +1 -1
  89. package/dist/worker-host.js +32 -9
  90. package/dist/worker-host.js.map +1 -1
  91. package/dist/worker-protocol.d.ts +30 -0
  92. package/dist/worker-protocol.d.ts.map +1 -1
  93. package/dist/worker-protocol.js +24 -0
  94. package/dist/worker-protocol.js.map +1 -1
  95. package/package.json +2 -2
  96. package/src/asset-store.ts +32 -2
  97. package/src/batch-processor.ts +133 -510
  98. package/src/batch-progress.ts +228 -0
  99. package/src/batch-scheduler.ts +209 -0
  100. package/src/browser-detect.ts +221 -0
  101. package/src/concurrency-controller.ts +52 -0
  102. package/src/errors.ts +82 -0
  103. package/src/executor.ts +106 -55
  104. package/src/history.ts +3 -2
  105. package/src/idb-asset-store.ts +7 -1
  106. package/src/index.ts +50 -15
  107. package/src/managers/asset-manager.ts +259 -0
  108. package/src/managers/history-manager.ts +327 -0
  109. package/src/managers/mcp-manifest-builder.ts +108 -0
  110. package/src/managers/quota-manager.ts +149 -0
  111. package/src/managers/workflow-coordinator.ts +158 -0
  112. package/src/opfs-asset-store.ts +16 -2
  113. package/src/plugin-context.ts +87 -0
  114. package/src/plugin-permissions.ts +228 -0
  115. package/src/runtime-impl.ts +298 -0
  116. package/src/runtime.ts +16 -1116
  117. package/src/test-utils/fakes.ts +72 -0
  118. package/src/types.ts +116 -0
  119. package/src/worker-host.ts +35 -7
  120. package/src/worker-protocol.ts +47 -0
  121. package/dist/workflow-builder.d.ts +0 -124
  122. package/dist/workflow-builder.d.ts.map +0 -1
  123. package/dist/workflow-builder.js +0 -240
  124. package/dist/workflow-builder.js.map +0 -1
  125. package/src/workflow-builder.ts +0 -303
package/dist/runtime.js CHANGED
@@ -1,983 +1,17 @@
1
1
  /**
2
- * Lokvis Runtime Implementation
2
+ * Lokvis Runtime 入口(Facade,W1.7)
3
3
  *
4
- * Runtime 是整个系统的"浏览器操作系统",唯一职责:Input Run → Output。
5
- */
6
- import { validateWorkflow } from '@lokvis/schema';
7
- import { createEventBus } from './event-bus.js';
8
- import { createAssetStore, createMemoryAssetStore, generateId, } from './asset-store.js';
9
- import { CapabilityRegistry } from './capability-registry.js';
10
- import { WorkflowExecutor } from './executor.js';
11
- import { MAX_WORKFLOW_STEPS } from './workflow-builder.js';
12
- import { HistoryStack } from './history.js';
13
- import { createHistoryStore, } from './history-store.js';
14
- import { BatchProcessor } from './batch-processor.js';
15
- import { MemoryGuard, DEFAULT_MEMORY_BUDGET } from './memory-guard.js';
16
- export const RUNTIME_VERSION = '0.1.0';
17
- /** 默认历史记录上限 */
18
- const DEFAULT_MAX_HISTORY = 10;
19
- /**
20
- * 同时持有的工作流历史栈上限(W2.8 内存治理)。
21
- *
22
- * 修复 review 报告:原实现 historyStacks 是无限增长 Map,每次 run() 都加入新
23
- * workflow.id(ui-react buildLinearWorkflow 用 `wf_${Date.now()}` 每次唯一),
24
- * 长会话累积导致 Map 引用的 AssetId 无法回收 → 内存泄漏。
25
- *
26
- * 32 是经验值:覆盖用户常见使用(多 tab 切换 + undo 范围),超限按 FIFO
27
- * 清理最旧 stack(reset 触发 onEvict → assetStore.remove 回收资产)。
28
- */
29
- const MAX_CONCURRENT_WORKFLOW_STACKS = 32;
30
- /** 存储配额超限时抛出(W2.9) */
31
- export class QuotaExceededError extends Error {
32
- usage;
33
- delta;
34
- quota;
35
- constructor(usage, delta, quota) {
36
- super(`Storage quota exceeded: usage=${usage} + delta=${delta} > quota=${quota}`);
37
- this.name = 'QuotaExceededError';
38
- this.usage = usage;
39
- this.delta = delta;
40
- this.quota = quota;
41
- }
42
- }
43
- /**
44
- * 从 AssetSource 估算导入字节数用于配额预检。
45
- * url/opfs 源大小未知,返回 0 跳过预检 —— 真实大小在 import 完成后
46
- * 通过 `usage += asset.metadata.size` 补记到账面,后续操作仍受配额约束。
47
- */
48
- function estimateSourceSize(source) {
49
- if (source.kind === 'file')
50
- return source.file.size;
51
- if (source.kind === 'blob')
52
- return source.blob.size;
53
- return 0;
54
- }
55
- function wrapAssetStoreWithQuota(inner, quota) {
56
- let usage = 0;
57
- let initialized = false;
58
- /** 串行化 import/create/remove 的 chain tail,确保 check-update 原子性 */
59
- let chain = Promise.resolve();
60
- async function ensureInit() {
61
- if (initialized)
62
- return;
63
- const all = await inner.list();
64
- usage = all.reduce((sum, a) => sum + a.metadata.size, 0);
65
- initialized = true;
66
- }
67
- function assertQuota(delta) {
68
- if (usage + delta > quota) {
69
- throw new QuotaExceededError(usage, delta, quota);
70
- }
71
- }
72
- /** 将 import/create/remove 串行化:依次 await init → assert → inner op → update usage */
73
- function runExclusive(op) {
74
- const run = chain.then(op, op);
75
- // chain 仅用于排队,不传播 rejection(避免一次失败阻塞后续)
76
- chain = run.then(() => undefined, () => undefined);
77
- return run;
78
- }
79
- return {
80
- async import(source) {
81
- return runExclusive(async () => {
82
- await ensureInit();
83
- assertQuota(estimateSourceSize(source));
84
- const asset = await inner.import(source);
85
- usage += asset.metadata.size;
86
- return asset;
87
- });
88
- },
89
- async get(id) {
90
- return inner.get(id);
91
- },
92
- async getBlob(handle) {
93
- return inner.getBlob(handle);
94
- },
95
- async remove(id) {
96
- return runExclusive(async () => {
97
- const existing = await inner.get(id);
98
- await inner.remove(id);
99
- if (existing) {
100
- usage = Math.max(0, usage - existing.metadata.size);
101
- }
102
- });
103
- },
104
- async list() {
105
- return inner.list();
106
- },
107
- async create(blob, metadata, type) {
108
- return runExclusive(async () => {
109
- await ensureInit();
110
- // m8 修复:配额预检与累加使用同一口径(metadata.size),
111
- // 避免 blob.size 与 metadata.size 漂移导致账面与预检不一致
112
- assertQuota(metadata.size);
113
- const asset = await inner.create(blob, metadata, type);
114
- usage += asset.metadata.size;
115
- return asset;
116
- });
117
- },
118
- /**
119
- * m6 优化:暴露配额包装器内部维护的 usage(O(1)),
120
- * 供 runtime.getStorageUsage 优先使用,避免每次 O(n) 全量 listAssets。
121
- * 下划线前缀表"内部 API",非 AssetStore 接口一部分。
122
- * 若 ensureInit 未完成,返回 -1 表示"未就绪",调用方 fallback 到 listAssets。
123
- */
124
- _getQuotaUsage() {
125
- return initialized ? usage : -1;
126
- },
127
- };
128
- }
129
- /** Runtime 实现类 */
130
- export class LokvisRuntimeImpl {
131
- version = RUNTIME_VERSION;
132
- eventBus;
133
- config;
134
- _status = 'idle';
135
- /**
136
- * AssetStore 实例。类型为 QuotaAwareAssetStore —— 由 wrapAssetStoreWithQuota
137
- * 返回(在构造函数中无条件包裹,即使是注入的 assetStore 也会被包装以提供配额校验)。
138
- * 保留 _getQuotaUsage 内部 API 供 getStorageUsage O(1) 读取 usage。
139
- * 注:外部注入的 assetStore 在 wrapAssetStoreWithQuota 中同样被包装,
140
- * 因此所有路径下 this.assetStore 都是 QuotaAwareAssetStore。
141
- */
142
- assetStore;
143
- capabilityRegistry;
144
- executor;
145
- memoryGuard;
146
- batchProcessor;
147
- /**
148
- * 每个工作流独立的 HistoryStack。
149
- * W7.2 起,栈快照(entries + cursor)连同 initialInputs / currentOutputs
150
- * 通过 historyStore 持久化到 IndexedDB,刷新后可恢复。
151
- */
152
- historyStacks = new Map();
153
- /** 记录每个工作流的初始输入 AssetId(undo 回到初始时使用) */
154
- initialInputsMap = new Map();
155
- /** 记录每个工作流当前的输出 AssetId(undo/redo 后切换"当前") */
156
- currentOutputsMap = new Map();
157
- /**
158
- * 历史持久化存储(W7.2)。undefined 时退化为仅内存历史(刷新后丢失)。
159
- * 由 createRuntime 在 enableIndexedDB 时自动创建,或通过 config 注入。
160
- */
161
- historyStore;
162
- /**
163
- * 加载持久化历史快照期间的守卫标志。
164
- * restore() 会触发 onChanged → persistHistory,此时跳过写回,
165
- * 避免把刚读出的数据又重复写入(冗余 IO + 潜在覆盖竞态)。
166
- */
167
- isLoadingHistory = false;
168
- /**
169
- * 加载期间被 onChanged 标记为"dirty"的工作流 ID 集合(W7.2 review 修复)。
170
- *
171
- * 原实现:isLoadingHistory 期间所有 persistHistory 调用直接 return,
172
- * 若加载期间有其他来源(run / undo / 外部事件)触发 onChanged,
173
- * 这些变更会被永久丢弃(加载结束后不会重发 persist)。
174
- *
175
- * 现策略:加载期间被跳过的 persistHistory 把 workflowId 加入此 Set,
176
- * loadPersistedHistory 结束后逐个补 persist,确保不丢变更。
177
- * (restore() 自身触发的 onChanged 也加入,但其内容与刚读出的相同,
178
- * 补 persist 仅多一次等价写回,幂等无害。)
179
- */
180
- dirtyDuringLoad = new Set();
181
- /**
182
- * 元数据读取器注册表(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
183
- *
184
- * Plugin(plugin-image)通过 PluginContext.registerMetadataReader 注册
185
- * 查询函数(如 'image.read-exif'),Runtime 持有引用并按名调用。
186
- * 解决了 readExif(Blob→ExifData)不符合 Engine 层 Blob↔Blob 纯函数约束、
187
- * 也不符合 CapabilityImplementation Asset[]→Asset[] 契约的问题。
188
- * UI 经 runtime.readAssetExif 间接调用,不直接依赖 plugin/engine。
189
- */
190
- metadataReaders = new Map();
191
- /**
192
- * 注册元数据读取器(由 PluginContext.registerMetadataReader 转发)。
193
- * 下划线前缀表示内部 API,不暴露在 LokvisRuntime 公开接口。
194
- */
195
- _registerMetadataReader(name, reader) {
196
- this.metadataReaders.set(name, reader);
197
- }
198
- constructor(config = {}) {
199
- this.config = {
200
- enableOpfs: config.enableOpfs ?? true,
201
- enableIndexedDB: config.enableIndexedDB ?? true,
202
- storageQuota: config.storageQuota ?? 1024 * 1024 * 1024, // 1GB
203
- enableLog: config.enableLog ?? true,
204
- engineStrategy: config.engineStrategy ?? 'first',
205
- isPro: config.isPro ?? false,
206
- memoryBudget: config.memoryBudget ?? DEFAULT_MEMORY_BUDGET,
207
- };
208
- this.eventBus = createEventBus();
209
- // 注入或降级到内存 store;随后用配额校验包裹(W2.9)
210
- // M6 修复:enableOpfs/enableIndexedDB 仅在 createLokvis()/createRuntime
211
- // 工厂中生效(工厂按 flag 调 createAssetStore 选择 OPFS→IDB→Memory)。
212
- // 直接 new LokvisRuntimeImpl 且未传 assetStore 时,无法同步等待 createAssetStore,
213
- // 兜底用 Memory store;若用户显式期望持久化,提示其用 createLokvis()。
214
- if (!config.assetStore && (this.config.enableOpfs || this.config.enableIndexedDB)) {
215
- console.warn('[lokvis] LokvisRuntimeImpl constructed without assetStore: ' +
216
- 'enableOpfs/enableIndexedDB flags are ignored. ' +
217
- 'Use createLokvis() to respect these flags, or pass an assetStore explicitly.');
218
- }
219
- const rawStore = config.assetStore ?? createMemoryAssetStore();
220
- this.assetStore = wrapAssetStoreWithQuota(rawStore, this.config.storageQuota);
221
- // W7.2 历史持久化:优先用注入的 historyStore;否则在 createRuntime 工厂中
222
- // 由 createHistoryStore 自动创建并注入。直接 new Impl 时为 undefined,
223
- // 历史退化为仅内存模式(与 W2 行为一致)。
224
- this.historyStore = config.historyStore;
225
- this.capabilityRegistry = new CapabilityRegistry(this.config.engineStrategy);
226
- this.executor = new WorkflowExecutor({
227
- assetStore: this.assetStore,
228
- capabilityRegistry: this.capabilityRegistry,
229
- eventBus: this.eventBus,
230
- enableLog: this.config.enableLog,
231
- });
232
- // W3.3 MemoryGuard:追踪中间结果占用,达到 high 阈值时建议 OPFS 溢出。
233
- // BatchProcessor 据此动态收缩并发槽位(W6.1)。
234
- this.memoryGuard = new MemoryGuard({
235
- budget: this.config.memoryBudget,
236
- assetStore: this.assetStore,
237
- });
238
- // W6.1 BatchProcessor:把 W5 playground 的并发/进度/重试逻辑下沉到 runtime。
239
- // 注入 this(实现 LokvisRuntime 接口),不直接依赖 LokvisRuntimeImpl 避免循环引用。
240
- this.batchProcessor = new BatchProcessor({
241
- runtime: this,
242
- eventBus: this.eventBus,
243
- isPro: this.config.isPro,
244
- memoryGuard: this.memoryGuard,
245
- });
246
- // 监听 node:finished 事件,自动 append 到 HistoryStack
247
- this.eventBus.on('node:finished', (event) => {
248
- this.recordHistoryFromNodeEvent(event);
249
- });
250
- }
251
- get status() {
252
- return this._status;
253
- }
254
- get isPro() {
255
- return this.config.isPro;
256
- }
257
- get batch() {
258
- return this.batchProcessor;
259
- }
260
- // ─── 工作流执行 ──────────────────────────────────────
261
- async run(workflow, inputs, options) {
262
- this._status = 'running';
263
- // Schema 层校验:在 executor.execute 之前调用 validateWorkflow,
264
- // 让结构问题(保留字哨兵 __input__、悬挂 edge、自环、重复 id、真环)
265
- // 在入口处暴露,错误信息精准(如 "Edge from __input__ references a
266
- // reserved sentinel id"),而不是被 executor 拓扑排序误判为含糊的 "cycle"。
267
- // 三层防御的第 3 层(前两层:executor 防御性校验 + 单元测试覆盖)。
268
- //
269
- // W10.2/W10.3 增强:
270
- // - resolveCapability 回调注入 capability 兼容性校验(相邻节点
271
- // outputTypes 与 inputTypes 必须有交集;输入/输出节点类型与
272
- // workflow.inputs/outputs.type 兼容)
273
- // - maxSteps: 5(由 MAX_WORKFLOW_STEPS 常量定义,M1 MVP 约束)
274
- const validation = validateWorkflow(workflow, {
275
- maxSteps: MAX_WORKFLOW_STEPS,
276
- resolveCapability: (name) => {
277
- const cap = this.capabilityRegistry.get(name);
278
- if (!cap)
279
- return undefined;
280
- return {
281
- inputTypes: cap.inputTypes,
282
- outputTypes: cap.outputTypes,
283
- };
284
- },
285
- });
286
- if (!validation.success) {
287
- this._status = 'error';
288
- const error = validation.error.issues
289
- .map((i) => i.message)
290
- .join('; ');
291
- const result = {
292
- workflowId: workflow.id,
293
- outputs: [],
294
- duration: 0,
295
- status: 'failed',
296
- error,
297
- };
298
- this.eventBus.emit({
299
- type: 'workflow:completed',
300
- workflowId: workflow.id,
301
- result,
302
- });
303
- return result;
304
- }
305
- // 历史栈管理:
306
- // - 默认:每次 run() 重置历史(重跑语义),并通过 onEvict 回收旧 outputs 资产
307
- // - appendHistory:true:保留已有历史栈,支持跨次 undo/redo 链(如连续滤镜)
308
- const inputIds = await this.collectInputAssetIds(inputs);
309
- if (options?.appendHistory && this.historyStacks.has(workflow.id)) {
310
- // 追加模式:保留历史栈与 currentOutputs,仅确保初始输入已记录
311
- if (!this.initialInputsMap.has(workflow.id)) {
312
- this.initialInputsMap.set(workflow.id, inputIds);
313
- }
314
- }
315
- else {
316
- // 重置模式(默认):丢弃旧历史,重新初始化
317
- const existingStack = this.historyStacks.get(workflow.id);
318
- if (existingStack) {
319
- existingStack.reset();
320
- }
321
- this.initialInputsMap.set(workflow.id, inputIds);
322
- this.currentOutputsMap.set(workflow.id, inputIds);
323
- }
324
- this.enforceHistoryStacksLimit();
325
- try {
326
- const result = await this.executor.execute(workflow, inputs);
327
- this._status = result.status === 'failed' ? 'error' : 'idle';
328
- // 成功完成后,记录最终输出为当前
329
- if (result.status === 'completed' && result.outputs.length > 0) {
330
- this.currentOutputsMap.set(workflow.id, result.outputs);
331
- }
332
- return result;
333
- }
334
- catch (error) {
335
- this._status = 'error';
336
- throw error;
337
- }
338
- }
339
- async cancel(workflowId) {
340
- return this.executor.cancel(workflowId);
341
- }
342
- async pause(workflowId) {
343
- return this.executor.pause(workflowId);
344
- }
345
- async resume(workflowId) {
346
- return this.executor.resume(workflowId);
347
- }
348
- /**
349
- * 销毁指定工作流的运行时状态(W2.8 内存治理)。
350
- *
351
- * 调用时机:
352
- * - ui-react 卸载 Workspace 组件时
353
- * - 用户主动关闭工作流标签页时
354
- *
355
- * 行为:
356
- * - 调用 stack.reset() 触发 onEvict → assetStore.remove 回收历史 outputs 资产
357
- * - 从 historyStacks / initialInputsMap / currentOutputsMap 三 Map 中删除 entry
358
- * - 调用 executor.cancel 取消运行中的执行(若有)
359
- *
360
- * 修复 review 报告:原实现无清理入口,Workflow 组件卸载后 Map 中残留 entry,
361
- * 长会话累积导致内存与 OPFS 空间双泄漏。
362
- */
363
- async disposeWorkflow(workflowId) {
364
- await this.cancel(workflowId).catch(() => {
365
- /* 工作流可能未在运行 */
366
- });
367
- const stack = this.historyStacks.get(workflowId);
368
- if (stack) {
369
- stack.reset();
370
- this.historyStacks.delete(workflowId);
371
- }
372
- this.initialInputsMap.delete(workflowId);
373
- this.currentOutputsMap.delete(workflowId);
374
- }
375
- // ─── 历史与撤销 ──────────────────────────────────────
376
- async history(workflowId) {
377
- // 避免对从未运行过的工作流创建空栈:先查 Map,无则直接返回空数组
378
- return this.historyStacks.get(workflowId)?.list() ?? [];
379
- }
380
- async getHistoryState(workflowId) {
381
- const stack = this.historyStacks.get(workflowId);
382
- if (!stack)
383
- return { entries: [], cursor: -1 };
384
- const snap = stack.snapshot();
385
- return { entries: snap.entries, cursor: snap.cursor };
386
- }
387
- async undo(workflowId) {
388
- const stack = this.getOrCreateHistoryStack(workflowId);
389
- const result = stack.undo();
390
- if (result === undefined)
391
- return; // 无可 undo
392
- // 更新当前输出:
393
- // - null 表示回到初始状态,使用 initialInputs
394
- // - entry 表示回退到该条目的 outputs
395
- const newCurrent = result === null
396
- ? (this.initialInputsMap.get(workflowId) ?? [])
397
- : result.outputs;
398
- this.currentOutputsMap.set(workflowId, newCurrent);
399
- // history:changed 事件由 stack 的 onChanged 回调统一发射,避免双发
400
- }
401
- async redo(workflowId) {
402
- const stack = this.getOrCreateHistoryStack(workflowId);
403
- const entry = stack.redo();
404
- if (entry === undefined)
405
- return; // 无可 redo
406
- this.currentOutputsMap.set(workflowId, entry.outputs);
407
- // history:changed 事件由 stack 的 onChanged 回调统一发射,避免双发
408
- }
409
- async jumpTo(workflowId, index) {
410
- const stack = this.getOrCreateHistoryStack(workflowId);
411
- const result = stack.jumpTo(index);
412
- if (result === undefined)
413
- return; // 越界或游标未变,无操作
414
- // 同 undo/redo:更新当前输出
415
- const newCurrent = result === null
416
- ? (this.initialInputsMap.get(workflowId) ?? [])
417
- : result.outputs;
418
- this.currentOutputsMap.set(workflowId, newCurrent);
419
- // history:changed 事件由 stack 的 onChanged 回调统一发射
420
- }
421
- // ─── Asset 管理 ──────────────────────────────────────
422
- async importAsset(source) {
423
- // 修复 review 报告:原实现直接透传 source 给 assetStore.import,
424
- // 但 MemoryAssetStore/OpfsAssetStore/IdbAssetStore 的 extractBlobFromSource
425
- // 仅支持 file/blob 两种 kind,url/opfs 会抛 "not supported"。
426
- // 这里在 runtime 层兜底处理 url(fetch → blob),opfs 暂不支持(OPFS
427
- // 路径访问需要 filesystem access permission,未来单独实现)
428
- let effectiveSource = source;
429
- if (source.kind === 'url') {
430
- const resp = await fetch(source.url);
431
- if (!resp.ok) {
432
- throw new Error(`Failed to fetch asset from ${source.url}: ${resp.status}`);
433
- }
434
- const blob = await resp.blob();
435
- const name = source.url.split('/').pop()?.split('?')[0] ?? 'asset';
436
- effectiveSource = { kind: 'blob', blob, name };
437
- }
438
- else if (source.kind === 'opfs') {
439
- throw new Error("AssetSource kind 'opfs' is not yet supported by importAsset; " +
440
- 'use the OPFS-aware AssetStore directly or convert to blob first');
441
- }
442
- const asset = await this.assetStore.import(effectiveSource);
443
- this.eventBus.emit({
444
- type: 'asset:imported',
445
- assetId: asset.id,
446
- metadata: asset.metadata,
447
- });
448
- return asset.id;
449
- }
450
- async getAsset(id) {
451
- const asset = await this.assetStore.get(id);
452
- if (!asset)
453
- throw new Error(`Asset not found: ${id}`);
454
- return asset;
455
- }
456
- async exportAsset(id, format) {
457
- const asset = await this.getAsset(id);
458
- const blob = await this.assetStore.getBlob(asset.blob);
459
- // OPFS 存储后端用 .bin 扩展名存储,读取时 fileHandle.getFile() 返回的
460
- // File.type 可能为空字符串或 'application/octet-stream'(浏览器对未知扩展名
461
- // 的默认兜底 MIME)。这两种情况都会导致 Object URL 的 Content-Type 退化,
462
- // 下载时文件扩展名变成 .octet-stream。
463
- // 用 asset metadata 的 mimeType 补全 Blob type(IDB/Memory 后端不受影响)。
464
- const OPFS_FALLBACK_MIME = 'application/octet-stream';
465
- const mimeType = !blob.type || blob.type === OPFS_FALLBACK_MIME
466
- ? asset.metadata.mimeType
467
- : blob.type;
468
- // 关键:用 arrayBuffer() 显式读取数据到内存,再构造新 Blob。
469
- // 不能用 new Blob([blob]) —— 浏览器实现中它可能延迟引用底层 OPFS 文件,
470
- // WatermarkBatchTool 在 export 后立即 removeAsset 删除 OPFS 文件,
471
- // 导致后续 downloadBlob 读取悬空引用失败("check internet connection")。
472
- // arrayBuffer() 立即拉取数据,确保返回的 Blob 完全独立于底层存储。
473
- const buffer = await blob.arrayBuffer();
474
- const exported = new Blob([buffer], { type: mimeType });
475
- this.eventBus.emit({
476
- type: 'export:completed',
477
- assetId: id,
478
- format: format ?? asset.metadata.format,
479
- size: blob.size,
480
- });
481
- return exported;
482
- }
483
- /**
484
- * 读取 image 资产的 EXIF 元数据(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
485
- *
486
- * Runtime 持有 plugin-image 通过 ctx.registerMetadataReader('image.read-exif', fn)
487
- * 注册的 reader 引用,按名调用。reader 内部调 readExifFromBlob(exifr)。
488
- * Plugin 未安装时优雅降级返回 null(不抛错)。
489
- *
490
- * 架构决策:readExif 是 Blob→ExifData 查询,不符合 Engine 层 Blob↔Blob 纯函数
491
- * 约束,也不符合 Capability Asset[]→Asset[] 契约,故走 MetadataReader 机制,
492
- * 不进 engine-image、不走 Capability execute。
493
- */
494
- async readAssetExif(id) {
495
- const asset = await this.getAsset(id);
496
- if (asset.type !== 'image')
497
- return null;
498
- const reader = this.metadataReaders.get('image.read-exif');
499
- if (!reader)
500
- return null; // Plugin 未安装,优雅降级
501
- return reader(asset);
502
- }
503
- async removeAsset(id) {
504
- await this.assetStore.remove(id);
505
- this.eventBus.emit({ type: 'asset:removed', assetId: id });
506
- }
507
- async listAssets() {
508
- return this.assetStore.list();
509
- }
510
- async getStorageUsage() {
511
- // m6 优化:优先用配额包装器内部维护的 usage(O(1),import/create/remove
512
- // 时增量更新),避免每次 O(n) 全量 listAssets 影响 StatusBar 刷新。
513
- // 包装器未就绪(ensureInit 未完成)返回 -1 时,fallback 到 listAssets
514
- // 实时计算(source of truth,与 W6.4 富元数据一致)。
515
- //
516
- // 类型说明:assetStore 字段类型为 QuotaAwareAssetStore(含 _getQuotaUsage),
517
- // 由 wrapAssetStoreWithQuota 返回。无需重新断言 —— 类型信息未丢失。
518
- const cached = this.assetStore._getQuotaUsage();
519
- if (cached >= 0) {
520
- return { usage: cached, quota: this.config.storageQuota };
521
- }
522
- const all = await this.assetStore.list();
523
- const usage = all.reduce((sum, a) => sum + a.metadata.size, 0);
524
- return { usage, quota: this.config.storageQuota };
525
- }
526
- // ─── 能力查询 ────────────────────────────────────────
527
- async capabilities() {
528
- return this.capabilityRegistry.list();
529
- }
530
- async hasCapability(name) {
531
- return this.capabilityRegistry.has(name);
532
- }
533
- // ─── MCP 暴露(见 docs/AI生态冲击调整方案.md §6) ─────
534
- /**
535
- * 生成 MCP server manifest(不启动 server,仅描述当前可被 MCP 暴露的能力)。
536
- * - `mcpExposure='private'`:任何模式都不暴露
537
- * - `mcpExposure='batch-only'`:仅在 `options.batchMode=true` 时暴露
538
- * (避免单文件误用)
539
- * - 其余(默认 'public'):总是暴露
540
- * - tool 名取 capability.mcpToolName 或 `lokvis_${name.replace(/\./g, '_')}`
541
- * - resource 固定为 capabilities 与 workflows 两个清单
542
- */
543
- toMcpManifest(options = {}) {
544
- const { batchMode = false } = options;
545
- const tools = [];
546
- const capabilities = this.capabilityRegistry.list();
547
- for (const cap of capabilities) {
548
- // private 任何模式都不暴露
549
- if (cap.mcpExposure === 'private')
550
- continue;
551
- // batch-only 仅在 batch 模式暴露(避免单文件误用)
552
- if (cap.mcpExposure === 'batch-only' && !batchMode)
553
- continue;
554
- const toolName = cap.mcpToolName ?? `lokvis_${cap.name.replace(/\./g, '_')}`;
555
- tools.push({
556
- name: toolName,
557
- description: cap.description,
558
- inputSchema: capabilityParamsToJsonSchema(cap.params),
559
- capabilities: [cap.name],
560
- });
561
- }
562
- return {
563
- serverName: 'lokvis',
564
- version: RUNTIME_VERSION,
565
- tools,
566
- resources: [
567
- {
568
- uri: 'lokvis://capabilities',
569
- name: 'Capabilities',
570
- description: 'List all available Lokvis capabilities',
571
- mimeType: 'application/json',
572
- },
573
- {
574
- uri: 'lokvis://workflows',
575
- name: 'Workflows',
576
- description: 'List saved workflows',
577
- mimeType: 'application/json',
578
- },
579
- ],
580
- };
581
- }
582
- // ─── 插件安装 ────────────────────────────────────────
583
- /**
584
- * 在本 Runtime 上安装一个插件(实现 LokvisRuntime.installPlugin 接口)。
585
- *
586
- * 步骤:
587
- * 1. 注册能力声明(plugin.config.capabilities → CapabilityRegistry)
588
- * 2. 构造受限 PluginContext(只暴露受限 Runtime API + 注册器 + 日志)
589
- * 3. 调用 plugin.install(ctx),让插件注册 CapabilityImplementation
590
- * 4. 发射 `plugin:loaded` 事件
591
- *
592
- * 不吞错:plugin.install 抛出的错误原样上抛,由 SDK 包成 PluginLoadError。
593
- *
594
- * 此前 SDK 通过 `instanceof LokvisRuntimeImpl` + `_getAssetStore()` /
595
- * `_getCapabilityRegistry()` 反向访问内部依赖,现改为公共接口调用,
596
- * SDK 不再依赖具体实现类。
597
- */
598
- async installPlugin(plugin) {
599
- for (const capability of plugin.config.capabilities) {
600
- this.capabilityRegistry.registerCapability(capability);
601
- }
602
- const ctx = createPluginContext(plugin.config.name, this);
603
- await plugin.install(ctx);
604
- this.eventBus.emit({
605
- type: 'plugin:loaded',
606
- name: plugin.config.name,
607
- version: plugin.config.version,
608
- });
609
- }
610
- // ─── 内部 API(供测试使用,SDK 不再调用) ──────────────
611
- /** 获取 AssetStore(仅测试用,SDK 通过 installPlugin 间接访问) */
612
- _getAssetStore() {
613
- return this.assetStore;
614
- }
615
- /** 获取 CapabilityRegistry(仅测试用,SDK 通过 installPlugin 间接访问) */
616
- _getCapabilityRegistry() {
617
- return this.capabilityRegistry;
618
- }
619
- /**
620
- * 获取 MemoryGuard(内部用,供集成测试驱动内存压力验证 BatchProcessor 收缩)。
621
- */
622
- _getMemoryGuard() {
623
- return this.memoryGuard;
624
- }
625
- /** 获取工作流当前输出 AssetId(undo/redo 后的"当前"状态,内部用) */
626
- _getCurrentOutputs(workflowId) {
627
- return this.currentOutputsMap.get(workflowId) ?? [];
628
- }
629
- /** 获取工作流当前输出 AssetId(公开 API,供 UI / MCP 查询) */
630
- async getCurrentOutputs(workflowId) {
631
- return this._getCurrentOutputs(workflowId);
632
- }
633
- // ─── 私有:历史栈管理 ──────────────────────────────
634
- /**
635
- * LRU 上限清理:historyStacks 超过 MAX_CONCURRENT_WORKFLOW_STACKS 时
636
- * 按 FIFO 删除最旧 stack(reset 触发 onEvict → assetStore.remove 回收资产)。
637
- *
638
- * Map 的迭代顺序是插入顺序(ES2015+ 规范),所以第一个 entry 即最旧。
639
- * 注意:当前 run() 的工作流尚未插入 Map(getOrCreateHistoryStack 才会插入),
640
- * 所以这里清理不会误删当前工作流。
641
- */
642
- enforceHistoryStacksLimit() {
643
- while (this.historyStacks.size >= MAX_CONCURRENT_WORKFLOW_STACKS) {
644
- // 取最旧 workflowId(Map 第一个 key)
645
- const oldestId = this.historyStacks.keys().next().value;
646
- if (oldestId === undefined)
647
- break;
648
- const stack = this.historyStacks.get(oldestId);
649
- if (stack) {
650
- // reset 触发 onEvict,回收历史 outputs 资产
651
- stack.reset();
652
- }
653
- this.historyStacks.delete(oldestId);
654
- this.initialInputsMap.delete(oldestId);
655
- this.currentOutputsMap.delete(oldestId);
656
- }
657
- }
658
- /** 获取或创建工作流对应的 HistoryStack */
659
- getOrCreateHistoryStack(workflowId) {
660
- let stack = this.historyStacks.get(workflowId);
661
- if (!stack) {
662
- const stackConfig = {
663
- maxEntries: DEFAULT_MAX_HISTORY,
664
- onEvict: (entry) => {
665
- // 淘汰条目时清理其 outputs 资产(避免 OPFS 泄漏)
666
- // 注意:此时条目已从栈中移除,且 undo 不会再回到它
667
- for (const assetId of entry.outputs) {
668
- // 静默移除,忽略不存在的情况
669
- this.assetStore.remove(assetId).catch(() => { });
670
- }
671
- },
672
- onChanged: (wfId, entries, currentIndex) => {
673
- this.eventBus.emit({
674
- type: 'history:changed',
675
- workflowId: wfId,
676
- entries,
677
- currentIndex,
678
- });
679
- // W7.2:持久化快照到 IndexedDB(加载期间跳过,避免冗余写回)
680
- void this.persistHistory(wfId);
681
- },
682
- };
683
- stack = new HistoryStack(workflowId, stackConfig);
684
- this.historyStacks.set(workflowId, stack);
685
- }
686
- return stack;
687
- }
688
- /** 将输入归一化为 AssetId[](run() 入参可为 AssetId[] 或 Asset[]) */
689
- async collectInputAssetIds(inputs) {
690
- if (inputs.length === 0)
691
- return [];
692
- if (typeof inputs[0] === 'string') {
693
- return inputs;
694
- }
695
- return inputs.map((a) => a.id);
696
- }
697
- /** 监听 node:finished 事件,自动 append 到对应工作流的 HistoryStack */
698
- recordHistoryFromNodeEvent(event) {
699
- if (!event.outputs || event.outputs.length === 0)
700
- return;
701
- const stack = this.getOrCreateHistoryStack(event.workflowId);
702
- const outputs = event.outputs.map((a) => a.id);
703
- const now = Date.now();
704
- // node 的 inputs = 上一步的 outputs(或初始输入)
705
- const inputs = this.currentOutputsMap.get(event.workflowId) ?? [];
706
- const entry = {
707
- id: generateId(),
708
- workflowId: event.workflowId,
709
- nodeId: event.nodeId,
710
- capability: event.capability,
711
- params: event.params,
712
- inputs,
713
- outputs,
714
- timestamp: now,
715
- };
716
- stack.append(entry);
717
- // 更新当前输出为该 node 的 outputs
718
- this.currentOutputsMap.set(event.workflowId, outputs);
719
- }
720
- // ─── 私有:历史持久化(W7.2) ────────────────────────
721
- /**
722
- * 把指定工作流的当前历史状态快照写入 historyStore。
723
- *
724
- * 时序修复:currentOutputs 从 stack snapshot 派生(cursor === -1 用
725
- * initialInputs,否则用 entries[cursor].outputs),而非读 currentOutputsMap。
726
- * 原因:onChanged 在 undo/redo/jumpTo/run 内部同步触发时,map 尚未更新,
727
- * 会读到旧值(例如 run 后 append 触发 onChanged,但 currentOutputsMap 在
728
- * append 返回后才 set)。
729
- *
730
- * 竞态安全:多个 fire-and-forget save 的 IDB readwrite 事务由 IndexedDB
731
- * 引擎按发起顺序串行化(同 object store 不重叠),无需应用层加链。
732
- *
733
- * - entries 为空时改为 delete,避免残留空记录(reset/clear 后自然清理)
734
- * - 加载期间(isLoadingHistory=true)跳过写回,但把 workflowId 加入
735
- * dirtyDuringLoad,loadPersistedHistory 结束后补 persist(避免丢变更)
736
- */
737
- async persistHistory(workflowId) {
738
- if (!this.historyStore)
739
- return;
740
- if (this.isLoadingHistory) {
741
- this.dirtyDuringLoad.add(workflowId);
742
- return;
743
- }
744
- // fire-and-forget 调用方用 `void this.persistHistory(...)`,故内部必须
745
- // try/catch,否则 IDB 故障(数据库关闭 / quota exceeded)会变成 unhandled
746
- // promise rejection。历史持久化是非关键路径,失败只 warn 不抛。
747
- try {
748
- const stack = this.historyStacks.get(workflowId);
749
- // 栈已从内存移除(disposeWorkflow / enforceHistoryStacksLimit 的 reset+delete
750
- // 后异步到达此处)→ 删除持久化记录,避免孤儿数据跨会话残留
751
- if (!stack) {
752
- await this.historyStore.delete(workflowId);
753
- return;
754
- }
755
- const { entries, cursor } = stack.snapshot();
756
- if (entries.length === 0) {
757
- await this.historyStore.delete(workflowId);
758
- return;
759
- }
760
- // 从 snapshot 派生 currentOutputs,而非读 currentOutputsMap —— 后者在
761
- // onChanged 触发时尚未更新(见方法文档注释)
762
- const initialInputs = this.initialInputsMap.get(workflowId) ?? [];
763
- const currentOutputs = cursor === -1
764
- ? initialInputs
765
- : (entries[cursor]?.outputs ?? initialInputs);
766
- await this.historyStore.save({
767
- workflowId,
768
- entries,
769
- cursor,
770
- initialInputs,
771
- currentOutputs,
772
- updatedAt: Date.now(),
773
- });
774
- }
775
- catch (err) {
776
- console.warn(`[lokvis] persistHistory failed for workflow ${workflowId}:`, err);
777
- }
778
- }
779
- /**
780
- * 从 historyStore 预加载所有持久化的历史快照,恢复到内存。
781
- *
782
- * 由 createRuntime 工厂在构造完 impl 后调用一次。加载期间置 isLoadingHistory
783
- * 守卫,使 restore() 触发的 onChanged → persistHistory 跳过冗余写回;
784
- * 但被跳过的 workflowId 记入 dirtyDuringLoad,加载结束后补 persist,
785
- * 避免加载期间其他来源(run / undo / 外部事件)的变更被永久丢弃。
786
- *
787
- * 注意:restore 会 emit history:changed 事件,但此时 UI 尚未订阅
788
- * (runtime-slice.init 在 createRuntime resolve 后才订阅),故无副作用。
789
- *
790
- * 非 LokvisRuntime 接口的一部分,仅为 impl 的初始化钩子(工厂调用)。
791
- */
792
- async loadPersistedHistory() {
793
- if (!this.historyStore)
794
- return;
795
- let records = [];
796
- this.isLoadingHistory = true;
797
- try {
798
- records = await this.historyStore.loadAll();
799
- for (const record of records) {
800
- // 跳过空记录(理论上 save 已删除,双重防御)
801
- if (record.entries.length === 0)
802
- continue;
803
- const stack = this.getOrCreateHistoryStack(record.workflowId);
804
- stack.restore({ entries: record.entries, cursor: record.cursor });
805
- this.initialInputsMap.set(record.workflowId, record.initialInputs);
806
- this.currentOutputsMap.set(record.workflowId, record.currentOutputs);
807
- }
808
- }
809
- finally {
810
- this.isLoadingHistory = false;
811
- // 加载期间被跳过的 persist 补发:逐个 await 保证顺序
812
- // 复制一份避免补 persist 过程中新触发 onChanged → dirtyDuringLoad 死循环
813
- const pending = [...this.dirtyDuringLoad];
814
- this.dirtyDuringLoad.clear();
815
- for (const wfId of pending) {
816
- await this.persistHistory(wfId);
817
- }
818
- }
819
- }
820
- }
821
- /**
822
- * 创建 Runtime 实例(W2.8 + W2.9)。
823
- *
824
- * 默认通过 createAssetStore 工厂按 OPFS → IndexedDB → Memory 降级创建 AssetStore,
825
- * 并用配额校验包裹。也可通过 config.assetStore 注入自定义 store。
826
- *
827
- * 注:此函数为 async(工厂需异步探测环境)。SDK 的 createLokvis 已是 async。
828
- */
829
- export async function createRuntime(config) {
830
- const assetStore = config?.assetStore ??
831
- (await createAssetStore({ preferOpfs: config?.enableOpfs ?? true }));
832
- // W7.2:历史持久化 —— 优先用注入的 historyStore;否则在 enableIndexedDB 时
833
- // 通过 createHistoryStore 自动创建(IDB 不可用时返回 undefined,退化仅内存)
834
- const historyStore = config?.historyStore ??
835
- ((config?.enableIndexedDB ?? true)
836
- ? createHistoryStore(config?.historyStoreOptions)
837
- : undefined);
838
- const impl = new LokvisRuntimeImpl({ ...config, assetStore, historyStore });
839
- // 预加载持久化的历史快照(跨会话恢复 undo/redo 链)
840
- await impl.loadPersistedHistory();
841
- return impl;
842
- }
843
- /**
844
- * 构造受限 PluginContext(模块级 helper,供 installPlugin 使用)。
845
- *
846
- * Plugin 只看到受限的 Runtime API:
847
- * - getAsset / importAsset / getAssetBlob / createAsset / listCapabilities
848
- * - 看不到 React / Redux / Cloud
849
- *
850
- * registerMetadataReader 把读取函数转发给 runtime._registerMetadataReader
851
- * (依赖反转:Plugin 提供实现,Runtime 持有引用)。
852
- *
853
- * 错误契约:getAsset 在资产不存在时抛 plain Error,message 以 "Asset not found"
854
- * 开头。SDK 的 fromLokvisError 据此模式匹配转换为 AssetNotFoundError,
855
- * 保持 SDK 消费者的错误类型契约不变。
856
- */
857
- function createPluginContext(pluginName, runtime) {
858
- const assetStore = runtime._getAssetStore();
859
- const capabilityRegistry = runtime._getCapabilityRegistry();
860
- return {
861
- runtime: {
862
- getAsset: async (id) => {
863
- const asset = await assetStore.get(id);
864
- if (!asset)
865
- throw new Error(`Asset not found: ${id}`);
866
- return asset;
867
- },
868
- importAsset: async (file) => {
869
- // PluginContext.importAsset 接受 File | Blob,统一转为 AssetSource
870
- if (file instanceof File) {
871
- const asset = await assetStore.import({ kind: 'file', file });
872
- return asset.id;
873
- }
874
- const asset = await assetStore.import({
875
- kind: 'blob',
876
- blob: file,
877
- name: `blob_${Date.now()}`,
878
- });
879
- return asset.id;
880
- },
881
- getAssetBlob: (asset) => assetStore.getBlob(asset.blob),
882
- createAsset: (blob, metadata, type) => assetStore.create(blob, metadata, type),
883
- listCapabilities: async () => capabilityRegistry.list(),
884
- },
885
- eventBus: runtime.eventBus,
886
- registerCapability: (impl) => capabilityRegistry.registerImplementation(impl),
887
- registerMetadataReader: (name, reader) => {
888
- runtime._registerMetadataReader(name, reader);
889
- },
890
- registerPanel: (panel) => {
891
- // Panel 注册由 UI 层处理,这里仅记录日志
892
- void panel;
893
- },
894
- log: (level, message) => {
895
- const prefix = `[${pluginName}]`;
896
- if (level === 'error')
897
- console.error(`${prefix} ${message}`);
898
- else if (level === 'warn')
899
- console.warn(`${prefix} ${message}`);
900
- else
901
- console.log(`${prefix} ${message}`);
902
- },
903
- };
904
- }
905
- /**
906
- * 把 Capability.params(CapabilityParam[])转换为 JSON Schema 对象,
907
- * 供 MCP tool manifest 的 inputSchema 字段使用。
908
- *
909
- * 手写转换而非用 zod-to-json-schema:Capability.params 是数组形式
910
- * (非 ZodSchema),直接映射即可,无需引入额外依赖。
911
- * (见 docs/AI生态冲击调整方案.md §6.3 的依赖决策)
912
- */
913
- function capabilityParamsToJsonSchema(params) {
914
- const properties = {};
915
- const required = [];
916
- for (const p of params) {
917
- const prop = capabilityParamToJsonSchemaProperty(p);
918
- properties[p.name] = prop;
919
- if (p.required)
920
- required.push(p.name);
921
- }
922
- return {
923
- type: 'object',
924
- properties,
925
- ...(required.length > 0 ? { required } : {}),
926
- };
927
- }
928
- /**
929
- * 把 CapabilityParamType 映射为合法的 JSON Schema 类型片段。
4
+ * 本文件仅 re-export runtime-impl.ts 的实现类与工厂,保持外部导入路径
5
+ * (`@lokvis/runtime` / `'../runtime.js'`)不变。实现细节见 runtime-impl.ts。
930
6
  *
931
- * CapabilityParamType 含 `color` / `file` / `enum` 等 Lokvis 专属类型,
932
- * 它们都不是合法 JSON Schema 类型,必须映射到标准类型:
933
- * - `color` → `{ type: 'string', format: 'color' }`
934
- * - `file` `{ type: 'string' }`(描述里说明是文件路径)
935
- * - `enum` `{ type: 'string' }`(枚举值由外层追加 `enum` 字段)
936
- * - `object`/`array`/`number`/`string`/`boolean` → 同名 JSON Schema 类型
7
+ * Re-export 列表:
8
+ * - `LokvisRuntimeImpl` Runtime 实现类(测试 / SDK 通过此名构造)
9
+ * - `createRuntime` 异步工厂(按 OPFS IDB Memory 降级创建 store)
10
+ * - `RUNTIME_VERSION` 版本常量(写入 manifest.version)
11
+ * - `QuotaExceededError` 配额超限错误类型(SDK / 集成代码从此入口导入)
937
12
  */
938
- function capabilityParamTypeToJsonType(type) {
939
- switch (type) {
940
- case 'color':
941
- return { type: 'string', format: 'color' };
942
- case 'file':
943
- case 'enum':
944
- return { type: 'string' };
945
- case 'number':
946
- case 'string':
947
- case 'boolean':
948
- case 'object':
949
- case 'array':
950
- return { type };
951
- default:
952
- // 未知类型降级为 string,避免生成非法 JSON Schema
953
- return { type: 'string' };
954
- }
955
- }
956
- /** 单个 CapabilityParam → JSON Schema property */
957
- function capabilityParamToJsonSchemaProperty(p) {
958
- const { type: jsonType, format } = capabilityParamTypeToJsonType(p.type);
959
- const prop = { type: jsonType };
960
- if (format)
961
- prop.format = format;
962
- if (p.description)
963
- prop.description = p.description;
964
- if (p.default !== undefined)
965
- prop.default = p.default;
966
- // minimum/maximum 仅对 number 合法;string 应使用 minLength/maxLength
967
- // (CapabilityParam 仅定义了数值语义的 min/max,故只对 number 类型应用)
968
- if (p.type === 'number') {
969
- if (typeof p.min === 'number')
970
- prop.minimum = p.min;
971
- if (typeof p.max === 'number')
972
- prop.maximum = p.max;
973
- }
974
- if (p.type === 'enum' && p.values) {
975
- prop.enum = p.values;
976
- }
977
- if (p.type === 'array' && p.items) {
978
- // 递归映射 items 类型,避免 items 为 color/file/enum 时仍是非法类型
979
- prop.items = capabilityParamTypeToJsonType(p.items);
980
- }
981
- return prop;
982
- }
13
+ export { LokvisRuntimeImpl, createRuntime, RUNTIME_VERSION, } from './runtime-impl.js';
14
+ // QuotaExceededError 仅作 re-export,保持 `@lokvis/runtime` 的对外导出路径不变
15
+ // (SDK / 测试 / 集成代码均从 runtime 包入口导入该错误类型)
16
+ export { QuotaExceededError } from './managers/quota-manager.js';
983
17
  //# sourceMappingURL=runtime.js.map