dsh-context-compression-improved 0.9.7 → 0.9.9-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +15 -98
  3. package/README.zh.md +14 -92
  4. package/THIRD_PARTY_NOTICES.md +32 -14
  5. package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +27 -27
  6. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  7. package/{packages/selector/lib → lib}/client.d.ts +16 -0
  8. package/{packages/selector/lib → lib}/client.js +393 -116
  9. package/{packages/selector/lib → lib}/index.js +829 -10
  10. package/{packages/selector/lib → lib}/invariant.js +2 -1
  11. package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
  12. package/{packages/selector/lib → lib}/pruner.js +77 -983
  13. package/lib/savings-integral.js +4515 -0
  14. package/{packages/selector/lib → lib}/tail-trim.js +2 -90
  15. package/lib/tool-result.js +150 -0
  16. package/package.json +129 -116
  17. package/screenshots.json +3 -6
  18. package/.gitattributes +0 -2
  19. package/.githooks/pre-push +0 -37
  20. package/.github/workflows/ci.yml +0 -39
  21. package/CHANGELOG.de.md +0 -580
  22. package/CHANGELOG.es.md +0 -588
  23. package/CHANGELOG.fr.md +0 -576
  24. package/CHANGELOG.it.md +0 -577
  25. package/CHANGELOG.ja.md +0 -261
  26. package/CHANGELOG.ko.md +0 -254
  27. package/CHANGELOG.md +0 -532
  28. package/CHANGELOG.ru.md +0 -554
  29. package/CHANGELOG.zh.md +0 -236
  30. package/CONTRIBUTING.md +0 -22
  31. package/README.de.md +0 -96
  32. package/README.es.md +0 -96
  33. package/README.fr.md +0 -96
  34. package/README.it.md +0 -96
  35. package/README.ja.md +0 -102
  36. package/README.ko.md +0 -102
  37. package/README.ru.md +0 -96
  38. package/SECURITY.md +0 -18
  39. package/assets/board.png +0 -0
  40. package/assets/context.png +0 -0
  41. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  42. package/docs/assets/context-compression-selector-settings.png +0 -0
  43. package/docs/compat-0.1.5-report.md +0 -77
  44. package/docs/installation.de.md +0 -104
  45. package/docs/installation.es.md +0 -104
  46. package/docs/installation.fr.md +0 -104
  47. package/docs/installation.it.md +0 -104
  48. package/docs/installation.ja.md +0 -78
  49. package/docs/installation.ko.md +0 -78
  50. package/docs/installation.md +0 -103
  51. package/docs/installation.ru.md +0 -104
  52. package/docs/installation.zh.md +0 -100
  53. package/docs/repair-log.md +0 -657
  54. package/eslint.config.js +0 -30
  55. package/packages/selector/LICENSE +0 -21
  56. package/packages/selector/README.md +0 -26
  57. package/packages/selector/README.zh.md +0 -24
  58. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  59. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  60. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  61. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  62. package/packages/selector/lib/config.js +0 -1777
  63. package/packages/selector/lib/host-generation.js +0 -62
  64. package/packages/selector/lib/style.css +0 -350
  65. package/packages/selector/package.json +0 -174
  66. package/packages/selector/screenshots.json +0 -3
  67. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  68. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  69. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  70. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  71. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  72. package/packages/selector/src/client/bridge-scope.ts +0 -125
  73. package/packages/selector/src/client/decode.ts +0 -57
  74. package/packages/selector/src/client/index.ts +0 -421
  75. package/packages/selector/src/client/locales/de.ts +0 -142
  76. package/packages/selector/src/client/locales/es.ts +0 -142
  77. package/packages/selector/src/client/locales/fr.ts +0 -142
  78. package/packages/selector/src/client/locales/it.ts +0 -142
  79. package/packages/selector/src/client/locales/ja.ts +0 -142
  80. package/packages/selector/src/client/locales/ko.ts +0 -142
  81. package/packages/selector/src/client/locales/ru.ts +0 -142
  82. package/packages/selector/src/client/locales.ts +0 -284
  83. package/packages/selector/src/client/monitor-fab.ts +0 -349
  84. package/packages/selector/src/client/preset-options.ts +0 -88
  85. package/packages/selector/src/client/savings-card.tsx +0 -150
  86. package/packages/selector/src/client/scope-face.ts +0 -24
  87. package/packages/selector/src/client/settings-section.tsx +0 -140
  88. package/packages/selector/src/compat/host-generation.ts +0 -96
  89. package/packages/selector/src/compat/llm-messages.ts +0 -50
  90. package/packages/selector/src/compat/settings-lease.ts +0 -108
  91. package/packages/selector/src/compat/tool-result.ts +0 -91
  92. package/packages/selector/src/css-modules.d.ts +0 -6
  93. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  94. package/packages/selector/src/estimator-catalog.ts +0 -104
  95. package/packages/selector/src/index.ts +0 -655
  96. package/packages/selector/src/invariant.ts +0 -113
  97. package/packages/selector/src/preset-overlay.ts +0 -749
  98. package/packages/selector/src/profiles.ts +0 -431
  99. package/packages/selector/src/pruner/content.ts +0 -198
  100. package/packages/selector/src/pruner/session.ts +0 -97
  101. package/packages/selector/src/pruner/state.ts +0 -61
  102. package/packages/selector/src/pruner/tuning.ts +0 -23
  103. package/packages/selector/src/pruner/types.ts +0 -78
  104. package/packages/selector/src/pruner.ts +0 -2868
  105. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  106. package/packages/selector/src/runtime/audit.ts +0 -303
  107. package/packages/selector/src/runtime/config.ts +0 -756
  108. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  109. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  110. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  111. package/packages/selector/src/runtime/measurement.ts +0 -444
  112. package/packages/selector/src/runtime/monitor.ts +0 -235
  113. package/packages/selector/src/runtime/reducers.ts +0 -1754
  114. package/packages/selector/src/runtime/retrieve.ts +0 -484
  115. package/packages/selector/src/runtime/savings-projection.ts +0 -226
  116. package/packages/selector/src/runtime/savings.ts +0 -417
  117. package/packages/selector/src/runtime/session-events.ts +0 -30
  118. package/packages/selector/src/runtime/summary-command.ts +0 -127
  119. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  120. package/packages/selector/src/runtime/token-count.ts +0 -72
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  134. package/packages/selector/src/runtime/toolclass.ts +0 -103
  135. package/packages/selector/src/runtime/types.ts +0 -365
  136. package/packages/selector/src/runtime/value.ts +0 -48
  137. package/packages/selector/src/settings-bridge.ts +0 -175
  138. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  139. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  140. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  141. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  142. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  143. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  144. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  145. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  146. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  147. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
  148. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  149. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  150. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  154. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  155. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
  156. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  157. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  158. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  159. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  160. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  161. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  162. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  163. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  164. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  165. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  166. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  167. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  168. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  169. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  170. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  171. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  172. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  173. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  174. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  175. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  176. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  177. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  178. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  179. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  180. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  181. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  182. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  183. package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
  184. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  185. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
  186. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  187. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  188. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  189. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  190. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  191. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  192. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  193. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  194. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  195. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  196. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  197. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  198. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  199. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  200. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  201. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  202. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  203. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  204. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  205. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  206. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  207. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  208. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  209. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  210. package/packages/selector/tsconfig.json +0 -11
  211. package/packages/selector/tsdown.client.config.ts +0 -102
  212. package/packages/selector/tsdown.config.ts +0 -20
  213. package/pnpm-workspace.yaml +0 -72
  214. package/scripts/capture-profile-baseline.mjs +0 -42
  215. package/scripts/cell-browser-e2e.mjs +0 -354
  216. package/scripts/generate-tokenizer-fixtures.py +0 -81
  217. package/scripts/generate-vision-fixtures.py +0 -208
  218. package/scripts/hosts.mjs +0 -77
  219. package/scripts/packed-components-smoke.mjs +0 -763
  220. package/scripts/packed-install-e2e.mjs +0 -1346
  221. package/scripts/sync-hosts.mjs +0 -174
  222. package/scripts/toolclass-corpus-replay.mjs +0 -281
  223. package/scripts/verify-release.mjs +0 -335
  224. package/tests/TEST_INVENTORY.md +0 -41
  225. package/tsconfig.base.json +0 -18
  226. package/tsconfig.json +0 -7
  227. package/tsconfig.tests.json +0 -15
  228. package/vitest.built.config.ts +0 -9
  229. package/vitest.config.ts +0 -46
  230. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  231. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  232. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  233. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  234. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  235. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  236. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  237. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  238. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  239. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  240. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
