dsh-context-compression-improved 0.9.0 → 0.9.3

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/CHANGELOG.md CHANGED
@@ -2,6 +2,62 @@
2
2
 
3
3
  All notable changes use this file. The project follows semantic versioning after `0.1.0`.
4
4
 
5
+ ## 0.9.3 - 2026-10-08
6
+
7
+ ### Fixed
8
+
9
+ - **≤0.1.1 resume killer: tool-result-pruner loader entry failed to import**.
10
+ The 0.1.0/0.1.1 host loader module table serves a `@deepseek-ai/dsh-session`
11
+ without the `SessionSeq` / `deriveEventMessage` runtime exports; the static
12
+ named imports in `pruner.ts` / `runtime/measurement.ts` died at ESM link
13
+ time, the loader entry failed to mount, and the whole `standard` agent
14
+ preset mount failed — every session resume on the two oldest cells errored
15
+ with "failed to apply loader entry compaction … does not provide an export
16
+ named 'SessionSeq'" (2026-10-08 five-cell reproduction). Both imports are
17
+ now namespace soft-imports with feature-detected fallbacks: `SessionSeq`
18
+ degrades to identity (old-line session seqs are plain numbers; the brand is
19
+ new-line paranoia), `deriveEventMessage` degrades to null which the
20
+ measurement adapter already maps to `unavailableTokenCount`. CJS-interop
21
+ shapes (named exports under `default`) are covered too.
22
+
23
+ ## 0.9.2 - 2026-10-08
24
+
25
+ ### Reverted
26
+
27
+ - **Standalone settings.section restored (family-tab consolidation rolled back
28
+ for this plugin)**: the 上下文压缩选择器 sidebar entry (`settings.section`,
29
+ order 17, the exact 0.9.0 registration and component identity) is back as the
30
+ only settings-nav seat; the `dsh-family.tab` contributor tab introduced in
31
+ 0.9.1 is removed. 2026-10-08 user verdict: perm-gate and cci were never in
32
+ the family tab-ification scope — both plugins ship independent insections.
33
+ The `plugins.bundle.config` bundle-detail card is unchanged and keeps the
34
+ shared `sectionViaAdapter` closure adapter (now bundle-card-only).
35
+ - Tests: the four client specs (`settings-seat` / `code-skeleton` /
36
+ `custom-contract` / `preset-options-write`) are restored to the 0.9.0
37
+ contracts — settings.section seat pinned at order 17 with
38
+ `ContextCompressionSettingsSection` as the mounted component.
39
+
40
+ ## 0.9.1 - 2026-10-08
41
+
42
+ ### Changed
43
+
44
+ - **Settings consolidated into the family in-section tab**: the top-level
45
+ `settings.section` sidebar entry (上下文压缩选择器) is retired; the settings
46
+ panel now appears only as a contributor tab inside the 起子插件设置 family
47
+ section (`dsh-family.tab`, order 55), matching the 2026-10-08 fleet-wide
48
+ consolidation decision (perm-gate compat.8 removes its duplicated seats in
49
+ the same batch). The component goes through the shared closure
50
+ `useCompression` adapter (extracted from the `plugins.bundle.config` card,
51
+ which now reuses it) because neither the family-tab nor the bundle-detail
52
+ render chain maps `inject.hooks` into component hooks. Eager-bound `tNav`
53
+ label retained (search-index 0.5.3 family-tab incident). Server-side
54
+ settings bridge, lease, estimator-catalog and savings routes unchanged.
55
+
56
+ ### Fixed
57
+
58
+ - `packages/selector/dsh.plugin.json` version metadata was stale at
59
+ `0.9.0-alpha.4` while the package shipped 0.9.0.
60
+
5
61
  ## 0.9.0 - 2026-10-08
6
62
 
7
63
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.9.0",
3
+ "version": "0.9.3",
4
4
  "publishConfig": {
5
5
  "tag": "latest"
6
6
  },
@@ -65,6 +65,7 @@
65
65
  "test:watch": "vitest",
66
66
  "test:built": "vitest run --config vitest.built.config.ts",
67
67
  "test:e2e:packed": "node scripts/packed-install-e2e.mjs",
68
+ "test:browser:e2e": "node scripts/cell-browser-e2e.mjs",
68
69
  "test:unit": "vitest run",
69
70
  "verify:release": "node scripts/verify-release.mjs",
70
71
  "pack:dry-run": "pnpm -r --if-present run pack:dry-run"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-context-compression-improved",
3
- "version": "0.9.0-alpha.4",
3
+ "version": "0.9.2",
4
4
  "main": "./lib/index.js",
5
5
  "description": "Auditable tool-result context-compression selector with code-skeleton gate for DeepSeek Harness",
6
6
  "engines": {
@@ -3395,6 +3395,27 @@ window.__ModuleLoader__.load({
3395
3395
  }
3396
3396
  };
3397
3397
  };
