dsh-live-compact 1.1.13 → 1.1.15

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/shell.js CHANGED
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * 薄入口。这个文件必须能求值,引擎加载失败也不能把这里抛掉。
3
3
  * Thin entry. This file must evaluate even when the engine cannot load.
4
- * A throw here leaves stock disabled and /compact waiting.
5
4
  *
6
5
  * 预检查只解析配置,校验交给实际引擎;构造失败时释放本次注册,不重试原版盖掉报错。
7
6
  * Resolve config before construction; let the engine validate it and preserve its actual error.
8
7
  */
9
- import { loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
8
+ import { contextProperty, entryOf, loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
10
9
  import { configSchema, engineConfig } from "./settings.js";
11
10
  import { installPresetGate } from "./gate.js";
11
+ import { appendDecision, shadowDirectory } from "./shadow.js";
12
+
13
+ const CORDIS_INIT = Symbol.for("cordis.init");
14
+ const ISOLATE = Symbol.for("cordis.isolate");
12
15
 
13
16
  let Engine = null;
14
17
  let Stock = null;
@@ -43,6 +46,11 @@ try {
43
46
  if (!loadError) loadError = error instanceof Error ? error : new Error(String(error));
44
47
  }
45
48
 
49
+ if (loadError) {
50
+ const code = typeof loadError.code === "string" ? `${loadError.code} ` : "";
51
+ console.error(`spine: 引擎模块加载失败。${code}${reasonText(loadError)}`);
52
+ }
53
+
46
54
  // 官方设置界面按这份 schema 自动生成表单。拿不到 schemastery 就退回 stock 的 schema。
47
55
  try {
48
56
  const schema = await loadSchema();
@@ -60,50 +68,70 @@ export function preflightConfig(config = {}) {
60
68
  }
61
69
 
62
70
  function compactionRecord(ctx) {
63
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
64
- return key === undefined ? undefined : ctx?.reflect?.store?.[key];
71
+ const key = contextProperty(ctx, ISOLATE)?.compaction;
72
+ return key === undefined ? undefined : contextProperty(ctx, "reflect")?.store?.[key];
65
73
  }
66
74
 
67
- function releaseCompaction(ctx, previous) {
68
- const store = ctx?.reflect?.store;
69
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
70
- const current = compactionRecord(ctx);
71
- const currentFiber = current?.fiber ?? current?.ctx?.fiber;
72
- const contextFiber = ctx?.fiber;
73
- if (!current || current === previous || currentFiber !== contextFiber) return false;
75
+ function releaseCompaction(ctx, previous, key = contextProperty(ctx, ISOLATE)?.compaction) {
76
+ const store = contextProperty(ctx, "reflect")?.store;
77
+ const current = key === undefined ? undefined : store?.[key];
78
+ const currentFiber = contextProperty(current, "fiber") ?? contextProperty(contextProperty(current, "ctx"), "fiber");
79
+ const contextFiber = contextProperty(ctx, "fiber");
80
+ if (!current || current === previous || !contextFiber || currentFiber !== contextFiber) return false;
74
81
  delete store[key];
75
- if (contextFiber?.store?.compaction === current) delete contextFiber.store.compaction;
82
+ const fiberStore = contextProperty(contextFiber, "store");
83
+ if (fiberStore?.compaction === current) delete fiberStore.compaction;
76
84
  return true;
77
85
  }
78
86
 
79
87
  function detachRootStockCompaction(ctx) {
80
- const store = ctx?.reflect?.store;
88
+ const store = contextProperty(ctx, "reflect")?.store;
81
89
  const current = compactionRecord(ctx);
82
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
83
- const fiber = current?.fiber ?? current?.ctx?.fiber;
84
- const moduleName = fiber?.entry?.options?.name;
85
- if (!current || moduleName !== STOCK_ENGINE || fiber === ctx?.fiber) return false;
90
+ const key = contextProperty(ctx, ISOLATE)?.compaction;
91
+ const fiber = contextProperty(current, "fiber") ?? contextProperty(contextProperty(current, "ctx"), "fiber");
92
+ const contextFiber = contextProperty(ctx, "fiber");
93
+ const entry = entryOf(fiber);
94
+ const moduleName = contextProperty(entry, "options")?.name;
95
+ if (!current || !contextFiber || !fiber || moduleName !== STOCK_ENGINE || fiber === contextFiber) return false;
86
96
  if (compactionRecord(ctx) !== current) return false;
87
- const fiberStore = fiber?.store;
97
+ const fiberStore = contextProperty(fiber, "store");
88
98
  if (fiberStore?.compaction === current) delete fiberStore.compaction;
89
99
  delete store[key];
90
- return { store, key, current, fiber, fiberStore };
100
+ return { store, key, current, fiber, entry, fiberStore,
101
+ uid: contextProperty(fiber, "uid"), epoch: contextProperty(fiber, "_runner")?.epoch };
91
102
  }
92
103
 
93
104
  function commitRootStockCompaction(replacement) {
94
105
  if (!replacement || replacement.committed) return false;
95
- replacement.committed = true;
106
+ const options = contextProperty(replacement.entry, "options");
107
+ const disabled = options && Object.getOwnPropertyDescriptor(options, "disabled");
96
108
  try {
97
- // Cordis disposal is async. The replacement has already registered, so
98
- // the old root fiber can now drain its effects without blocking startup.
99
- const pending = replacement.fiber?.dispose?.();
100
- pending?.catch?.(() => {});
101
- } catch {}
109
+ // The loader writes unrequested disposals back as disabled. Mark this
110
+ // synchronous notification as intentional without changing its config.
111
+ if (options) options.disabled = true;
112
+ replacement.retirement = Promise.resolve(contextProperty(replacement.fiber, "dispose")?.call(replacement.fiber));
113
+ replacement.retirement.catch(() => {});
114
+ replacement.committed = true;
115
+ } finally {
116
+ if (disabled) Object.defineProperty(options, "disabled", disabled);
117
+ else if (options) delete options.disabled;
118
+ }
102
119
  return true;
103
120
  }
104
121
 
105
122
  function rollbackRootStockCompaction(replacement) {
106
123
  if (!replacement || replacement.committed) return false;
124
+ const { fiber, entry, uid, epoch, key } = replacement;
125
+ const scope = contextProperty(contextProperty(replacement.current, "ctx"), ISOLATE);
126
+ const state = contextProperty(fiber, "state");
127
+ if (uid === null || contextProperty(fiber, "uid") !== uid || contextProperty(fiber, "_runner")?.epoch !== epoch ||
128
+ (state !== undefined && ![1, 2].includes(state)) ||
129
+ (scope && scope.compaction !== key) || contextProperty(entry, "disabled")) return false;
130
+ const parent = contextProperty(entry, "parent");
131
+ const tree = contextProperty(parent, "tree");
132
+ const entryFiber = contextProperty(entry, "fiber");
133
+ if (tree && (!currentLoaderEntry(entry) || contextProperty(contextProperty(entryFiber, "ctx"), "fiber") !== fiber ||
134
+ ![1, 2].includes(loaderFiberState(parent)) || ![1, 2].includes(loaderFiberState(tree)))) return false;
107
135
  const current = replacement.store?.[replacement.key];
108
136
  if (current !== undefined && current !== replacement.current) return false;
109
137
  replacement.store[replacement.key] = replacement.current;
@@ -122,14 +150,72 @@ export function releaseRootStockCompaction(ctx, { deferDispose = false } = {}) {
122
150
  replacement.rollback = () => rollbackRootStockCompaction(replacement);
123
151
  return replacement;
124
152
  }
125
- commitRootStockCompaction(replacement);
153
+ try { commitRootStockCompaction(replacement); } catch (error) {
154
+ rollbackRootStockCompaction(replacement);
155
+ throw error;
156
+ }
126
157
  return true;
127
158
  }
128
159
 
160
+ function currentLoaderEntry(entry) {
161
+ return entry && contextProperty(contextProperty(entry, "parent"), "tree")?.store?.[contextProperty(entry, "options")?.id] === entry;
162
+ }
163
+
164
+ function loaderFiberState(loader) {
165
+ return contextProperty(contextProperty(contextProperty(loader, "ctx"), "fiber"), "state");
166
+ }
167
+
168
+ function configuredRootStock(ctx) {
169
+ const owner = entryOf(contextProperty(ctx, "fiber"), ctx);
170
+ if (contextProperty(owner, "options")?.id !== "compaction-spine") return undefined;
171
+ const stock = contextProperty(contextProperty(owner, "parent"), "tree")?.store?.["compaction-basic"];
172
+ const options = contextProperty(stock, "options");
173
+ return options?.name === STOCK_ENGINE && options.isolate?.compaction !== true && !contextProperty(stock, "disabled") ? stock : undefined;
174
+ }
175
+
176
+ function sameCompactionRealm(ctx, entry) {
177
+ const scope = contextProperty(ctx, ISOLATE);
178
+ const other = contextProperty(contextProperty(entry, "ctx"), ISOLATE);
179
+ return Boolean(scope && other && scope.compaction === other.compaction);
180
+ }
181
+
182
+ function activationCheck(ctx) {
183
+ const fiber = contextProperty(ctx, "fiber");
184
+ const entry = entryOf(fiber, ctx);
185
+ const uid = contextProperty(fiber, "uid");
186
+ const epoch = contextProperty(fiber, "_runner")?.epoch;
187
+ const scope = contextProperty(ctx, ISOLATE);
188
+ return () => !contextProperty(fiber, "runtime") ||
189
+ (uid != null && contextProperty(fiber, "uid") === uid && contextProperty(fiber, "_runner")?.epoch === epoch &&
190
+ contextProperty(ctx, ISOLATE) === scope && (!entry || (currentLoaderEntry(entry) && !contextProperty(entry, "disabled"))));
191
+ }
192
+
193
+ function restoreStockOnUnload(ctx, replacement) {
194
+ const entry = replacement.entry;
195
+ const update = contextProperty(entry, "update");
196
+ if (typeof update !== "function") return;
197
+ const installed = compactionRecord(ctx);
198
+ ctx.effect(() => async () => {
199
+ if (!replacement.committed) return;
200
+ await replacement.retirement;
201
+ const parent = contextProperty(entry, "parent");
202
+ if (!currentLoaderEntry(entry) || contextProperty(entry, "disabled") || ![1, 2].includes(loaderFiberState(parent)) ||
203
+ ![1, 2].includes(loaderFiberState(contextProperty(parent, "tree"))) ||
204
+ !sameCompactionRealm(ctx, entry)) return;
205
+ const current = compactionRecord(ctx);
206
+ if (current && current !== installed) return;
207
+ releaseCompaction(ctx, replacement.current);
208
+ await update.call(entry, {}, false, true);
209
+ const fiber = contextProperty(entry, "fiber");
210
+ await contextProperty(fiber, "await")?.call(fiber);
211
+ });
212
+ }
213
+
129
214
  function visibleTakeover(ctx, reason) {
130
215
  const line = `spine: ${MARK}。${reason}`;
131
216
  console.error(line);
132
- ctx?.logger?.warn?.(line);
217
+ try { contextProperty(ctx, "logger")?.warn?.(line); } catch {}
218
+ appendDecision(shadowDirectory(), { phase: "takeover", reason: "activation-failed", detail: reason });
133
219
  }
134
220
 
135
221
  const MARK = "本会话未接管";
@@ -155,11 +241,33 @@ const UnavailableCompaction = CompactionEngine
155
241
  : null;
156
242
 
157
243
  export default class LiveCompactEntry {
158
- static inject = ["llm", "tokenMeter", "sessions"];
244
+ static inject = Stock?.inject ?? ["llm", "tokenMeter", "sessions"];
159
245
  static Config = Schema || Stock?.Config || Engine?.Config;
160
246
 
161
247
  constructor(ctx, config) {
162
- installPresetGate(ctx, config);
248
+ const isCurrent = activationCheck(ctx);
249
+ const stock = configuredRootStock(ctx);
250
+ const stockFiber = contextProperty(stock, "fiber");
251
+ const init = contextProperty(stock, "_initTask");
252
+ if (stock && (init || (contextProperty(stockFiber, "state") === 1 && sameCompactionRealm(ctx, stock)))) {
253
+ // Loader mounts siblings in parallel. Wait for the configured stock
254
+ // entry to finish publishing before choosing the owner to replace.
255
+ return { [CORDIS_INIT]: async () => {
256
+ try { await init; } catch {} // The loader reports import failures.
257
+ if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
258
+ if (sameCompactionRealm(ctx, stock)) {
259
+ const fiber = contextProperty(stock, "fiber");
260
+ try { await contextProperty(fiber, "await")?.call(fiber); } catch {} // The loader reports activation failures.
261
+ }
262
+ if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
263
+ const engine = this.activate(ctx, config, isCurrent);
264
+ return engine[CORDIS_INIT]?.();
265
+ } };
266
+ }
267
+ return this.activate(ctx, config, isCurrent);
268
+ }
269
+
270
+ activate(ctx, config, isCurrent) {
163
271
  const previousCompaction = compactionRecord(ctx);
164
272
  let cause = loadError;
165
273
  let resolvedConfig;
@@ -173,21 +281,71 @@ export default class LiveCompactEntry {
173
281
  skipStock = true;
174
282
  }
175
283
  }
284
+ let constructed = false;
176
285
  if (!loadError && !skipStock && Engine) {
177
286
  let rootStockReplacement = false;
287
+ const rollback = () => {
288
+ releaseCompaction(ctx, previousCompaction, rootStockReplacement?.key);
289
+ rootStockReplacement?.rollback?.();
290
+ };
291
+ const commit = (engine, deferred) => {
292
+ if (!isCurrent()) { rollback(); return; }
293
+ if (deferred) engine.activateAfterInit(resolvedConfig.auto ?? true);
294
+ const commitGate = installPresetGate(ctx, config, { deferCommit: true });
295
+ if (!rootStockReplacement) { commitGate?.(); return; }
296
+
297
+ const installed = compactionRecord(ctx);
298
+ const fiber = contextProperty(ctx, "fiber");
299
+ const installedFiber = contextProperty(installed, "fiber") ?? contextProperty(contextProperty(installed, "ctx"), "fiber");
300
+ if (!installed || installedFiber !== fiber) throw new Error("spine: replacement compaction was not registered");
301
+ const { store, key } = rootStockReplacement;
302
+ restoreStockOnUnload(ctx, rootStockReplacement);
303
+ rootStockReplacement.commit();
304
+ const finishTakeover = () => {
305
+ if (!isCurrent()) return;
306
+ // Older Cordis deletes the shared slot when the retired provider's
307
+ // asynchronous disposer runs. Its replacement still owns its record.
308
+ if (store[key] === undefined && contextProperty(ctx, ISOLATE)?.compaction === key) {
309
+ store[key] = installed;
310
+ const reflect = contextProperty(ctx, "reflect");
311
+ if (contextProperty(fiber, "state") === 2) contextProperty(reflect, "notify")?.call(reflect, ["compaction"]);
312
+ }
313
+ if (compactionRecord(ctx) === installed) commitGate?.();
314
+ };
315
+ return rootStockReplacement.retirement.then(finishTakeover, finishTakeover);
316
+ };
178
317
  try {
179
318
  rootStockReplacement = releaseRootStockCompaction(ctx, { deferDispose: true });
180
- const engine = new Engine(ctx, config, resolvedConfig);
181
- rootStockReplacement?.commit?.();
319
+ if (previousCompaction && !rootStockReplacement) throw new Error("spine: compaction already provided by another engine");
320
+ constructed = true;
321
+ const deferActivation = Boolean(rootStockReplacement && typeof Engine.prototype[CORDIS_INIT] === "function");
322
+ const engine = new Engine(ctx, config, resolvedConfig, { strictActivation: true, deferActivation });
323
+ const initialize = engine[CORDIS_INIT];
324
+ if (typeof initialize === "function" || rootStockReplacement) {
325
+ engine[CORDIS_INIT] = async () => {
326
+ try {
327
+ const dispose = typeof initialize === "function" ? await initialize.call(engine) : undefined;
328
+ await commit(engine, deferActivation);
329
+ return dispose;
330
+ } catch (error) {
331
+ rollback();
332
+ visibleTakeover(ctx, reasonText(error));
333
+ throw error;
334
+ }
335
+ };
336
+ } else commit(engine, deferActivation);
182
337
  return engine;
183
338
  } catch (error) {
184
339
  cause = error instanceof Error ? error : new Error(String(error));
185
- releaseCompaction(ctx, previousCompaction);
186
- rootStockReplacement?.rollback?.();
340
+ rollback();
187
341
  skipStock = true;
188
342
  }
189
343
  }
190
344
  cause ??= new Error("spine: engine missing");
345
+ if (previousCompaction || (constructed && contextProperty(contextProperty(ctx, "fiber"), "runtime"))) {
346
+ visibleTakeover(ctx, reasonText(cause));
347
+ throw cause;
348
+ }
191
349
  if (!skipStock && process.env.SPINE_STOCK_FAIL !== "1" && Stock) {
192
350
  try {
193
351
  visibleTakeover(ctx, `这一轮用原版压缩。${reasonText(cause)}`);