@@ -1,78 +0,0 @@
1
- /* Vendored verbatim from @deepseek-ai/<pkg> — third-party code, exempt from this repo's lint rules. */
2
- /**
3
- * Structural secret redaction for settings values. `role('secret')` fields are
4
- * removed from a value before it crosses a wire boundary; a sidecar records
5
- * each schema-declared secret position and whether it currently holds a value,
6
- * so a configuration surface can render a write-only input without ever
7
- * receiving the secret itself.
8
- * @module @deepseek-ai/dsh-settings/redact
9
- */
10
- /** Whether a value is a plain data object the walker may recurse into. */
11
- function isRecord(value) {
12
- return typeof value === 'object' && value !== null && !Array.isArray(value);
13
- }
14
- function walk(node, value, path, secrets) {
15
- if (node === undefined)
16
- return value;
17
- if (node.meta?.role === 'secret') {
18
- secrets.push({ path, set: value !== undefined });
19
- return undefined;
20
- }
21
- switch (node.type) {
22
- case 'object': {
23
- const properties = node.dict ?? {};
24
- const source = isRecord(value) ? value : undefined;
25
- const rebuilt = {};
26
- if (source !== undefined) {
27
- for (const [key, entry] of Object.entries(source)) {
28
- if (key in properties)
29
- continue;
30
- rebuilt[key] = entry;
31
- }
32
- }
33
- for (const [key, child] of Object.entries(properties)) {
34
- const stripped = walk(child, source?.[key], [...path, key], secrets);
35
- if (stripped !== undefined)
36
- rebuilt[key] = stripped;
37
- }
38
- return source === undefined && Object.keys(rebuilt).length === 0 ? value : rebuilt;
39
- }
40
- case 'dict': {
41
- if (!isRecord(value))
42
- return value;
43
- const rebuilt = {};
44
- for (const [key, entry] of Object.entries(value)) {
45
- const stripped = walk(node.inner, entry, [...path, key], secrets);
46
- if (stripped !== undefined)
47
- rebuilt[key] = stripped;
48
- }
49
- return rebuilt;
50
- }
51
- case 'array': {
52
- if (!Array.isArray(value))
53
- return value;
54
- return value.map((entry, index) => walk(node.inner, entry, [...path, String(index)], secrets));
55
- }
56
- default:
57
- // TODO(settings-wire-redaction): Fail closed instead — a secret reachable
58
- // only through a union, intersection, or transform is returned verbatim
59
- // here, with nothing recording that it was missed.
60
- return value;
61
- }
62
- }
63
- /**
64
- * Remove every `role('secret')` field a schema declares from a value. The
65
- * walker follows `object`, `dict`, and `array` containers; a secret must be
66
- * declared directly on a field reachable through those containers (a secret
67
- * buried inside a union branch or transform is not reachable and must not be
68
- * modeled that way). The input is never mutated.
69
- * @param schema - live schemastery schema describing the value.
70
- * @param value - the value to strip; `undefined` yields an empty record with
71
- * object-property secret slots still enumerated.
72
- * @returns the stripped detached value and the ordered secret positions.
73
- */
74
- export function redactSecrets(schema, value) {
75
- const secrets = [];
76
- const stripped = walk(schema, value, [], secrets);
77
- return { value: stripped, secrets };
78
- }
@@ -1,234 +0,0 @@
1
- /* Vendored verbatim from @deepseek-ai/<pkg> — third-party code, exempt from this repo's lint rules. */
2
- /* eslint-disable */
3
- //#region lib/types/index.js
4
- /** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */
5
- /**
6
- * Mark an unreachable closed-union branch.
7
- * @param value - impossible value; an unhandled typed variant fails at the call site.
8
- * @param context - optional switch-site label included in the failure message.
9
- * @returns never; a runtime value that escaped its type always throws.
10
- */
11
- function assertNever(value, context) {
12
- const rendered = JSON.stringify(value) ?? String(value);
13
- throw new Error(`unreachable variant${context ? ` in ${context}` : ""}: ${rendered}`);
14
- }
15
- /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
16
- function hasIntrinsicConstructor(prototype, name) {
17
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
18
- if (typeof constructor !== "function") return false;
19
- try {
20
- return constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === `function ${name}() { [native code] }`;
21
- } catch {
22
- return false;
23
- }
24
- }
25
- /** Whether a candidate is one realm's intrinsic `Object.prototype`. */
26
- function isIntrinsicObjectPrototype(value) {
27
- return Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, "Object");
28
- }
29
- /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
30
- function hasPlainArrayPrototype(value) {
31
- const prototype = Object.getPrototypeOf(value);
32
- if (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, "Array")) return false;
33
- const objectPrototype = Object.getPrototypeOf(prototype);
34
- return typeof objectPrototype === "object" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);
35
- }
36
- /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
37
- function hasPlainObjectPrototype(value) {
38
- const prototype = Object.getPrototypeOf(value);
39
- return prototype === null || typeof prototype === "object" && isIntrinsicObjectPrototype(prototype);
40
- }
41
- /** Return every JSON-visible object key, or reject own data JSON would discard. */
42
- function enumerableStringKeys(value) {
43
- const keys = Reflect.ownKeys(value);
44
- if (keys.some((key) => typeof key !== "string" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;
45
- return keys;
46
- }
47
- /** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */
48
- function walkJsonValue(value, detach) {
49
- const ancestors = /* @__PURE__ */ new Set();
50
- let root;
51
- const assign = (destination, item) => {
52
- if (destination === void 0) return;
53
- if (destination.kind === "root") root = item;
54
- else if (destination.kind === "array") destination.target[destination.index] = item;
55
- else Object.defineProperty(destination.target, destination.key, {
56
- value: item,
57
- enumerable: true,
58
- configurable: true,
59
- writable: true
60
- });
61
- };
62
- const tasks = [{
63
- kind: "visit",
64
- value,
65
- ...detach ? { destination: { kind: "root" } } : {}
66
- }];
67
- for (let task = tasks.pop(); task !== void 0; task = tasks.pop()) {
68
- if (task.kind === "leave") {
69
- ancestors.delete(task.source);
70
- continue;
71
- }
72
- if (task.kind === "array-item") {
73
- if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return void 0;
74
- tasks.push({
75
- kind: "visit",
76
- value: task.source[task.index],
77
- ...task.target === void 0 ? {} : { destination: {
78
- kind: "array",
79
- target: task.target,
80
- index: task.index
81
- } }
82
- });
83
- continue;
84
- }
85
- if (task.kind === "object-property") {
86
- tasks.push({
87
- kind: "visit",
88
- value: task.source[task.key],
89
- ...task.target === void 0 ? {} : { destination: {
90
- kind: "object",
91
- target: task.target,
92
- key: task.key
93
- } }
94
- });
95
- continue;
96
- }
97
- const current = task.value;
98
- if (current === null) {
99
- assign(task.destination, null);
100
- continue;
101
- }
102
- if (typeof current === "boolean" || typeof current === "string") {
103
- assign(task.destination, current);
104
- continue;
105
- }
106
- if (typeof current === "number") {
107
- if (!Number.isFinite(current) || Object.is(current, -0)) return void 0;
108
- assign(task.destination, current);
109
- continue;
110
- }
111
- if (typeof current !== "object") return void 0;
112
- if (ancestors.has(current)) return void 0;
113
- if (Array.isArray(current)) {
114
- if (!hasPlainArrayPrototype(current)) return void 0;
115
- const length = current.length;
116
- if (Reflect.ownKeys(current).length !== length + 1) return void 0;
117
- const target = detach ? [] : void 0;
118
- if (target !== void 0) assign(task.destination, target);
119
- ancestors.add(current);
120
- tasks.push({
121
- kind: "leave",
122
- source: current
123
- });
124
- for (let index = length - 1; index >= 0; index--) tasks.push({
125
- kind: "array-item",
126
- source: current,
127
- index,
128
- ...target === void 0 ? {} : { target }
129
- });
130
- continue;
131
- }
132
- if (!hasPlainObjectPrototype(current)) return void 0;
133
- const keys = enumerableStringKeys(current);
134
- if (keys === void 0) return void 0;
135
- const target = detach ? {} : void 0;
136
- if (target !== void 0) assign(task.destination, target);
137
- ancestors.add(current);
138
- tasks.push({
139
- kind: "leave",
140
- source: current
141
- });
142
- for (let index = keys.length - 1; index >= 0; index--) {
143
- const key = keys[index];
144
- /* v8 ignore next -- the loop is bounded by the captured key count. */
145
- if (key === void 0) return void 0;
146
- tasks.push({
147
- kind: "object-property",
148
- source: current,
149
- key,
150
- ...target === void 0 ? {} : { target }
151
- });
152
- }
153
- }
154
- return detach ? root : true;
155
- }
156
- /**
157
- * Validate and detach lossless JSON in one read per property.
158
- * @param value - candidate value to validate and detach.
159
- * @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.
160
- */
161
- function snapshotJsonValue(value) {
162
- return walkJsonValue(value, true);
163
- }
164
- /**
165
- * Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.
166
- * @param value - candidate value to test.
167
- * @returns whether the value survives a JSON round trip without loss.
168
- */
169
- function isJsonValue(value) {
170
- return walkJsonValue(value, false) === true;
171
- }
172
- /**
173
- * Compare JSON-compatible values structurally.
174
- * @param a - one JSON-compatible value.
175
- * @param b - the other JSON-compatible value.
176
- * @returns whether both values contain the same JSON data.
177
- */
178
- function deepEqualJson(a, b) {
179
- if (a === b) return true;
180
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
181
- if (Array.isArray(a) || Array.isArray(b)) {
182
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
183
- return a.every((entry, index) => deepEqualJson(entry, b[index]));
184
- }
185
- const left = a;
186
- const right = b;
187
- const keys = Object.keys(left);
188
- if (keys.length !== Object.keys(right).length) return false;
189
- return keys.every((key) => key in right && deepEqualJson(left[key], right[key]));
190
- }
191
- /**
192
- * Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.
193
- * @param value - value to freeze.
194
- * @returns the same value after every reachable enumerable child is frozen.
195
- */
196
- function deepFreeze(value) {
197
- const seen = /* @__PURE__ */ new WeakSet();
198
- const pending = [{
199
- kind: "visit",
200
- node: value
201
- }];
202
- while (pending.length > 0) {
203
- const task = pending.pop();
204
- /* v8 ignore next -- the loop condition guarantees one pending task. */
205
- if (task === void 0) continue;
206
- if (task.kind === "property") {
207
- pending.push({
208
- kind: "visit",
209
- node: task.source[task.key]
210
- });
211
- continue;
212
- }
213
- const node = task.node;
214
- if (node === null || typeof node !== "object") continue;
215
- if (node instanceof AbortSignal) continue;
216
- if (seen.has(node)) continue;
217
- seen.add(node);
218
- Object.freeze(node);
219
- const keys = Object.keys(node);
220
- for (let index = keys.length - 1; index >= 0; index--) {
221
- const key = keys[index];
222
- /* v8 ignore next -- the loop is bounded by the captured key count. */
223
- if (key === void 0) continue;
224
- pending.push({
225
- kind: "property",
226
- source: node,
227
- key
228
- });
229
- }
230
- }
231
- return value;
232
- }
233
- //#endregion
234
- export { assertNever, deepEqualJson, deepFreeze, isJsonValue, snapshotJsonValue };
@@ -1,204 +0,0 @@
1
- import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
- import { tmpdir } from 'node:os'
3
- import { dirname, join } from 'node:path'
4
- import { Context, Service } from '@deepseek-ai/cordis'
5
- import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
6
- import { type SettingsNamespace } from '@deepseek-ai/dsh-settings'
7
- import { LegacySettingsProvider } from './helpers/legacy-settings/index.ts'
8
- import { afterEach, describe, expect, it } from 'vitest'
9
- import { apply } from '../src/index.ts'
10
- import type { OverlayableAgentPresets } from '../src/preset-overlay.ts'
11
- import { LegacyNamespaceRegistrar } from './helpers/legacy-namespace.ts'
12
-
13
- // 0.1.5 removed the settingsNamespace() wrapper; namespaces are validated at runtime.
14
- const nsBrand = (value: string): SettingsNamespace => value as unknown as SettingsNamespace
15
-
16
- let root: string | undefined
17
- let ctx: Context | undefined
18
-
19
- afterEach(async () => {
20
- await ctx?.fiber.dispose()
21
- ctx = undefined
22
- if (root !== undefined) await rm(root, { recursive: true, force: true })
23
- root = undefined
24
- })
25
-
26
- class MemorySettings extends LegacySettingsProvider {
27
- readonly writable = true
28
- private readonly stored: Record<string, unknown> = {}
29
-
30
- protected load(): Promise<Record<string, unknown>> {
31
- return Promise.resolve(structuredClone(this.stored))
32
- }
33
-
34
- protected persist(ns: SettingsNamespace, section: Record<string, unknown>): Promise<void> {
35
- this.stored[ns] = structuredClone(section)
36
- return Promise.resolve()
37
- }
38
- }
39
-
40
- class FakeAgentPresets extends Service implements OverlayableAgentPresets {
41
- constructor(ctx: Context, readonly preset: AgentPreset) {
42
- super(ctx, 'agentPresets')
43
- }
44
-
45
- async resolve(): Promise<AgentPreset> {
46
- return this.preset
47
- }
48
-
49
- async mount(_agentCtx: unknown): Promise<AgentPreset> {
50
- return await this.resolve()
51
- }
52
-
53
- async recompose(_agentCtx: unknown, _id: string): Promise<AgentPreset> {
54
- return await this.resolve()
55
- }
56
-
57
- async standingKeyFor(): Promise<string> {
58
- return (await this.resolve()).path
59
- }
60
- }
61
-
62
- async function sourcePreset(): Promise<AgentPreset> {
63
- root = await mkdtemp(join(tmpdir(), 'dsh-selector-host-overlay-'))
64
- const path = join(root, 'standard', 'agent.cordis.yml')
65
- await mkdir(dirname(path), { recursive: true })
66
- await writeFile(path, "- id: persona\n name: '/opt/preset/persona.js'\n")
67
- return { id: 'standard', trust: 'system', path }
68
- }
69
-
70
- describe('context compression selector Host preset integration', () => {
71
- it('decorates native composition only for the lifetime of the selector fiber', async () => {
72
- const preset = await sourcePreset()
73
- ctx = new Context()
74
- await ctx.plugin(MemorySettings).await()
75
- await ctx.plugin(LegacyNamespaceRegistrar).await()
76
- await ctx.plugin(FakeAgentPresets, preset).await()
77
-
78
- const selector = ctx.plugin({ apply: (child) => {
79
- apply(child, { presetOverlay: true })
80
- } })
81
- await selector.await()
82
-
83
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
84
- const mounted = await service.mount({})
85
- expect(mounted.path).not.toBe(preset.path)
86
- expect(await readFile(mounted.path, 'utf8')).toContain('id: tool-result-pruner')
87
- expect((await service.resolve()).path).toBe(preset.path)
88
-
89
- await selector.dispose()
90
- expect((await service.mount({})).path).toBe(preset.path)
91
- })
92
-
93
- it('0.1.7: duplicate Host rows own independent entry configs — one row\u2019s disposal never disturbs the other', async () => {
94
- const preset = await sourcePreset()
95
- ctx = new Context()
96
- await ctx.plugin(MemorySettings).await()
97
- await ctx.plugin(FakeAgentPresets, preset).await()
98
-
99
- const builtIn = ctx.plugin({ apply })
100
- await builtIn.await()
101
-
102
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
103
- expect((await service.mount({})).path).toBe(preset.path)
104
-
105
- // 0.1.7: there is no shared settings registration to lease — each row
106
- // carries its own compression doc on its entry config, so duplicate rows
107
- // cannot disturb each other and disposal is purely per row.
108
- const bundle = ctx.plugin({ apply: (child) => {
109
- apply(child, { presetOverlay: true, settings: { profile: 'cache-strict' } } as never)
110
- } })
111
- await bundle.await()
112
-
113
- const mounted = await service.mount({})
114
- expect(mounted.path).not.toBe(preset.path)
115
- expect((await service.recompose({}, 'standard')).path).toBe(mounted.path)
116
-
117
- // Disposing the non-overlay row never touches the overlay row's decoration
118
- // or its entry config.
119
- await builtIn.dispose()
120
- expect((await service.mount({})).path).toBe(mounted.path)
121
-
122
- await bundle.dispose()
123
- expect((await service.mount({})).path).toBe(preset.path)
124
- })
125
-
126
- it('writes the saved Auto Compact threshold into the generated compaction-basic composition', async () => {
127
- const preset = await sourcePreset()
128
- ctx = new Context()
129
- await ctx.plugin(MemorySettings).await()
130
- await ctx.plugin(LegacyNamespaceRegistrar).await()
131
- await ctx.plugin(FakeAgentPresets, preset).await()
132
- // A settings-owning row must register the namespace before the update.
133
- await ctx.plugin({ apply }).await()
134
- const namespace = nsBrand('context-compression')
135
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 73 } })
136
-
137
- const bundle = ctx.plugin({ apply: (child) => {
138
- apply(child, { presetOverlay: true })
139
- } })
140
- await bundle.await()
141
-
142
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
143
- const mounted = await service.mount({})
144
- const rendered = await readFile(mounted.path, 'utf8')
145
- expect(rendered).toContain('id: compaction-basic')
146
- expect(rendered).toContain('thresholdRatio: 0.73')
147
- // First-release retention stays pinned at 0.16 next to the threshold.
148
- expect(rendered).toContain('retainRatio: 0.16')
149
- // The SAME read feeds the runtime deployment config, so one generation
150
- // cannot split Auto Compact and micro compact across two thresholds.
151
- expect(rendered).toContain('id: tool-result-pruner')
152
- expect(rendered).toContain('autoCompactThresholdPercent: 73')
153
- await bundle.dispose()
154
- })
155
-
156
- it('defaults the generated threshold to 0.8 and keeps it absent from settings until saved', async () => {
157
- const preset = await sourcePreset()
158
- ctx = new Context()
159
- await ctx.plugin(MemorySettings).await()
160
- await ctx.plugin(LegacyNamespaceRegistrar).await()
161
- await ctx.plugin(FakeAgentPresets, preset).await()
162
-
163
- const bundle = ctx.plugin({ apply: (child) => {
164
- apply(child, { presetOverlay: true })
165
- } })
166
- await bundle.await()
167
-
168
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
169
- const rendered = await readFile((await service.mount({})).path, 'utf8')
170
- expect(rendered).toContain('thresholdRatio: 0.8')
171
- await bundle.dispose()
172
- })
173
-
174
- it('moves the standing composition generation when an equal-length threshold changes', async () => {
175
- const preset = await sourcePreset()
176
- ctx = new Context()
177
- await ctx.plugin(MemorySettings).await()
178
- await ctx.plugin(LegacyNamespaceRegistrar).await()
179
- await ctx.plugin(FakeAgentPresets, preset).await()
180
- // A settings-owning row must register the namespace before the update.
181
- await ctx.plugin({ apply }).await()
182
- const namespace = nsBrand('context-compression')
183
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 70 } })
184
-
185
- const bundle = ctx.plugin({ apply: (child) => {
186
- apply(child, { presetOverlay: true })
187
- } })
188
- await bundle.await()
189
-
190
- const service = ctx.agentPresets as unknown as OverlayableAgentPresets
191
- const first = await service.mount({})
192
- expect(await readFile(first.path, 'utf8')).toContain('thresholdRatio: 0.7')
193
- expect(await service.standingKeyFor()).toBe(first.path)
194
-
195
- // Same character length, different content: the generated identity and
196
- // standing composition generation must both move to the new threshold.
197
- await ctx.settings.update(namespace, { autoCompact: { thresholdPercent: 80 } })
198
- const second = await service.mount({})
199
- expect(second.path).not.toBe(first.path)
200
- expect(await readFile(second.path, 'utf8')).toContain('thresholdRatio: 0.8')
201
- expect(await service.standingKeyFor()).toBe(second.path)
202
- await bundle.dispose()
203
- })
204
- })
@@ -1,138 +0,0 @@
1
- /**
2
- * 压缩监控浮动球(FAB)客户端单测——骨架来自 pm `d29bcb1^` 撤下的
3
- * longtask-fab(计划 cci-monitor-fab task_3.1-3.4),数据层为注入依赖,
4
- * 本文件自断言消费侧行为。真实时钟 + initialDelayMs=1,不用假时钟
5
- * (jsdom × fake-timers 的 async advance 有已知坑)。
6
- */
7
- import { afterEach, describe, expect, it, vi } from 'vitest'
8
- import { initMonitorFab, type MonitorFabDeps, type MonitorSnapshotPayload } from '../src/client/monitor-fab.ts'
9
-
10
- const FAB_ID = 'dsh-cci-monitor-fab'
11
-
12
- function snapshotPatch(patch: Partial<MonitorSnapshotPayload> = {}): MonitorSnapshotPayload {
13
- return {
14
- ok: true,
15
- startedAt: new Date().toISOString(),
16
- gross: { exact: 10_000, estimated: 0 },
17
- offsets: { exact: 1_200, estimated: 0 },
18
- net: { exact: 8_800, estimated: 0 },
19
- usage: { requests: 5, cacheHitRate: 0.812 },
20
- pricing: { currency: 'USD', actualCost: '0.12', estimatedSavedCost: '1.30' },
21
- intent: { override: undefined, observedEnabled: false, gate: { floorFraction: 0.45, growthTokens: 50_000 }, lastFold: undefined },
22
- recentOffsets: [{ component: 'fresh', tokens: 1_200 }],
23
- sessionScope: null,
24
- ...patch,
25
- }
26
- }
27
-
28
- function makeDeps(patch: Partial<MonitorFabDeps> & { snapshots?: MonitorSnapshotPayload[] } = {}): MonitorFabDeps & {
29
- snapshots: MonitorSnapshotPayload[]
30
- overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
31
- } {
32
- const deps: MonitorFabDeps & {
33
- snapshots: MonitorSnapshotPayload[]
34
- overrides: Array<{ sessionId: string | undefined, action: 'on' | 'off' | 'clear' }>
35
- } = {
36
- t: (key: string) => key,
37
- sessionIdOf: () => undefined,
38
- enabledOf: () => true,
39
- fetchSnapshot: vi.fn(async () => deps.snapshots[deps.snapshots.length - 1]!),
40
- applyOverride: vi.fn(async (_sessionId: string | undefined, action: 'on' | 'off' | 'clear') => {
41
- deps.overrides.push({ sessionId: undefined, action })
42
- }),
43
- snapshots: [snapshotPatch()],
44
- overrides: [],
45
- initialDelayMs: 1,
46
- }
47
- return Object.assign(deps, patch)
48
- }
49
-
50
- /** 真实时钟下等条件成立(轮询 1ms 一轮,上限 500ms)。 */
51
- async function waitFor(predicate: () => boolean): Promise<void> {
52
- const deadline = Date.now() + 500
53
- while (!predicate()) {
54
- if (Date.now() > deadline) throw new Error('waitFor timeout')
55
- await new Promise(resolve => setTimeout(resolve, 5))
56
- }
57
- }
58
-
59
- afterEach(() => {
60
- document.body.innerHTML = ''
61
- localStorage.clear()
62
- vi.restoreAllMocks()
63
- })
64
-
65
- describe('monitor fab (body-level overlay)', () => {
66
- it('mounts idempotently — double init keeps a single FAB', () => {
67
- const deps = makeDeps()
68
- initMonitorFab(deps)
69
- initMonitorFab(deps)
70
- expect(document.querySelectorAll(`#${FAB_ID}`).length).toBe(1)
71
- })
72
-
73
- it('enabled gate hides the ball and suppresses polling', async () => {
74
- const fetchSnapshot = vi.fn(async () => snapshotPatch())
75
- initMonitorFab(makeDeps({ enabledOf: () => false, fetchSnapshot, initialDelayMs: 5 }))
76
- const fab = document.getElementById(FAB_ID) as HTMLElement
77
- await waitFor(() => fab.style.display === 'none')
78
- expect(fetchSnapshot).not.toHaveBeenCalled()
79
- })
80
-
81
- it('enabled: ball visible, first tick renders the snapshot', async () => {
82
- initMonitorFab(makeDeps())
83
- const fab = document.getElementById(FAB_ID) as HTMLElement
84
- await waitFor(() => fab.style.display === 'block')
85
- const net = document.querySelector('[data-net]') as HTMLElement
86
- expect(net.textContent).toBe('8,800')
87
- expect(fab.classList.contains('lit')).toBe(false)
88
- })
89
-
90
- it('negative net lights the ball (负节省警示)', async () => {
91
- initMonitorFab(makeDeps({ snapshots: [snapshotPatch({ net: { exact: -800, estimated: 0 } })] }))
92
- await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
93
- })
94
-
95
- it('fetch failure flips the stale marker without throwing', async () => {
96
- initMonitorFab(makeDeps({ fetchSnapshot: vi.fn(async () => { throw new Error('down') }) }))
97
- await waitFor(() => document.querySelector('[data-stale]')?.classList.contains('show') === true)
98
- })
99
-
100
- it('override buttons drive applyOverride then refetch', async () => {
101
- const deps = makeDeps()
102
- initMonitorFab(deps)
103
- await waitFor(() => (document.querySelector('[data-overoff]') as HTMLButtonElement)?.disabled === false)
104
- ;(document.querySelector('[data-overoff]') as HTMLButtonElement).click()
105
- await waitFor(() => deps.overrides.length === 1)
106
- expect(deps.overrides).toEqual([{ sessionId: undefined, action: 'off' }])
107
- await waitFor(() => (deps.fetchSnapshot as ReturnType<typeof vi.fn>).mock.calls.length >= 2)
108
- })
109
-
110
- it('灾难性遗忘区建议:点亮悬浮球并展示提示行', async () => {
111
- const deps = makeDeps({
112
- snapshots: [snapshotPatch({
113
- net: { exact: 0, estimated: 0 },
114
- context: { liveTokens: 90_000, contextWindow: 100_000, pct: 0.9 },
115
- suggestion: { suggest: true, thresholdPct: 0.7, occupancyPct: 0.9 },
116
- })],
117
- })
118
- initMonitorFab(deps)
119
- await waitFor(() => (document.getElementById(FAB_ID) as HTMLElement).classList.contains('lit'))
120
- const hint = document.querySelector('[data-hint]') as HTMLElement
121
- expect(hint.classList.contains('show')).toBe(true)
122
- expect(hint.textContent).toBe('monitor.panel.suggest')
123
- })
124
-
125
- it('无建议时提示行隐藏', async () => {
126
- initMonitorFab(makeDeps())
127
- await waitFor(() => (document.querySelector('[data-net]') as HTMLElement).textContent !== '')
128
- expect(document.querySelector('[data-hint]')?.classList.contains('show')).toBe(false)
129
- })
130
-
131
- it('position persists across drag-free re-init via localStorage', () => {
132
- localStorage.setItem('dsh.cci.monitor.pos', JSON.stringify({ x: 40, y: 60 }))
133
- initMonitorFab(makeDeps())
134
- const fab = document.getElementById(FAB_ID) as HTMLElement
135
- expect(fab.style.left).toBe('40px')
136
- expect(fab.style.top).toBe('60px')
137
- })
138
- })