3398
+ const sectionViaAdapter = (props) => {
3399
+ const inj = injected();
3400
+ const scope = inj.hooks?.compression;
3401
+ const useCompression = (selector) => {
3402
+ if (!scope) return selector({
3403
+ status: "loading",
3404
+ value: void 0,
3405
+ revision: void 0,
3406
+ writable: false,
3407
+ base: void 0,
3408
+ user: void 0,
3409
+ mode: "memory"
3410
+ });
3411
+ return (0, react.useSyncExternalStore)(scope.subscribe, () => selector(scope.getSnapshot()));
3412
+ };
3413
+ return (0, react.createElement)(ContextCompressionSettingsSection, {
3414
+ ...inj,
3415
+ ...props,
3416
+ useCompression
3417
+ });
3418
+ };
3398
3419
  try {
3399
3420
  ctx.slots.inject("settings.section", () => ctx.slots.register({
3400
3421
  name: "settings.section",
@@ -3405,7 +3426,7 @@ window.__ModuleLoader__.load({
3405
3426
  inject: injected
3406
3427
  }, ContextCompressionSettingsSection));
3407
3428
  } catch (error) {
3408
- console.warn("[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):", error);
3429
+ console.warn("[dsh-context-compression-improved] settings.section 注册失败(宿主无该槽,静默缺席):", error);
3409
3430
  }
3410
3431
  try {
3411
3432
  ctx.slots.inject("conversation.input.left", () => ctx.slots.register({
@@ -3425,27 +3446,7 @@ window.__ModuleLoader__.load({
3425
3446
  name: "plugins.bundle.config",
3426
3447
  key: "dsh-context-compression-improved",
3427
3448
  locale: NS
3428
- }, (props) => {
3429
- const inj = injected();
3430
- const scope = inj.hooks?.compression;
3431
- const useCompression = (selector) => {
3432
- if (!scope) return selector({
3433
- status: "loading",
3434
- value: void 0,
3435
- revision: void 0,
3436
- writable: false,
3437
- base: void 0,
3438
- user: void 0,
3439
- mode: "memory"
3440
- });
3441
- return (0, react.useSyncExternalStore)(scope.subscribe, () => selector(scope.getSnapshot()));
3442
- };
3443
- return (0, react.createElement)(ContextCompressionSettingsSection, {
3444
- ...inj,
3445
- ...props,
3446
- useCompression
3447
- });
3448
- }));
3449
+ }, sectionViaAdapter));
3449
3450
  } catch (error) {
3450
3451
  console.warn("[dsh-context-compression-improved] plugins.bundle.config 注册失败(旧宿主无该槽,静默缺席):", error);
3451
3452
  }
@@ -4,7 +4,7 @@ import z from "@deepseek-ai/schemastery";
4
4
  import { createHash } from "node:crypto";
5
5
  import { Service } from "@deepseek-ai/cordis";
6
6
  import { createUserMessage, freezeMessage } from "@deepseek-ai/dsh-llm";
7
- import { SessionSeq, deriveEventMessage } from "@deepseek-ai/dsh-session";
7
+ import * as dshSessionNamespace from "@deepseek-ai/dsh-session";
8
8
  import { readFileSync } from "node:fs";
9
9
  import { Tokenizer } from "@huggingface/tokenizers";
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -469,6 +469,8 @@ function emptyResult() {
469
469
  }
470
470
  //#endregion
471
471
  //#region src/runtime/measurement.ts
472
+ const dshSessionSoft$1 = dshSessionNamespace;
473
+ const deriveEventMessage = dshSessionSoft$1.deriveEventMessage ?? dshSessionSoft$1.default?.deriveEventMessage ?? (() => null);
472
474
  /**
473
475
  * Character pressure of one model-visible content array, measured on the same
474
476
  * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
@@ -3965,6 +3967,8 @@ function emitCompressionAudit(logger, record) {
3965
3967
  *
3966
3968
  * @module dsh-context-compression-improved-runtime
3967
3969
  */
3970
+ const dshSessionSoft = dshSessionNamespace;
3971
+ const SessionSeq = dshSessionSoft.SessionSeq ?? dshSessionSoft.default?.SessionSeq ?? ((value) => value);
3968
3972
  /** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
3969
3973
  function originalTextForSavings(candidate) {
3970
3974
  return flattenPlainText(viewToolResult(candidate.event.data.message).blocks);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-compression-improved",
3
- "version": "0.9.0",
3
+ "version": "0.9.3",
4
4
  "description": "One-install context-compression selector bundle for DeepSeek Harness",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -314,10 +314,29 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
314
314
  },
315
315
  }
316
316
  }
317
- // 设置 → 上下文压缩 直挂分节(0.1.1 契约;0.1.5 官方分节也注册在此,未声明槽
318
- // 的注册会在激活期抛错,故 try/catch 守卫 —— 同 dsh-prime-memory 的双槽冗余)。
319
- // 只挂这一处:再注册 `settings.plugins.tab` / `settings.plugin.item` 会在
320
- // 设置里同时出现独立分节和插件卡片,重复展示同一张面板。
317
+ // bundle 详情卡的组件适配器:closure 自取 injected() 并把 hooks.compression
318
+ // 手工适配成 useCompression(useSyncExternalStore 包装)。这条渲染链不带
319
+ // hookContext、宿主不会做 hooks 映射(0.1.7 真机实证,见下方 bundle 卡注释)。
320
+ const sectionViaAdapter = (props: { close?: () => void }) => {
321
+ const inj = injected()
322
+ const scope = inj.hooks?.compression
323
+ const useCompression = <T,>(selector: (snapshot: ScopeSnapshot<ContextCompressionSettings>) => T): T => {
324
+ if (!scope) return selector({ status: 'loading', value: undefined, revision: undefined, writable: false, base: undefined, user: undefined, mode: 'memory' })
325
+ return useSyncExternalStore(
326
+ scope.subscribe,
327
+ () => selector(scope.getSnapshot()),
328
+ )
329
+ }
330
+ return createElement(ContextCompressionSettingsSection, { ...inj, ...props, useCompression } as never)
331
+ }
332
+
333
+ // 设置 → 上下文压缩 直挂分节(2026-10-08 回退定案:本插件不在家族 tab 化
334
+ // 范围内——上下文压缩选择器是独立 insection,0.1.1 契约、0.1.0-0.2.0 单注册
335
+ // 点,恢复 0.9.0 原注册)。只挂这一处:再注册 `settings.plugins.tab` /
336
+ // `settings.plugin.item` 会在设置里同时出现独立分节和插件卡片,重复展示
337
+ // 同一张面板。未声明槽的注册会在激活期抛错,故 try/catch 守卫(同
338
+ // dsh-prime-memory 的双槽冗余)。label 沿用已 eager bind 的 tNav(search-index
339
+ // 0.5.3 family-tab incident 的教训通用:label 在宿主渲染期求值,禁懒取 locale)。
321
340
  try {
322
341
  ctx.slots.inject('settings.section', () => ctx.slots.register({
323
342
  name: 'settings.section',
@@ -328,7 +347,7 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
328
347
  inject: injected,
329
348
  }, ContextCompressionSettingsSection))
330
349
  } catch (error) {
331
- console.warn('[dsh-context-compression-improved] settings.section 注册失败(新宿主已收编):', error)
350
+ console.warn('[dsh-context-compression-improved] settings.section 注册失败(宿主无该槽,静默缺席):', error)
332
351
  }
333
352
 
334
353
  // 输入栏左座(0.1.5+ 宿主):组件刻意空渲染——注册此座位只为接收宿主的
@@ -356,25 +375,14 @@ let readMonitorPanelEnabled = (): boolean => monitorPanelEnabledCache
356
375
  // abdicate 成 data-slot-error 死格,且 abdication 本会话粘滞不再重试;
357
376
  // ②locale: NS 必须保留 —— 它是宿主标准包 t(localeSeat)的唯一来源;
358
377
  // ③组件闭包自取 injected(),并把 hooks.compression 手工适配成 useCompression
359
- // (useSyncExternalStore 包装)。读写仍走 configForms 原生臂(宿主桥)。
378
+ // (useSyncExternalStore 包装)——已抽为上方 sectionViaAdapter 共用。
360
379
  // 老宿主无该槽 → 激活期抛错由 try/catch 吞掉,静默缺席。
361
380
  try {
362
381
  ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
363
382
  name: 'plugins.bundle.config',
364
383
  key: 'dsh-context-compression-improved',
365
384
  locale: NS,
366
- }, (props: { close?: () => void }) => {
367
- const inj = injected()
368
- const scope = inj.hooks?.compression
369
- const useCompression = <T,>(selector: (snapshot: ScopeSnapshot<ContextCompressionSettings>) => T): T => {
370
- if (!scope) return selector({ status: 'loading', value: undefined, revision: undefined, writable: false, base: undefined, user: undefined, mode: 'memory' })
371
- return useSyncExternalStore(
372
- scope.subscribe,
373
- () => selector(scope.getSnapshot()),
374
- )
375
- }
376
- return createElement(ContextCompressionSettingsSection, { ...inj, ...props, useCompression } as never)
377
- }))
385
+ }, sectionViaAdapter))
378
386
  } catch (error) {
379
387
  console.warn('[dsh-context-compression-improved] plugins.bundle.config 注册失败(旧宿主无该槽,静默缺席):', error)
380
388
  }
@@ -13,7 +13,22 @@ import type { Context } from '@deepseek-ai/cordis'
13
13
  import z from '@deepseek-ai/schemastery'
14
14
  import { createUserMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
15
15
  import type { ContentBlock, ToolCallId, UserMessage } from '@deepseek-ai/dsh-llm'
16
- import { SessionSeq } from '@deepseek-ai/dsh-session'
16
+ // ≤0.1.1 宿主 loader 模块表的 dsh-session 没有 SessionSeq 运行时导出——静态
17
+ // named import 在 ESM 链接期即炸,loader entry(tool-result-pruner)mount 失败
18
+ // 连累整个 standard 预设(会话 resume 全挂,2026-10-08 五格 0.1.0/0.1.1 实证)。
19
+ // namespace 软取(链接零失败)+ 恒等回退:老线 session 事件 seq 本就是裸 number,
20
+ // 身份封印仅是新线防呆。CJS interop 形态(named 挂 default 下)一并兼容。
21
+ import * as dshSessionNamespace from '@deepseek-ai/dsh-session'
22
+ import type { SessionSeq as SessionSeqBrand } from '@deepseek-ai/dsh-session'
23
+ const dshSessionSoft = dshSessionNamespace as unknown as {
24
+ SessionSeq?: (value: number) => SessionSeqBrand
25
+ default?: { SessionSeq?: (value: number) => SessionSeqBrand }
26
+ }
27
+ const SessionSeqImpl =
28
+ dshSessionSoft.SessionSeq ??
29
+ dshSessionSoft.default?.SessionSeq ??
30
+ ((value: number) => value as SessionSeqBrand)
31
+ const SessionSeq = SessionSeqImpl as (value: number) => SessionSeqBrand
17
32
 
18
33
  // 0.1.7-rc.2 removed the shared 'plugin' source kind — each producer declares
19
34
  // its own kind in its own module (official pattern: compaction's
@@ -2,7 +2,20 @@
2
2
 
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
4
  import type { ContentBlock, TokenUsage } from '@deepseek-ai/dsh-llm'
5
- import { deriveEventMessage } from '@deepseek-ai/dsh-session'
5
+ // ≤0.1.1 宿主 dsh-session 无 deriveEventMessage 运行时导出(SessionSeq 同因,
6
+ // 见 pruner.ts 顶部注):namespace 软取,缺席落恒 null——调用方 L152 已有
7
+ // message===null → unavailableTokenCount 的降级路径,测量退化为 unavailable
8
+ // 而不是炸 loader entry。
9
+ import * as dshSessionNamespace from '@deepseek-ai/dsh-session'
10
+ const dshSessionSoft = dshSessionNamespace as unknown as {
11
+ deriveEventMessage?: (event: never) => unknown
12
+ default?: { deriveEventMessage?: (event: never) => unknown }
13
+ }
14
+ const deriveEventMessageImpl =
15
+ dshSessionSoft.deriveEventMessage ??
16
+ dshSessionSoft.default?.deriveEventMessage ??
17
+ (() => null)
18
+ const deriveEventMessage = deriveEventMessageImpl as typeof import('@deepseek-ai/dsh-session').deriveEventMessage
6
19
  import { sessionEvents } from './session-events.ts'
7
20
  import type { Session } from '@deepseek-ai/dsh-session'
8
21
  import type {} from '@deepseek-ai/dsh-token-meter'
@@ -0,0 +1,354 @@
1
+ // cell-browser-e2e.mjs —— 六线宿主格子 × 浏览器面 e2e(发版前后均可跑)。
2
+ //
3
+ // 与 packed-install-e2e.mjs 的分工:那条门在官方 dsh-v0.2.0-rc.1 克隆上验证
4
+ // 安装生命周期与 boot 探针(单线、无浏览器交互);本脚本补的是**多线浏览器面**:
5
+ // 按 scripts/hosts.mjs 的六线抽样各备一个格子,从 npm 安装宿主与插件,真启动
6
+ // web profile,用 CDP 驱动真实浏览器——设置节/详情卡渲染、Profile 点击写穿、
7
+ // 桥读回。0.1.0/0.1.1/0.1.2 三线只有这条门有浏览器面证据。
8
+ //
9
+ // 用法:
10
+ // pnpm test:browser:e2e # 六格全跑(首次会逐格 pnpm 装宿主)
11
+ // pnpm test:browser:e2e 0.1.5-rc.3 # 只跑一格(重跑/排障)
12
+ // 环境变量:
13
+ // CELL_E2E_DIR 格子根目录(默认 <repo>/.cell-e2e,已 gitignore;删掉即全量重备)
14
+ // PLUGIN_SPEC 插件安装 spec(默认 latest=验证 npm 发布物;可指 file:tgz 或本地目录)
15
+ // CHROME_PATH Chrome 可执行文件(默认查标准安装位置)
16
+ // 前提:pnpm 在 PATH;Chrome/Chromium 可用;registry 可达(宿主 15 rc 在 npm 上齐全)。
17
+ //
18
+ // 钉版矩阵来源(实测在案,见 .agents/plans/cci-compat-legacy-15rc/tasks.md):
19
+ // - 0.1.1 线宿主崩于「patch 层监视需要 Cordis HMR 服务」→ sandbox 依赖
20
+ // @deepseek-ai/cordis-plugin-hmr ^1.0.16 + profile 补丁行 insert hmr(root:[]);
21
+ // - 0.1.2 线同病,但 registerConfig 自 1.0.17 起才有 → hmr 钉 1.0.17;
22
+ // - 其余线最小依赖 @deepseek-ai/dsh@<rc> 即可(宿主自带运行时依赖)。
23
+ import fs from 'node:fs'
24
+ import path from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
26
+ import { spawn } from 'node:child_process'
27
+
28
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
29
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms))
30
+
31
+ const CELL_ROOT = process.env.CELL_E2E_DIR ?? path.join(repoRoot, '.cell-e2e')
32
+ // 默认=仓库当前版本:验证「这个版本」在六线上的表现,且精确 spec 免疫
33
+ // registry 的 dist-tag metadata 缓存(latest 曾解析到陈旧 0.8.0)。
34
+ const PLUGIN_SPEC = process.env.PLUGIN_SPEC
35
+ ?? JSON.parse(fs.readFileSync(path.join(repoRoot, 'packages/selector/package.json'), 'utf8')).version
36
+ const NPMRC = 'registry=https://registry.npmjs.org\n'
37
+ // pnpm ≥12 对带构建脚本的依赖默认拒绝并把安装变成非零退出——宿主运行时需要
38
+ // node-pty/koffi/protobufjs/dsh-subprocess-local 的原生/后装产物。pnpm 12.5 的
39
+ // 权威开关是 allowBuilds 布尔 map(onlyBuiltDependencies 清单会被无视)。
40
+ const ALLOW_BUILDS = [
41
+ 'allowBuilds:',
42
+ ' "@deepseek-ai/dsh-subprocess-local": true',
43
+ ' "@google/genai": true',
44
+ ' koffi: true',
45
+ ' node-pty: true',
46
+ ' protobufjs: true',
47
+ '',
48
+ ].join('\n')
49
+ // sandbox:默认 autoInstallPeers(true)——老宿主的 peer 闭包(dsh-timeout 等
50
+ // 只声明为 peer 的包)靠它补全,缺了 web client 直接不激活。
51
+ const SANDBOX_WORKSPACE_YAML = 'packages:\n - .\n\nnodeLinker: hoisted\n' + ALLOW_BUILDS
52
+ // profile web:只装插件本体,peers 不自动补(宿主运行时靠 sandbox 闭包兜底)。
53
+ const WEB_WORKSPACE_YAML = 'packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n' + ALLOW_BUILDS
54
+
55
+ // 六线抽样 = 计划 Gate 矩阵的口径(15rc 全测已被用户裁决为抽样即可)。
56
+ // cordis 家族钉版 = 实证格子矩阵:npm 上的 @deepseek-ai/dsh 会把老线拖到新
57
+ // cordis(0.1.0-rc.2 + cordis 4.0.4/loader 1.0.5 → web client 不激活),
58
+ // 各线必须钉它实证能跑的组合。hmr = 0.1.1/0.1.2 宿主的 patch 层监视必需
59
+ // (registerConfig 自 1.0.17 起,0.1.1 线钉 ^1.0.16),并配 profile 补丁行。
60
+ const HOSTS = [
61
+ {
62
+ rc: '0.1.0-rc.2', generation: 'legacy',
63
+ pins: { '@deepseek-ai/cordis': '4.0.2', '@deepseek-ai/cordis-plugin-group': '1.0.2', '@deepseek-ai/cordis-plugin-hmr': '1.0.17', '@deepseek-ai/cordis-plugin-include': '1.0.7', '@deepseek-ai/cordis-plugin-loader': '1.0.3', '@deepseek-ai/cordis-plugin-timer': '1.1.4' },
64
+ },
65
+ // hmr 必须精确钉:^1.0.16 会浮动到 1.0.19+,而 registerConfig 的签名在
66
+ // 1.0.19 与两条老线都不兼容(host 在 web url 打印后崩于 registerConfig)。
67
+ { rc: '0.1.1-rc.2', generation: 'legacy', pins: { '@deepseek-ai/cordis-plugin-hmr': '1.0.16' }, patchHmr: true },
68
+ { rc: '0.1.2-rc.1', generation: 'legacy', pins: { '@deepseek-ai/cordis-plugin-hmr': '1.0.17' }, patchHmr: true },
69
+ {
70
+ rc: '0.1.5-rc.3', generation: 'legacy',
71
+ pins: { '@deepseek-ai/cordis': '4.0.2', '@deepseek-ai/cordis-plugin-group': '1.0.2', '@deepseek-ai/cordis-plugin-hmr': '1.0.17', '@deepseek-ai/cordis-plugin-include': '1.0.7', '@deepseek-ai/cordis-plugin-loader': '1.0.3', '@deepseek-ai/cordis-plugin-timer': '1.1.4' },
72
+ },
73
+ {
74
+ rc: '0.1.7-rc.1', generation: 'modern',
75
+ pins: { '@deepseek-ai/cordis': '4.0.4', '@deepseek-ai/cordis-plugin-group': '1.0.4', '@deepseek-ai/cordis-plugin-hmr': '1.0.19', '@deepseek-ai/cordis-plugin-include': '1.0.9', '@deepseek-ai/cordis-plugin-loader': '1.0.5', '@deepseek-ai/cordis-plugin-timer': '1.1.6' },
76
+ },
77
+ { rc: '0.2.0-rc.2', generation: 'modern', pins: {} },
78
+ ]
79
+ const ONLY = process.argv[2]
80
+ const HOSTS_TO_RUN = ONLY ? HOSTS.filter(h => h.rc === ONLY) : HOSTS
81
+ if (ONLY && HOSTS_TO_RUN.length === 0) {
82
+ console.error(`unknown host rc "${ONLY}"; one of: ${HOSTS.map(h => h.rc).join(', ')}`)
83
+ process.exit(2)
84
+ }
85
+
86
+ const findChrome = () => {
87
+ if (process.env.CHROME_PATH) return process.env.CHROME_PATH
88
+ const candidates = process.platform === 'win32' ? [
89
+ 'C:/Program Files/Google/Chrome/Application/chrome.exe',
90
+ 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
91
+ ] : [
92
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
93
+ '/usr/bin/google-chrome',
94
+ '/usr/bin/chromium-browser',
95
+ ]
96
+ return candidates.find(p => fs.existsSync(p))
97
+ }
98
+
99
+ const run = (command, args, options = {}) => new Promise((resolve, reject) => {
100
+ // Node ≥18.20 拒绝无 shell 直接 spawn .cmd(EINVAL)。
101
+ const child = spawn(command, args, { shell: process.platform === 'win32', stdio: ['ignore', 'pipe', 'pipe'], ...options })
102
+ let out = ''
103
+ child.stdout.on('data', c => { out += c })
104
+ child.stderr.on('data', c => { out += c })
105
+ child.once('exit', code => code === 0 ? resolve(out) : reject(new Error(`${command} exited ${code}\n${out.slice(-2000)}`)))
106
+ child.once('error', reject)
107
+ })
108
+
109
+ const PROFILE_PATCH_BASE = `# cell-browser-e2e provisioned profile patch
110
+ `
111
+
112
+ async function provisionCell({ rc, pins, patchHmr }) {
113
+ const sandbox = path.join(CELL_ROOT, rc)
114
+ const web = path.join(sandbox, 'home/profiles/web')
115
+ const fresh = !fs.existsSync(path.join(sandbox, 'node_modules/@deepseek-ai/dsh/package.json'))
116
+ if (fresh) {
117
+ fs.rmSync(sandbox, { recursive: true, force: true })
118
+ fs.mkdirSync(web, { recursive: true })
119
+ const sandboxPkg = {
120
+ name: 'cell-browser-e2e-host',
121
+ private: true,
122
+ dependencies: { '@deepseek-ai/dsh': rc, ...pins },
123
+ }
124
+ await fs.promises.writeFile(path.join(sandbox, 'package.json'), JSON.stringify(sandboxPkg, null, 2) + '\n')
125
+ // 自带 workspace+npmrc:切断对仓库 workspace 的目录继承(否则 pnpm 把安装
126
+ // 静默吞进仓库根),并钉死 registry(命令行 --registry 经 shell 传递不可靠)。
127
+ await fs.promises.writeFile(path.join(sandbox, 'pnpm-workspace.yaml'), SANDBOX_WORKSPACE_YAML)
128
+ await fs.promises.writeFile(path.join(sandbox, '.npmrc'), NPMRC)
129
+ await run('pnpm.cmd', ['install', '--no-frozen-lockfile'], { cwd: sandbox })
130
+ await fs.promises.writeFile(path.join(web, 'pnpm-workspace.yaml'), WEB_WORKSPACE_YAML)
131
+ await fs.promises.writeFile(path.join(web, '.npmrc'), NPMRC)
132
+ const profilePkg = {
133
+ name: 'dsh-profile-web',
134
+ private: true,
135
+ dependencies: { 'dsh-context-compression-improved': PLUGIN_SPEC },
136
+ dsh: { profile: { bundles: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', 'dsh-context-compression-improved'] } },
137
+ }
138
+ await fs.promises.writeFile(path.join(web, 'package.json'), JSON.stringify(profilePkg, null, 2) + '\n')
139
+ const patch = patchHmr
140
+ ? `${PROFILE_PATCH_BASE}- insert:\n - name: '@deepseek-ai/cordis-plugin-hmr'\n config:\n root: []\n`
141
+ : `${PROFILE_PATCH_BASE}[]\n`
142
+ await fs.promises.writeFile(path.join(web, 'cordis.patch.yml'), patch)
143
+ await run('pnpm.cmd', ['install', '--no-frozen-lockfile'], { cwd: web })
144
+ } else {
145
+ // 复用格子:只把插件刷到目标 spec(幂等)。
146
+ const web = path.join(sandbox, 'home/profiles/web')
147
+ const pkgPath = path.join(web, 'package.json')
148
+ const pkg = JSON.parse(await fs.promises.readFile(pkgPath, 'utf8'))
149
+ if (pkg.dependencies['dsh-context-compression-improved'] !== PLUGIN_SPEC) {
150
+ pkg.dependencies['dsh-context-compression-improved'] = PLUGIN_SPEC
151
+ await fs.promises.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
152
+ await run('pnpm.cmd', ['install', '--no-frozen-lockfile'], { cwd: web })
153
+ }
154
+ }
155
+ const installed = JSON.parse(await fs.promises.readFile(path.join(web, 'node_modules/dsh-context-compression-improved/package.json'), 'utf8')).version
156
+ return { sandbox, installed }
157
+ }
158
+
159
+ async function bootHost(sandbox) {
160
+ const host = spawn(process.execPath, ['node_modules/@deepseek-ai/dsh/lib/bin.js', '--profile', 'web', '--port', '0', '--no-open'], {
161
+ cwd: sandbox,
162
+ env: { ...process.env, DSH_HOME: path.join(sandbox, 'home') },
163
+ stdio: ['ignore', 'pipe', 'pipe'],
164
+ })
165
+ let bootOut = ''
166
+ host.stdout.on('data', c => { bootOut += c })
167
+ host.stderr.on('data', c => { bootOut += c })
168
+ const t0 = Date.now()
169
+ while (Date.now() - t0 < 60000) {
170
+ const m = bootOut.match(/dsh web: (http:\/\/\S+)/u)
171
+ if (m) return { host, url: m[1] }
172
+ if (host.exitCode !== null) throw new Error(`host exited ${host.exitCode} before web url:\n${bootOut.slice(-1200)}`)
173
+ await sleep(1000)
174
+ }
175
+ host.kill('SIGKILL')
176
+ throw new Error(`no web url within 60s:\n${bootOut.slice(-1200)}`)
177
+ }
178
+
179
+ async function probeWithChrome(bootUrl, generation, shotPath, chromePath) {
180
+ const cdpPort = 9400 + Math.floor(Math.random() * 400)
181
+ const chrome = spawn(chromePath, [
182
+ '--headless=new', `--remote-debugging-port=${cdpPort}`, '--no-first-run', '--no-default-browser-check',
183
+ `--user-data-dir=${path.join(CELL_ROOT, 'chrome-profile-' + Date.now())}`, '--window-size=1280,900', 'about:blank',
184
+ ], { stdio: 'ignore' })
185
+ try {
186
+ await sleep(2500)
187
+ const targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json()
188
+ const page = targets.find(t => t.type === 'page')
189
+ const ws = new WebSocket(page.webSocketDebuggerUrl)
190
+ let id = 0
191
+ const pending = new Map()
192
+ ws.onmessage = (ev) => {
193
+ const msg = JSON.parse(ev.data)
194
+ if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id) }
195
+ }
196
+ await new Promise(r => { ws.onopen = r })
197
+ const send = (method, params = {}) => new Promise(resolve => {
198
+ const mid = ++id
199
+ pending.set(mid, resolve)
200
+ ws.send(JSON.stringify({ id: mid, method, params }))
201
+ })
202
+ const evalJS = async (expression, awaitPromise = false) => {
203
+ const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise })
204
+ return r.result?.result?.value ?? r.result?.result?.description ?? 'undefined'
205
+ }
206
+ const realClick = async findExpr => {
207
+ const pos = await evalJS(`(() => {
208
+ const el = (${findExpr});
209
+ if (!el) return null;
210
+ const r = el.getBoundingClientRect();
211
+ return JSON.stringify({ x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
212
+ })()`)
213
+ if (!pos || pos === 'null' || pos === 'undefined') return null
214
+ const { x, y } = JSON.parse(pos)
215
+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, pointerType: 'mouse' })
216
+ for (const type of ['mousePressed', 'mouseReleased']) {
217
+ await send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, pointerType: 'mouse' })
218
+ }
219
+ return `${x},${y}`
220
+ }
221
+ const waitClick = async (tag, findExpr, timeoutMs = 25000) => {
222
+ const t0 = Date.now()
223
+ while (Date.now() - t0 < timeoutMs) {
224
+ if (await realClick(findExpr)) return true
225
+ await sleep(700)
226
+ }
227
+ const labels = await evalJS(`JSON.stringify([...document.querySelectorAll("button,a[role=button]")].map(b => b.textContent?.trim()).filter(Boolean).slice(0, 14))`)
228
+ throw new Error(`click TIMEOUT ${tag}; buttons: ${labels}`)
229
+ }
230
+ const readSettings = async () => JSON.parse(await evalJS(`(async () => {
231
+ const r = await fetch("/api/dsh-context-compression-improved/settings", { headers: { accept: "application/json" } });
232
+ const j = await r.json();
233
+ return JSON.stringify({ profile: j.doc && j.doc.profile, generation: j.generation });
234
+ })()`, true))
235
+
236
+ // 首屏两层门(顺序因线而异,且可能复弹):API Key 弹窗「稍后配置」+
237
+ // 0.1.x「内测声明→继续」。轮询直到两层都不在(有轮次上限)。
238
+ const dismissOverlays = async () => {
239
+ for (let round = 0; round < 4; round += 1) {
240
+ const apiModal = await realClick(`(() => {
241
+ const b = [...document.querySelectorAll("button")].find(b => b.textContent?.trim() === "稍后配置");
242
+ return b ?? null;
243
+ })()`)
244
+ await sleep(800)
245
+ const banner = await realClick(`(() => {
246
+ const b = [...document.querySelectorAll("button")].find(b => b.textContent?.trim() === "继续");
247
+ return b ?? null;
248
+ })()`)
249
+ if (!apiModal && !banner) return true
250
+ await sleep(1200)
251
+ }
252
+ return false
253
+ }
254
+ await send('Page.enable')
255
+ await send('Page.navigate', { url: bootUrl })
256
+ await sleep(11000)
257
+ await dismissOverlays()
258
+ await sleep(1000)
259
+
260
+ if (generation === 'modern') {
261
+ // 插件面板 → 包详情 → plugins.bundle.config 卡片
262
+ await dismissOverlays()
263
+ await waitClick('plugins-panel', `(() => {
264
+ const b = [...document.querySelectorAll("nav button, button")].filter(b => b.textContent?.trim() === "插件").pop();
265
+ return b ?? null;
266
+ })()`)
267
+ await sleep(2500)
268
+ await waitClick('pkg-title', `(() => {
269
+ const el = [...document.querySelectorAll("*")].filter(e => /^dsh-context-compression-improved/.test(e.textContent?.trim() ?? "") && e.children.length === 0).pop();
270
+ if (!el) return null;
271
+ el.scrollIntoView({ block: "center" });
272
+ return el.closest("button") ?? el;
273
+ })()`)
274
+ await sleep(3000)
275
+ } else {
276
+ // 设置弹窗 → 左栏「上下文压缩选择器」分类 → settings.section 节
277
+ await waitClick('settings-panel', `(() => {
278
+ const b = [...document.querySelectorAll("button")].filter(b => b.textContent?.trim() === "设置").pop();
279
+ return b ?? null;
280
+ })()`)
281
+ await sleep(2000)
282
+ await dismissOverlays()
283
+ await waitClick('cci-category', `(() => {
284
+ const b = [...document.querySelectorAll("button")].filter(b => (b.textContent ?? "").includes("上下文压缩")).pop();
285
+ return b ?? null;
286
+ })()`)
287
+ await sleep(2500)
288
+ }
289
+
290
+ const face = await evalJS(`(() => ({
291
+ slotErr: document.querySelectorAll("[data-slot-error]").length,
292
+ sectionText: document.body.innerText.includes("平衡模式") || document.body.innerText.includes("压缩 Profile"),
293
+ hasBalancedBtn: [...document.querySelectorAll("button")].some(b => b.textContent?.includes("平衡模式")),
294
+ hasSavingsBtn: [...document.querySelectorAll("button")].some(b => b.textContent?.includes("节省模式")),
295
+ entryErrors: window.__cciEntryError ?? null,
296
+ }))()`)
297
+
298
+ // 写穿断言:before/after 必须翻转,不依赖任何残留状态。
299
+ const before = await readSettings()
300
+ const target = before.profile === 'savings' ? '平衡模式' : '节省模式'
301
+ const expected = target === '节省模式' ? 'savings' : 'balanced'
302
+ const clicked = await evalJS(`(() => {
303
+ const card = [...document.querySelectorAll("button")].find(b => b.textContent?.includes(${JSON.stringify(target)}));
304
+ if (card) { card.click(); return 'clicked'; }
305
+ return 'no-btn';
306
+ })()`)
307
+ if (clicked !== 'clicked') throw new Error(`profile button "${target}" not rendered`)
308
+ await sleep(3500)
309
+ const after = await readSettings()
310
+ const shot = await send('Page.captureScreenshot', { format: 'png' })
311
+ if (shot.result?.data) await fs.promises.writeFile(shotPath, Buffer.from(shot.result.data, 'base64'))
312
+ ws.close()
313
+ return { face, before, after, expected }
314
+ } finally {
315
+ chrome.kill()
316
+ }
317
+ }
318
+
319
+ const chromePath = findChrome()
320
+ if (!chromePath) {
321
+ console.error('no Chrome/Chromium found; set CHROME_PATH')
322
+ process.exit(2)
323
+ }
324
+
325
+ const results = []
326
+ let failed = 0
327
+ for (const host of HOSTS_TO_RUN) {
328
+ const line = `${host.rc} (${host.generation})`
329
+ let host_ = null
330
+ try {
331
+ const { sandbox, installed } = await provisionCell(host)
332
+ console.log(`CELL ${line}: plugin ${installed}`)
333
+ const booted = await bootHost(sandbox)
334
+ host_ = booted.host
335
+ console.log(`CELL ${line}: boot ${booted.url}`)
336
+ await sleep(4000)
337
+ const shotPath = path.join(CELL_ROOT, `${host.rc}.png`)
338
+ const { face, before, after, expected } = await probeWithChrome(booted.url, host.generation, shotPath, chromePath)
339
+ const pass = face.slotErr === 0 && face.sectionText === true && face.hasSavingsBtn === true
340
+ && after.profile === expected && before.profile !== after.profile
341
+ console.log(`CELL ${line}: ${pass ? 'PASS' : 'FAIL'} ${JSON.stringify({ face, before, after })}`)
342
+ results.push({ rc: host.rc, pass, installed })
343
+ if (!pass) failed += 1
344
+ } catch (error) {
345
+ console.log(`CELL ${line}: FAIL ${String(error.message).slice(-1500)}`)
346
+ results.push({ rc: host.rc, pass: false })
347
+ failed += 1
348
+ } finally {
349
+ host_?.kill('SIGKILL')
350
+ await sleep(1500)
351
+ }
352
+ }
353
+ console.log('SUMMARY ' + JSON.stringify(results))
354
+ process.exit(failed === 0 ? 0 : 1)