dsh-live-compact 1.1.12 → 1.1.14

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,15 +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, loadBase, loadCompaction, loadSchema, STOCK_ENGINE } from "./adapter.js";
10
9
  import { configSchema, engineConfig } from "./settings.js";
11
10
  import { installPresetGate } from "./gate.js";
12
11
 
12
+ const CORDIS_INIT = Symbol.for("cordis.init");
13
+ const ISOLATE = Symbol.for("cordis.isolate");
14
+
13
15
  let Engine = null;
14
16
  let Stock = null;
15
17
  let CompactionEngine = null;
@@ -60,14 +62,13 @@ export function preflightConfig(config = {}) {
60
62
  }
61
63
 
62
64
  function compactionRecord(ctx) {
63
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
65
+ const key = ctx?.[ISOLATE]?.compaction;
64
66
  return key === undefined ? undefined : ctx?.reflect?.store?.[key];
65
67
  }
66
68
 
67
- function releaseCompaction(ctx, previous) {
69
+ function releaseCompaction(ctx, previous, key = ctx?.[ISOLATE]?.compaction) {
68
70
  const store = ctx?.reflect?.store;
69
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
70
- const current = compactionRecord(ctx);
71
+ const current = key === undefined ? undefined : store?.[key];
71
72
  const currentFiber = current?.fiber ?? current?.ctx?.fiber;
72
73
  const contextFiber = ctx?.fiber;
73
74
  if (!current || current === previous || currentFiber !== contextFiber) return false;
@@ -79,7 +80,7 @@ function releaseCompaction(ctx, previous) {
79
80
  function detachRootStockCompaction(ctx) {
80
81
  const store = ctx?.reflect?.store;
81
82
  const current = compactionRecord(ctx);
82
- const key = ctx?.[Symbol.for("cordis.isolate")]?.compaction;
83
+ const key = ctx?.[ISOLATE]?.compaction;
83
84
  const fiber = current?.fiber ?? current?.ctx?.fiber;
84
85
  const moduleName = fiber?.entry?.options?.name;
85
86
  if (!current || moduleName !== STOCK_ENGINE || fiber === ctx?.fiber) return false;
@@ -87,23 +88,37 @@ function detachRootStockCompaction(ctx) {
87
88
  const fiberStore = fiber?.store;
88
89
  if (fiberStore?.compaction === current) delete fiberStore.compaction;
89
90
  delete store[key];
90
- return { store, key, current, fiber, fiberStore };
91
+ return { store, key, current, fiber, fiberStore, uid: fiber?.uid, epoch: fiber?._runner?.epoch };
91
92
  }
92
93
 
93
94
  function commitRootStockCompaction(replacement) {
94
95
  if (!replacement || replacement.committed) return false;
95
- replacement.committed = true;
96
+ const options = replacement.fiber?.entry?.options;
97
+ const disabled = options && Object.getOwnPropertyDescriptor(options, "disabled");
96
98
  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 {}
99
+ // The loader writes unrequested disposals back as disabled. Mark this
100
+ // synchronous notification as intentional without changing its config.
101
+ if (options) options.disabled = true;
102
+ replacement.retirement = Promise.resolve(replacement.fiber?.dispose?.());
103
+ replacement.retirement.catch(() => {});
104
+ replacement.committed = true;
105
+ } finally {
106
+ if (disabled) Object.defineProperty(options, "disabled", disabled);
107
+ else if (options) delete options.disabled;
108
+ }
102
109
  return true;
103
110
  }
104
111
 
105
112
  function rollbackRootStockCompaction(replacement) {
106
113
  if (!replacement || replacement.committed) return false;
114
+ const { fiber, uid, epoch, key } = replacement;
115
+ const entry = fiber?.entry;
116
+ const scope = replacement.current.ctx?.[ISOLATE];
117
+ if (fiber?.uid === null || fiber?.uid !== uid || fiber?._runner?.epoch !== epoch ||
118
+ (fiber?.state !== undefined && ![1, 2].includes(fiber.state)) ||
119
+ (scope && scope.compaction !== key) || entry?.disabled) return false;
120
+ if (entry?.parent?.tree && (!currentLoaderEntry(entry) || entry.fiber?.ctx?.fiber !== fiber ||
121
+ ![1, 2].includes(entry.parent.ctx?.fiber?.state) || ![1, 2].includes(entry.parent.tree.ctx?.fiber?.state))) return false;
107
122
  const current = replacement.store?.[replacement.key];
108
123
  if (current !== undefined && current !== replacement.current) return false;
109
124
  replacement.store[replacement.key] = replacement.current;
@@ -122,14 +137,62 @@ export function releaseRootStockCompaction(ctx, { deferDispose = false } = {}) {
122
137
  replacement.rollback = () => rollbackRootStockCompaction(replacement);
123
138
  return replacement;
124
139
  }
125
- commitRootStockCompaction(replacement);
140
+ try { commitRootStockCompaction(replacement); } catch (error) {
141
+ rollbackRootStockCompaction(replacement);
142
+ throw error;
143
+ }
126
144
  return true;
127
145
  }
128
146
 
147
+ function currentLoaderEntry(entry) {
148
+ return entry && entry.parent?.tree?.store?.[entry.options?.id] === entry;
149
+ }
150
+
151
+ function configuredRootStock(ctx) {
152
+ const owner = ctx.fiber?.entry;
153
+ if (owner?.options?.id !== "compaction-spine") return undefined;
154
+ const stock = owner.parent?.tree?.store?.["compaction-basic"];
155
+ return stock?.options?.name === STOCK_ENGINE && stock.options.isolate?.compaction !== true && !stock.disabled ? stock : undefined;
156
+ }
157
+
158
+ function sameCompactionRealm(ctx, entry) {
159
+ return ctx[ISOLATE]?.compaction === entry.ctx?.[ISOLATE]?.compaction;
160
+ }
161
+
162
+ function activationCheck(ctx) {
163
+ const fiber = ctx.fiber;
164
+ const entry = fiber?.entry;
165
+ const uid = fiber?.uid;
166
+ const epoch = fiber?._runner?.epoch;
167
+ const scope = ctx[ISOLATE];
168
+ return () => !fiber?.runtime || (uid != null && fiber.uid === uid && fiber._runner?.epoch === epoch &&
169
+ ctx[ISOLATE] === scope && (!entry || (currentLoaderEntry(entry) && !entry.disabled)));
170
+ }
171
+
172
+ function restoreStockOnUnload(ctx, replacement) {
173
+ const entry = replacement.fiber?.entry;
174
+ if (typeof entry?.update !== "function") return;
175
+ const installed = compactionRecord(ctx);
176
+ ctx.effect(() => async () => {
177
+ if (!replacement.committed) return;
178
+ await replacement.retirement;
179
+ const parent = entry.parent?.ctx?.fiber;
180
+ const tree = entry.parent?.tree?.ctx?.fiber;
181
+ if (!currentLoaderEntry(entry) || entry.disabled || ![1, 2].includes(parent?.state) ||
182
+ ![1, 2].includes(tree?.state) ||
183
+ entry.ctx?.[ISOLATE]?.compaction !== ctx[ISOLATE]?.compaction) return;
184
+ const current = compactionRecord(ctx);
185
+ if (current && current !== installed) return;
186
+ releaseCompaction(ctx, replacement.current);
187
+ await entry.update({}, false, true);
188
+ await entry.fiber?.await?.();
189
+ });
190
+ }
191
+
129
192
  function visibleTakeover(ctx, reason) {
130
193
  const line = `spine: ${MARK}。${reason}`;
131
194
  console.error(line);
132
- ctx?.logger?.warn?.(line);
195
+ try { contextProperty(ctx, "logger")?.warn?.(line); } catch {}
133
196
  }
134
197
 
135
198
  const MARK = "本会话未接管";
@@ -155,11 +218,30 @@ const UnavailableCompaction = CompactionEngine
155
218
  : null;
156
219
 
157
220
  export default class LiveCompactEntry {
158
- static inject = ["llm", "tokenMeter", "sessions"];
221
+ static inject = Stock?.inject ?? ["llm", "tokenMeter", "sessions"];
159
222
  static Config = Schema || Stock?.Config || Engine?.Config;
160
223
 
161
224
  constructor(ctx, config) {
162
- installPresetGate(ctx, config);
225
+ const isCurrent = activationCheck(ctx);
226
+ const stock = configuredRootStock(ctx);
227
+ if (stock && (stock._initTask || (stock.fiber?.state === 1 && sameCompactionRealm(ctx, stock)))) {
228
+ // Loader mounts siblings in parallel. Wait for the configured stock
229
+ // entry to finish publishing before choosing the owner to replace.
230
+ return { [CORDIS_INIT]: async () => {
231
+ try { await stock._initTask; } catch {} // The loader reports import failures.
232
+ if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
233
+ if (sameCompactionRealm(ctx, stock)) {
234
+ try { await stock.fiber?.await?.(); } catch {} // The loader reports activation failures.
235
+ }
236
+ if (!isCurrent() || configuredRootStock(ctx) !== stock) return;
237
+ const engine = this.activate(ctx, config, isCurrent);
238
+ return engine[CORDIS_INIT]?.();
239
+ } };
240
+ }
241
+ return this.activate(ctx, config, isCurrent);
242
+ }
243
+
244
+ activate(ctx, config, isCurrent) {
163
245
  const previousCompaction = compactionRecord(ctx);
164
246
  let cause = loadError;
165
247
  let resolvedConfig;
@@ -173,21 +255,53 @@ export default class LiveCompactEntry {
173
255
  skipStock = true;
174
256
  }
175
257
  }
258
+ let constructed = false;
176
259
  if (!loadError && !skipStock && Engine) {
177
260
  let rootStockReplacement = false;
261
+ const rollback = () => {
262
+ releaseCompaction(ctx, previousCompaction, rootStockReplacement?.key);
263
+ rootStockReplacement?.rollback?.();
264
+ };
265
+ const commit = (engine, deferred) => {
266
+ if (!isCurrent()) { rollback(); return; }
267
+ if (deferred) engine.activateAfterInit(resolvedConfig.auto ?? true);
268
+ const commitGate = installPresetGate(ctx, config, { deferCommit: true });
269
+ if (rootStockReplacement) restoreStockOnUnload(ctx, rootStockReplacement);
270
+ rootStockReplacement?.commit?.();
271
+ commitGate?.();
272
+ };
178
273
  try {
179
274
  rootStockReplacement = releaseRootStockCompaction(ctx, { deferDispose: true });
180
- const engine = new Engine(ctx, config, resolvedConfig);
181
- rootStockReplacement?.commit?.();
275
+ if (previousCompaction && !rootStockReplacement) throw new Error("spine: compaction already provided by another engine");
276
+ constructed = true;
277
+ const deferActivation = Boolean(rootStockReplacement && typeof Engine.prototype[CORDIS_INIT] === "function");
278
+ const engine = new Engine(ctx, config, resolvedConfig, { strictActivation: true, deferActivation });
279
+ const initialize = engine[CORDIS_INIT];
280
+ if (typeof initialize === "function") {
281
+ engine[CORDIS_INIT] = async () => {
282
+ try {
283
+ const dispose = await initialize.call(engine);
284
+ commit(engine, deferActivation);
285
+ return dispose;
286
+ } catch (error) {
287
+ rollback();
288
+ visibleTakeover(ctx, reasonText(error));
289
+ throw error;
290
+ }
291
+ };
292
+ } else commit(engine, deferActivation);
182
293
  return engine;
183
294
  } catch (error) {
184
295
  cause = error instanceof Error ? error : new Error(String(error));
185
- releaseCompaction(ctx, previousCompaction);
186
- rootStockReplacement?.rollback?.();
296
+ rollback();
187
297
  skipStock = true;
188
298
  }
189
299
  }
190
300
  cause ??= new Error("spine: engine missing");
301
+ if (previousCompaction || (constructed && ctx.fiber?.runtime)) {
302
+ visibleTakeover(ctx, reasonText(cause));
303
+ throw cause;
304
+ }
191
305
  if (!skipStock && process.env.SPINE_STOCK_FAIL !== "1" && Stock) {
192
306
  try {
193
307
  visibleTakeover(ctx, `这一轮用原版压缩。${reasonText(cause)}`);
package/thunder.js CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  const PROSE_TOKEN_CAP = 32000;
9
+ const CJK_CHARACTER = /[\p{Script=Han}\p{Script=Hangul}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}]/u;
9
10
 
10
11
  export function sharedPrefixLength(previous, next) {
11
12
  if (!previous || !next) return 0;
@@ -28,9 +29,17 @@ export function decideThunder({ previous, next, modelKind, prefixTokens, attachM
28
29
  return "attach";
29
30
  }
30
31
 
31
- function estimateTokens(text) {
32
- const cjk = (text.match(/[\u4e00-\u9fff]/g) || []).length;
33
- return Math.ceil(cjk / 1.5 + (text.length - cjk) / 4);
32
+ function limitProse(text, tokens) {
33
+ // Twelfths of a token preserve the estimate at exact budget boundaries.
34
+ const budget = Math.floor(tokens) * 12;
35
+ let cost = 0;
36
+ let end = 0;
37
+ for (const character of text) {
38
+ cost += CJK_CHARACTER.test(character) ? 8 : character.length * 3;
39
+ if (cost > budget) return text.slice(0, end);
40
+ end += character.length;
41
+ }
42
+ return text;
34
43
  }
35
44
 
36
45
  export function buildSendLess({ taskLine, uncovered, facts, proseTokens = PROSE_TOKEN_CAP }) {
@@ -42,17 +51,7 @@ export function buildSendLess({ taskLine, uncovered, facts, proseTokens = PROSE_
42
51
  }
43
52
  return `[unknown] ${String(fact)}`;
44
53
  }).filter(Boolean);
45
- let prose = uncovered || "";
46
- if (estimateTokens(prose) > proseTokens) {
47
- let low = 0;
48
- let high = prose.length;
49
- while (low < high) {
50
- const mid = Math.ceil((low + high) / 2);
51
- if (estimateTokens(prose.slice(0, mid)) <= proseTokens) low = mid;
52
- else high = mid - 1;
53
- }
54
- prose = prose.slice(0, low);
55
- }
54
+ const prose = limitProse(uncovered || "", proseTokens);
56
55
  return [
57
56
  taskLine || "Continue the current task.",
58
57
  "Facts already copied locally:",