dsh-context-compression-improved 0.11.0 → 0.11.2

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 (310) hide show
  1. package/README.md +15 -110
  2. package/README.zh.md +14 -104
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  5. package/{packages/selector/lib → lib}/index.js +101 -0
  6. package/package.json +129 -116
  7. package/screenshots.json +3 -6
  8. package/.agents/plans/improve/checklist.md +0 -32
  9. package/.agents/plans/improve/findings.md +0 -102
  10. package/.agents/plans/improve/spec.md +0 -53
  11. package/.agents/plans/improve/tasks.md +0 -70
  12. package/.gitattributes +0 -2
  13. package/.githooks/pre-push +0 -37
  14. package/.github/workflows/ci.yml +0 -47
  15. package/CHANGELOG.de.md +0 -580
  16. package/CHANGELOG.es.md +0 -588
  17. package/CHANGELOG.fr.md +0 -576
  18. package/CHANGELOG.it.md +0 -577
  19. package/CHANGELOG.ja.md +0 -261
  20. package/CHANGELOG.ko.md +0 -254
  21. package/CHANGELOG.md +0 -557
  22. package/CHANGELOG.ru.md +0 -554
  23. package/CHANGELOG.zh.md +0 -247
  24. package/CONTRIBUTING.md +0 -22
  25. package/README.de.md +0 -96
  26. package/README.es.md +0 -96
  27. package/README.fr.md +0 -96
  28. package/README.it.md +0 -96
  29. package/README.ja.md +0 -102
  30. package/README.ko.md +0 -102
  31. package/README.ru.md +0 -96
  32. package/SECURITY.md +0 -18
  33. package/assets/board.png +0 -0
  34. package/assets/context.png +0 -0
  35. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  36. package/docs/assets/context-compression-selector-settings.png +0 -0
  37. package/docs/compat-0.1.5-report.md +0 -77
  38. package/docs/installation.de.md +0 -104
  39. package/docs/installation.es.md +0 -104
  40. package/docs/installation.fr.md +0 -104
  41. package/docs/installation.it.md +0 -104
  42. package/docs/installation.ja.md +0 -78
  43. package/docs/installation.ko.md +0 -78
  44. package/docs/installation.md +0 -103
  45. package/docs/installation.ru.md +0 -104
  46. package/docs/installation.zh.md +0 -100
  47. package/docs/repair-log.md +0 -657
  48. package/docs/shallow-teaching-preset-template.md +0 -46
  49. package/eslint.config.js +0 -30
  50. package/packages/selector/LICENSE +0 -21
  51. package/packages/selector/README.md +0 -26
  52. package/packages/selector/README.zh.md +0 -24
  53. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  54. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  55. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  56. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  57. package/packages/selector/lib/style.css +0 -350
  58. package/packages/selector/package.json +0 -178
  59. package/packages/selector/screenshots.json +0 -3
  60. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -352
  61. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  62. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -89
  63. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  64. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  65. package/packages/selector/src/client/bridge-scope.ts +0 -125
  66. package/packages/selector/src/client/decode.ts +0 -68
  67. package/packages/selector/src/client/fab-pos.ts +0 -71
  68. package/packages/selector/src/client/index.ts +0 -438
  69. package/packages/selector/src/client/locales/de.ts +0 -167
  70. package/packages/selector/src/client/locales/es.ts +0 -167
  71. package/packages/selector/src/client/locales/fr.ts +0 -167
  72. package/packages/selector/src/client/locales/it.ts +0 -167
  73. package/packages/selector/src/client/locales/ja.ts +0 -167
  74. package/packages/selector/src/client/locales/ko.ts +0 -167
  75. package/packages/selector/src/client/locales/ru.ts +0 -167
  76. package/packages/selector/src/client/locales.ts +0 -334
  77. package/packages/selector/src/client/monitor-fab.ts +0 -445
  78. package/packages/selector/src/client/preset-options.ts +0 -88
  79. package/packages/selector/src/client/savings-card.tsx +0 -269
  80. package/packages/selector/src/client/scope-face.ts +0 -24
  81. package/packages/selector/src/client/settings-section.tsx +0 -156
  82. package/packages/selector/src/compat/host-generation.ts +0 -96
  83. package/packages/selector/src/compat/llm-messages.ts +0 -50
  84. package/packages/selector/src/compat/settings-lease.ts +0 -108
  85. package/packages/selector/src/compat/tool-result.ts +0 -91
  86. package/packages/selector/src/css-modules.d.ts +0 -6
  87. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  88. package/packages/selector/src/estimator-catalog.ts +0 -104
  89. package/packages/selector/src/index.ts +0 -890
  90. package/packages/selector/src/invariant.ts +0 -113
  91. package/packages/selector/src/preset-overlay.ts +0 -749
  92. package/packages/selector/src/profiles.ts +0 -554
  93. package/packages/selector/src/pruner/content.ts +0 -199
  94. package/packages/selector/src/pruner/session.ts +0 -97
  95. package/packages/selector/src/pruner/state.ts +0 -61
  96. package/packages/selector/src/pruner/tuning.ts +0 -23
  97. package/packages/selector/src/pruner/types.ts +0 -78
  98. package/packages/selector/src/pruner.ts +0 -3222
  99. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  100. package/packages/selector/src/runtime/audit.ts +0 -321
  101. package/packages/selector/src/runtime/config.ts +0 -887
  102. package/packages/selector/src/runtime/custom-policy.ts +0 -300
  103. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  104. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  105. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  106. package/packages/selector/src/runtime/fold-router.ts +0 -143
  107. package/packages/selector/src/runtime/measurement.ts +0 -444
  108. package/packages/selector/src/runtime/monitor.ts +0 -341
  109. package/packages/selector/src/runtime/panel-command.ts +0 -213
  110. package/packages/selector/src/runtime/reducers.ts +0 -1755
  111. package/packages/selector/src/runtime/retrieve.ts +0 -505
  112. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  113. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  114. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  115. package/packages/selector/src/runtime/savings.ts +0 -526
  116. package/packages/selector/src/runtime/sediment-card.ts +0 -126
  117. package/packages/selector/src/runtime/sediment-clock.ts +0 -87
  118. package/packages/selector/src/runtime/sediment-guard.ts +0 -136
  119. package/packages/selector/src/runtime/sediment-publish.ts +0 -144
  120. package/packages/selector/src/runtime/sediment-span.ts +0 -170
  121. package/packages/selector/src/runtime/sediment.ts +0 -209
  122. package/packages/selector/src/runtime/session-events.ts +0 -30
  123. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  124. package/packages/selector/src/runtime/shallow-tools.ts +0 -342
  125. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  126. package/packages/selector/src/runtime/stats-db.ts +0 -492
  127. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  128. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  129. package/packages/selector/src/runtime/summary-command.ts +0 -127
  130. package/packages/selector/src/runtime/tail-trim.ts +0 -177
  131. package/packages/selector/src/runtime/token-count.ts +0 -72
  132. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  133. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  134. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  135. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  136. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -82
  137. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  138. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  139. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  140. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  141. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  142. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -129
  143. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  144. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  145. package/packages/selector/src/runtime/tool-names.ts +0 -42
  146. package/packages/selector/src/runtime/toolclass.ts +0 -103
  147. package/packages/selector/src/runtime/triage/masks.ts +0 -128
  148. package/packages/selector/src/runtime/triage/shallow.ts +0 -132
  149. package/packages/selector/src/runtime/triage/signals.ts +0 -167
  150. package/packages/selector/src/runtime/triage/types.ts +0 -125
  151. package/packages/selector/src/runtime/types.ts +0 -396
  152. package/packages/selector/src/runtime/value.ts +0 -48
  153. package/packages/selector/src/settings-bridge.ts +0 -175
  154. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  155. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  156. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  157. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  158. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  159. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  160. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  161. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  162. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  163. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  164. package/packages/selector/tests/fab-pos.client.spec.ts +0 -47
  165. package/packages/selector/tests/fixtures/sediment-pool/52adc205-cloud-5.orig.txt +0 -231
  166. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-25.orig.txt +0 -236
  167. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-38.orig.txt +0 -220
  168. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-42.orig.txt +0 -140
  169. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-cloud-53.orig.txt +0 -117
  170. package/packages/selector/tests/fixtures/sediment-pool/95fcba5d-local-10.orig.txt +0 -67
  171. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-45.orig.txt +0 -119
  172. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-49.orig.txt +0 -119
  173. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-63.orig.txt +0 -131
  174. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-75.orig.txt +0 -196
  175. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-76.orig.txt +0 -71
  176. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-85.orig.txt +0 -126
  177. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-86.orig.txt +0 -86
  178. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-87.orig.txt +0 -50
  179. package/packages/selector/tests/fixtures/sediment-pool/a7a767c0-cloud-96.orig.txt +0 -102
  180. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  181. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  182. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  183. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  184. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  185. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  186. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  187. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -240
  188. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  189. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  190. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  191. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  192. package/packages/selector/tests/ptc-custom-write.client.spec.ts +0 -86
  193. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -89
  194. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  195. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  196. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  197. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  198. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  199. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  200. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  201. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  202. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  203. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  204. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  205. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  206. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  207. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  208. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  209. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  210. package/packages/selector/tests/runtime/fold-router.spec.ts +0 -140
  211. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  212. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  213. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  214. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  215. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  216. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  217. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  218. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  219. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  220. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  221. package/packages/selector/tests/runtime/ptc-profile.spec.ts +0 -133
  222. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2795
  223. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  224. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  225. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  226. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  227. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  228. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  229. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  230. package/packages/selector/tests/runtime/sediment-card.spec.ts +0 -111
  231. package/packages/selector/tests/runtime/sediment-config.spec.ts +0 -56
  232. package/packages/selector/tests/runtime/sediment-guard.spec.ts +0 -71
  233. package/packages/selector/tests/runtime/sediment-masks.spec.ts +0 -95
  234. package/packages/selector/tests/runtime/sediment-orchestrator.spec.ts +0 -166
  235. package/packages/selector/tests/runtime/sediment-pool-share.spec.ts +0 -65
  236. package/packages/selector/tests/runtime/sediment-publish.spec.ts +0 -142
  237. package/packages/selector/tests/runtime/sediment-real-shapes.spec.ts +0 -158
  238. package/packages/selector/tests/runtime/sediment-settings.spec.ts +0 -73
  239. package/packages/selector/tests/runtime/sediment-signals.spec.ts +0 -124
  240. package/packages/selector/tests/runtime/sediment-span.spec.ts +0 -92
  241. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  242. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  243. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  244. package/packages/selector/tests/runtime/shallow-primitives.spec.ts +0 -135
  245. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  246. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  247. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -350
  248. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  249. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  250. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  251. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  252. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  253. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  254. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  255. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  256. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  257. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  258. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -121
  259. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  260. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  261. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  262. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  263. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  264. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  265. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  266. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  267. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  268. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  269. package/packages/selector/tsconfig.json +0 -11
  270. package/packages/selector/tsdown.client.config.ts +0 -102
  271. package/packages/selector/tsdown.config.ts +0 -20
  272. package/pnpm-workspace.yaml +0 -76
  273. package/scripts/capture-profile-baseline.mjs +0 -42
  274. package/scripts/cell-browser-e2e.mjs +0 -354
  275. package/scripts/generate-tokenizer-fixtures.py +0 -81
  276. package/scripts/generate-vision-fixtures.py +0 -208
  277. package/scripts/hosts.d.mts +0 -3
  278. package/scripts/hosts.mjs +0 -79
  279. package/scripts/packed-components-smoke.mjs +0 -763
  280. package/scripts/packed-install-e2e.mjs +0 -1346
  281. package/scripts/sediment-latency-report.mjs +0 -63
  282. package/scripts/sync-hosts.mjs +0 -174
  283. package/scripts/toolclass-corpus-replay.mjs +0 -281
  284. package/scripts/verify-release.mjs +0 -343
  285. package/tests/TEST_INVENTORY.md +0 -41
  286. package/tsconfig.base.json +0 -18
  287. package/tsconfig.json +0 -7
  288. package/tsconfig.tests.json +0 -15
  289. package/vitest.built.config.ts +0 -9
  290. package/vitest.config.ts +0 -54
  291. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  292. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  293. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  294. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  295. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  296. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  297. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  298. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  299. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  300. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  301. /package/{packages/selector/lib → lib}/client.js +0 -0
  302. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  303. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  304. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  305. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  306. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  307. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  308. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  309. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  310. /package/{packages/selector/lib → lib}/tool-result.js +0 -0
@@ -1,749 +0,0 @@
1
- /** Plugin-owned, reversible compression overlays for native agent presets. */
2
-
3
- import { AsyncLocalStorage } from 'node:async_hooks'
4
- import { createHash } from 'node:crypto'
5
- import { chmod, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from 'node:fs/promises'
6
- import { tmpdir } from 'node:os'
7
- import { isAbsolute, join } from 'node:path'
8
- import { fileURLToPath } from 'node:url'
9
- import { applyEntryPatches, entryListSchema } from '@deepseek-ai/cordis-plugin-include'
10
- import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
11
- import type { AgentPreset } from '@deepseek-ai/dsh-agent-presets'
12
- import { dump, load } from 'js-yaml'
13
-
14
- /** Cordis 把未被代理的原始 service 暴露在该 symbol 下(见 cordis createTraceable 的 get 陷阱)。 */
15
- const CORDIS_ORIGINAL = Symbol.for('cordis.original')
16
-
17
- /**
18
- * 取得 Cordis traceable 代理背后的原始 service。原始对象是宿主内部调用
19
- * (`this.resolveMountable → this.resolve`) 时的接收者;只有装饰它,压缩栈补丁才能
20
- * 真正注入(实证:装饰代理/原型代理均失败)。
21
- */
22
- function rawService(presets: object): object {
23
- const raw = (presets as Record<symbol, unknown>)[CORDIS_ORIGINAL]
24
- return raw !== null && typeof raw === 'object' ? raw : presets
25
- }
26
-
27
- /** Absolute runtime entry points used by the generated compression stack. */
28
- export interface CompressionModulePaths {
29
- /** Exact aggregate/history compaction implementation shipped with the Bundle. */
30
- readonly compactionBasic: string
31
- /** Exact manual compact command shipped with the Bundle. */
32
- readonly commandCompact: string
33
- /** Exact enhanced tool-result pruner shipped with the Bundle. */
34
- readonly toolResultPruner: string
35
- }
36
-
37
- /** The public native methods the decorator uses without reaching into core internals. */
38
- export interface OverlayableAgentPresets {
39
- /** Resolve a source preset for discovery and authoring. */
40
- resolve(id?: string): Promise<AgentPreset>
41
- /** Compose an agent from a preset. */
42
- mount(agentCtx: unknown, id?: string): Promise<AgentPreset>
43
- /** Move a blank agent to a different preset. */
44
- recompose(agentCtx: unknown, id: string): Promise<AgentPreset>
45
- /** Ensure a standing preset composition for cold readers. */
46
- standingKeyFor(id?: string): Promise<unknown>
47
- /** Register a preset definition; the 0.2.0 registry pre-composes it here. Optional: older host lines lack it. */
48
- register?(definition: unknown): Promise<unknown>
49
- }
50
-
51
- /** Configuration for one reversible decoration. */
52
- export interface PresetOverlayOptions {
53
- /** Absolute module entry points written into the generated composition. */
54
- readonly modules: CompressionModulePaths
55
- /** Preset ids that deliberately retain their native composition. */
56
- readonly excludedPresetIds?: readonly string[]
57
- /**
58
- * Reads the Auto Compact threshold percent (50�?0) to freeze into newly
59
- * generated compositions �?once per composition, into BOTH the
60
- * compaction-basic `thresholdRatio` and the runtime deployment config, so
61
- * one generation can never split Auto Compact and micro compact across two
62
- * thresholds. Returning `undefined` keeps both defaults untouched.
63
- */
64
- readonly autoCompactThresholdPercent?: () => number | undefined
65
- /** Test seam for locating the owner-only generated directory. */
66
- readonly tempParent?: string
67
- /**
68
- * Metadata boundary used to prepare and observe the native standing key.
69
- * Production uses the real filesystem; tests may model coarser mtime
70
- * resolution without replacing identity generation.
71
- */
72
- readonly metadataIo?: PresetOverlayMetadataIo
73
- }
74
-
75
- /** Minimal filesystem metadata surface that determines AgentPresets identity. */
76
- export interface PresetOverlayMetadataIo {
77
- /** Persist one deterministic atime/mtime stamp on an unpublished staging file. */
78
- setTimes(path: string, stamp: Date): Promise<void>
79
- /** Read exactly the fields consumed by AgentPresets' standing key. */
80
- read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>>
81
- }
82
-
83
- /** Handle returned by {@link decorateAgentPresets}. */
84
- export interface PresetOverlayInstallation {
85
- /** Restore native methods and remove every generated composition. */
86
- dispose(): Promise<void>
87
- }
88
-
89
- /**
90
- * Fixed base for deterministic standing mtimes. The stamp is derived from the
91
- * FULL content identity (source + modules + threshold), not from the write
92
- * clock: identical identities always republish to the same stamp (no
93
- * generation flapping).
94
- *
95
- * The seconds component carries an 8-hex identity window directly. Most
96
- * identities therefore separate even when a filesystem truncates mtimes to
97
- * whole seconds; identities that share that 32-bit window deliberately collide
98
- * first, are detected from the staging file's observed {mtimeMs, size}, and
99
- * escalate to later hash windows before publication. The prefix keeps the
100
- * latest possible stamp around year 2162, inside the nanosecond range every
101
- * supported filesystem can store; the next 3 hex digits set sub-second
102
- * milliseconds on filesystems that preserve them.
103
- */
104
- const STANDING_MTIME_EPOCH_SECONDS = Math.floor(Date.UTC(2026, 0, 1) / 1000)
105
- const STANDING_MTIME_WINDOW_HEX = 11
106
-
107
- const DEFAULT_METADATA_IO: PresetOverlayMetadataIo = Object.freeze({
108
- async setTimes(path: string, stamp: Date): Promise<void> {
109
- await utimes(path, stamp, stamp)
110
- },
111
- async read(path: string): Promise<Readonly<{ mtimeMs: number, size: number }>> {
112
- const observed = await stat(path)
113
- return { mtimeMs: observed.mtimeMs, size: observed.size }
114
- },
115
- })
116
-
117
- /**
118
- * Deterministic standing stamp for one full generation identity, read from
119
- * hash window `windowIndex` (0 = identity prefix). Exported for the
120
- * collision-fixture tests; production code uses {@link standingStampMs}.
121
- */
122
- export function standingStampMsAtWindow(identity: string, windowIndex: number): number {
123
- const start = windowIndex * STANDING_MTIME_WINDOW_HEX
124
- const seconds = STANDING_MTIME_EPOCH_SECONDS + parseInt(identity.slice(start, start + 8).padEnd(8, '0'), 16)
125
- const subSecond = parseInt(identity.slice(start + 8, start + STANDING_MTIME_WINDOW_HEX).padEnd(3, '0'), 16) % 1000
126
- return seconds * 1000 + subSecond
127
- }
128
-
129
- /** Deterministic standing stamp for one full generation identity. */
130
- export function standingStampMs(identity: string): number {
131
- return standingStampMsAtWindow(identity, 0)
132
- }
133
-
134
- /**
135
- * True for the filesystem errors a concurrent publish can raise on Windows:
136
- * `MoveFileEx` reports a lost race — or a reader holding the destination open —
137
- * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
138
- */
139
- function isPublishRace(error: unknown): boolean {
140
- const code = (error as { code?: unknown } | null)?.code
141
- return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES' || code === 'EEXIST'
142
- }
143
-
144
- const COMPRESSION_IDS = new Set([
145
- 'compaction',
146
- 'compaction-basic',
147
- 'command-compact',
148
- 'tool-result-pruner',
149
- ])
150
-
151
- const COMPRESSION_PACKAGES = new Set([
152
- '@deepseek-ai/dsh-compaction-basic',
153
- '@deepseek-ai/dsh-command-compact',
154
- '@deepseek-ai/dsh-compaction-tool-result-pruner',
155
- 'dsh-context-compression-improved-runtime',
156
- 'dsh-context-compression-improved',
157
- 'dsh-context-compression-improved/pruner',
158
- ])
159
-
160
- /**
161
- * Resolve the three compression package entries once from this package.
162
- * @returns Absolute entry paths for the canonical compression layer.
163
- */
164
- export function resolveCompressionModulePaths(): CompressionModulePaths {
165
- return {
166
- compactionBasic: modulePath(
167
- '@deepseek-ai/dsh-compaction-basic', import.meta.resolve('@deepseek-ai/dsh-compaction-basic')),
168
- commandCompact: modulePath(
169
- '@deepseek-ai/dsh-command-compact', import.meta.resolve('@deepseek-ai/dsh-command-compact')),
170
- toolResultPruner: modulePath(
171
- 'dsh-context-compression-improved/pruner', import.meta.resolve('dsh-context-compression-improved/pruner')),
172
- }
173
- }
174
-
175
- /** Convert one package resolution into the absolute path preset mounting accepts. */
176
- function modulePath(specifier: string, resolved: string): string {
177
- if (!resolved.startsWith('file:')) {
178
- throw new Error(`context-compression selector: ${specifier} resolved outside the filesystem (${resolved})`)
179
- }
180
- return fileURLToPath(resolved)
181
- }
182
-
183
- /** One operation's permission to see generated presets through resolve(). */
184
- interface CompositionOperation {
185
- readonly composing: true
186
- }
187
-
188
- /** Generated composition storage owned by one decorator installation. */
189
- class PresetOverlayStore {
190
- private rootTask: Promise<string> | undefined
191
- private disposed = false
192
- private readonly metadataIo: PresetOverlayMetadataIo
193
-
194
- constructor(private readonly options: PresetOverlayOptions) {
195
- this.metadataIo = options.metadataIo ?? DEFAULT_METADATA_IO
196
- const paths = Object.entries(options.modules) as [keyof CompressionModulePaths, string][]
197
- for (const [name, path] of paths) {
198
- if (!isAbsolute(path)) {
199
- throw new TypeError(`context-compression selector: module path ${name} is not absolute: ${path}`)
200
- }
201
- }
202
- }
203
-
204
- /** Return a detached preset record whose path names the canonical overlay. */
205
- async overlay(preset: AgentPreset): Promise<AgentPreset> {
206
- if (this.disposed) throw new Error('context-compression selector: preset overlay is disposed')
207
- if (preset.broken !== undefined) return preset
208
- const source = await readFile(preset.path, 'utf8')
209
- const rows = parseRows(source, preset.path)
210
- const thresholdPercent = this.options.autoCompactThresholdPercent?.()
211
- if (thresholdPercent !== undefined && !Number.isFinite(thresholdPercent)) {
212
- // JSON.stringify maps NaN to null (colliding identities) and the YAML
213
- // dump would serialize it as `.nan`; refuse instead.
214
- throw new Error(`context-compression selector: Auto Compact threshold percent must be finite, got ${String(thresholdPercent)}`)
215
- }
216
- const patched = applyEntryPatches(
217
- stripCompressionRows(rows),
218
- [{ insert: canonicalCompressionRows(this.options.modules, thresholdPercent) }],
219
- (message: string, ...args: unknown[]) => {
220
- throw new Error(renderPatchWarning(message, args))
221
- },
222
- )
223
- const rendered = dump(patched, {
224
- schema: entryListSchema,
225
- noRefs: true,
226
- lineWidth: -1,
227
- sortKeys: false,
228
- })
229
- // The percent joins the content identity by value, not by rendered
230
- // length, so an equal-length change (70 -> 80) still produces a new file.
231
- const identity = createHash('sha256')
232
- .update(preset.id).update('\0')
233
- .update(source).update('\0')
234
- .update(JSON.stringify({ modules: this.options.modules, autoCompactThresholdPercent: thresholdPercent ?? null }))
235
- .digest('hex')
236
- .slice(0, 24)
237
- const root = await this.root()
238
- const path = join(root, `${preset.id}-${identity}.agent.cordis.yml`)
239
- // Publish through a unique temporary file whose content, permissions, and
240
- // DETERMINISTIC identity stamp are all complete before the atomic rename:
241
- // once the final path exists it is fully metadata'd, so a concurrent
242
- // composer (or AgentPresets' standing-key reader) can never observe a
243
- // wall-clock mtime on a published composition.
244
- const staging = join(root, `${preset.id}-${identity}.${String(process.pid)}-${String(Math.random()).slice(2)}.tmp`)
245
- try {
246
- await writeFile(staging, rendered, { encoding: 'utf8', mode: 0o600 })
247
- await chmod(staging, 0o600)
248
- // Reserve and verify the FINAL observed standing key while the file is
249
- // still private. No reader can observe a colliding {mtimeMs,size}
250
- // between rename and a later corrective utimes call.
251
- await this.disambiguateStamp(staging, identity)
252
- await this.publish(staging, path)
253
- } catch (error) {
254
- // A failed publish must not leak its staging file into the store; the
255
- // cleanup must never mask the original failure either.
256
- try {
257
- await rm(staging, { force: true })
258
- } catch {
259
- // intentional: the publish error below is the actionable one
260
- }
261
- throw error
262
- }
263
- return { ...preset, path }
264
- }
265
-
266
- /** In-flight publish chains, one per destination path. */
267
- private readonly publishChains = new Map<string, Promise<void>>()
268
-
269
- /**
270
- * Publish one stamped staging file to its final path, serialized per path.
271
- *
272
- * POSIX `rename` replaces an existing destination atomically, so concurrent
273
- * composers of one identity are naturally idempotent there. Windows
274
- * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
275
- * surfaced as `standingKeyFor()` throwing during concurrent composition.
276
- * Every composer of one identity writes identical bytes and re-derives the
277
- * same deterministic identity stamp, so a destination that already observes
278
- * this staging file's {mtimeMs, size} key IS the intended end state: confirm
279
- * it and treat the lost race as success. Every other outcome still throws, so
280
- * a silently reused generation stays forbidden, and the caller still removes
281
- * the staging file when this rejects.
282
- */
283
- private publish(staging: string, path: string): Promise<void> {
284
- const previous = this.publishChains.get(path) ?? Promise.resolve()
285
- const queued = previous.catch(() => undefined).then(async () => {
286
- try {
287
- await rename(staging, path)
288
- return
289
- } catch (error) {
290
- if (!isPublishRace(error)) throw error
291
- try {
292
- const intended = await this.metadataIo.read(staging)
293
- const published = await this.metadataIo.read(path)
294
- // Sub-second precision survives a wrapped seconds field, but NTFS
295
- // rounds it to 100ns, so compare the standing key within that
296
- // rounding rather than by exact float equality.
297
- if (published.size === intended.size
298
- && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
299
- await rm(staging, { force: true })
300
- return
301
- }
302
- } catch {
303
- // The destination is unreadable: report the original publish failure.
304
- }
305
- throw error
306
- }
307
- })
308
- const tracked = queued.finally(() => {
309
- if (this.publishChains.get(path) === tracked) this.publishChains.delete(path)
310
- })
311
- this.publishChains.set(path, tracked)
312
- return tracked
313
- }
314
-
315
- /** Observed {mtimeMs,size} keys published by this store, per identity. */
316
- private readonly standingKeys = new Map<string, string>()
317
-
318
- /**
319
- * Ensure an unpublished staging file's observed {mtimeMs, size} is not
320
- * shared with a different identity. Escalation rewrites the mtime from later
321
- * hash windows before atomic publication, and fails loudly if no window
322
- * separates them (better a loud error than a silently reused generation).
323
- */
324
- private async disambiguateStamp(path: string, identity: string): Promise<void> {
325
- for (let window = 0; window < 3; window += 1) {
326
- const stamp = new Date(standingStampMsAtWindow(identity, window))
327
- await this.metadataIo.setTimes(path, stamp)
328
- // The native key uses the on-disk byte size, not the UTF-16 length of
329
- // the rendered string.
330
- const observed = await this.metadataIo.read(path)
331
- const key = `${String(observed.mtimeMs)}:${String(observed.size)}`
332
- const owner = this.standingKeys.get(key)
333
- if (owner === undefined || owner === identity) {
334
- this.standingKeys.set(key, identity)
335
- return
336
- }
337
- }
338
- throw new Error(`context-compression selector: standing stamp collision for identity ${identity} across all hash windows`)
339
- }
340
-
341
- /** Remove all generated files without touching any source preset. */
342
- async dispose(): Promise<void> {
343
- if (this.disposed) return
344
- this.disposed = true
345
- if (this.rootTask === undefined) return
346
- const root = await this.rootTask
347
- await rm(root, { recursive: true, force: true })
348
- }
349
-
350
- /** Lazily create the one owner-only directory for this installation. */
351
- private async root(): Promise<string> {
352
- if (this.rootTask === undefined) {
353
- const parent = this.options.tempParent ?? tmpdir()
354
- this.rootTask = mkdtemp(join(parent, 'dsh-context-compression-presets-'))
355
- .then(async (root) => {
356
- await chmod(root, 0o700)
357
- return root
358
- })
359
- }
360
- return await this.rootTask
361
- }
362
- }
363
-
364
- /** Parse one native preset with exactly the Loader's YAML dialect. */
365
- function parseRows(source: string, path: string): EntryOptions[] {
366
- const parsed = load(source, { schema: entryListSchema })
367
- if (!Array.isArray(parsed)) {
368
- throw new TypeError(`context-compression selector: preset ${path} is not a top-level entry list`)
369
- }
370
- return parsed as EntryOptions[]
371
- }
372
-
373
- /** Remove any prior compression implementation before adding the canonical one. */
374
- function stripCompressionRows(rows: EntryOptions[]): EntryOptions[] {
375
- const kept: EntryOptions[] = []
376
- for (const row of rows) {
377
- if (COMPRESSION_IDS.has(row.id) || COMPRESSION_PACKAGES.has(row.name)) continue
378
- if (row.group === true && Array.isArray(row.config)) {
379
- const nested = row.config as unknown as EntryOptions[]
380
- kept.push({ ...row, config: stripCompressionRows(nested) })
381
- } else {
382
- kept.push(row)
383
- }
384
- }
385
- return kept
386
- }
387
-
388
- /**
389
- * Complete, same-realm compression stack added to every applicable preset.
390
- * When the Host settings expose an Auto Compact threshold, one read feeds both
391
- * the compaction-basic `thresholdRatio` (beside the pinned first-release
392
- * `retainRatio`) and the runtime deployment config, so plugin History and
393
- * native Auto Compact share one watermark for this whole generation.
394
- */
395
- function canonicalCompressionRows(
396
- modules: CompressionModulePaths,
397
- thresholdPercent?: number,
398
- ): EntryOptions[] {
399
- return [
400
- {
401
- id: 'compaction',
402
- name: 'cordis:group',
403
- group: true,
404
- isolate: {
405
- compaction: true,
406
- toolResultPruner: true,
407
- },
408
- config: [
409
- {
410
- id: 'compaction-basic',
411
- name: modules.compactionBasic,
412
- ...(thresholdPercent === undefined ? {} : {
413
- config: {
414
- thresholdRatio: thresholdPercent / 100,
415
- retainRatio: 0.16,
416
- },
417
- }),
418
- },
419
- {
420
- id: 'command-compact',
421
- name: modules.commandCompact,
422
- },
423
- {
424
- id: 'tool-result-pruner',
425
- name: modules.toolResultPruner,
426
- config: {
427
- headChars: 4096,
428
- tailChars: 1024,
429
- ...(thresholdPercent === undefined ? {} : { autoCompactThresholdPercent: thresholdPercent }),
430
- },
431
- },
432
- ],
433
- },
434
- ]
435
- }
436
-
437
- /** Render include's printf-style warning without silently losing its target. */
438
- function renderPatchWarning(message: string, args: readonly unknown[]): string {
439
- let index = 0
440
- return `context-compression selector: ${message.replace(/%C/g, () => JSON.stringify(args[index++]))}`
441
- }
442
-
443
- /** Read a definition's preset id when the shape is a plain object. */
444
- function readDefinitionId(definition: unknown): string | undefined {
445
- if (typeof definition !== 'object' || definition === null) return undefined
446
- const id = (definition as { id?: unknown }).id
447
- return typeof id === 'string' ? id : undefined
448
- }
449
-
450
- /**
451
- * Inject the canonical compression stack into one preset definition's rows.
452
- *
453
- * The 0.2.0 `dsh-agent-preset-registry` PRE-BUILDS a generation per definition
454
- * (`activate` → `mountPreset(ctx, id, definition.plugins)`) and `mount` only
455
- * `retain`s it; the composition never calls `resolve`. So the stack must land in
456
- * the definition's own `plugins` before activation, not in a resolved preset
457
- * file. Best-effort: a failed injection leaves the original rows untouched.
458
- */
459
- function injectCompressionRows(
460
- definition: unknown,
461
- options: PresetOverlayOptions,
462
- excluded: ReadonlySet<string>,
463
- ): void {
464
- const id = readDefinitionId(definition)
465
- if (id === undefined || excluded.has(id)) return
466
- const plugins = (definition as { plugins?: unknown }).plugins
467
- if (!Array.isArray(plugins)) return
468
- try {
469
- const thresholdPercent = options.autoCompactThresholdPercent?.()
470
- const next = applyEntryPatches(
471
- stripCompressionRows(plugins as EntryOptions[]),
472
- [{ insert: compressionRowsBySpecifier(thresholdPercent) }],
473
- (message: string, ...args: unknown[]) => {
474
- throw new Error(renderPatchWarning(message, args))
475
- },
476
- )
477
- ;(definition as { plugins: EntryOptions[] }).plugins = next
478
- } catch {
479
- // 保留原 rows:注入失败不影响定义注册主流程
480
- }
481
- }
482
-
483
- /**
484
- * The canonical compression stack addressed by BARE SPECIFIERS. The 0.2.0
485
- * `dsh-agent-preset-registry` preset files declare this exact group by package
486
- * name, and its loader resolves bare specifiers (`@deepseek-ai/...`,
487
- * `dsh-context-compression-improved/pruner`) — absolute filesystem paths from
488
- * {@link resolveCompressionModulePaths} are NOT accepted there (empirically:
489
- * every injected row reports "never started").
490
- */
491
- function compressionRowsBySpecifier(thresholdPercent?: number): EntryOptions[] {
492
- return [
493
- {
494
- id: 'compaction',
495
- name: 'cordis:group',
496
- group: true,
497
- isolate: { compaction: true, toolResultPruner: true },
498
- config: [
499
- {
500
- id: 'compaction-basic',
501
- name: '@deepseek-ai/dsh-compaction-basic',
502
- ...(thresholdPercent === undefined ? {} : {
503
- config: { thresholdRatio: thresholdPercent / 100, retainRatio: 0.16 },
504
- }),
505
- },
506
- { id: 'command-compact', name: '@deepseek-ai/dsh-command-compact' },
507
- {
508
- id: 'tool-result-pruner',
509
- name: 'dsh-context-compression-improved/pruner',
510
- config: {
511
- headChars: 4096,
512
- tailChars: 1024,
513
- ...(thresholdPercent === undefined ? {} : { autoCompactThresholdPercent: thresholdPercent }),
514
- },
515
- },
516
- ],
517
- },
518
- ]
519
- }
520
-
521
- /** Method names whose native execution is allowed to resolve an overlay. */
522
- type CompositionMethod = 'mount' | 'recompose' | 'standingKeyFor' | 'register'
523
-
524
- /** Restore one method to exactly the own/prototype state it had before decoration. */
525
- interface MethodSnapshot {
526
- readonly name: 'resolve' | CompositionMethod
527
- /** Object whose OWN property holds the original (the raw service target). */
528
- readonly home: object
529
- readonly own: PropertyDescriptor | undefined
530
- readonly original: (...args: never[]) => unknown
531
- wrapped?: (...args: never[]) => unknown
532
- }
533
-
534
- /** One physical decoration shared by every duplicate Host row. */
535
- interface SharedDecoration {
536
- /** Canonical options prevent two rows from silently requesting different stacks. */
537
- readonly optionsKey: string
538
- /** Number of live plugin fibers leasing this decoration. */
539
- references: number
540
- /** Physical method wrappers and generated-directory owner. */
541
- readonly installation: PresetOverlayInstallation
542
- }
543
-
544
- /**
545
- * Cordis can hand two callers different traceable proxies for one service.
546
- * Symbol properties forward to the shared target, unlike proxy identity.
547
- */
548
- const SHARED_DECORATION = Symbol.for(
549
- 'dsh-context-compression-improved/preset-overlay',
550
- )
551
-
552
- /** Object-identity keys keep test metadata policies from sharing one store. */
553
- const METADATA_IO_KEYS = new WeakMap<object, number>()
554
- let nextMetadataIoKey = 1
555
-
556
- function metadataIoKey(metadataIo: PresetOverlayMetadataIo): number {
557
- const existing = METADATA_IO_KEYS.get(metadataIo)
558
- if (existing !== undefined) return existing
559
- const key = nextMetadataIoKey
560
- nextMetadataIoKey += 1
561
- METADATA_IO_KEYS.set(metadataIo, key)
562
- return key
563
- }
564
-
565
- /**
566
- * Reversibly decorate native AgentPresets composition calls.
567
- *
568
- * Duplicate Host rows share one physical decoration. This matters while an
569
- * installation migrates from a Harness-bundled selector row to the standalone
570
- * Bundle: either row can unload first without double-compressing or disposing
571
- * the generated files still used by the other.
572
- * @param presets Native AgentPresets service to decorate during composition.
573
- * @param options Canonical module paths, exclusions, and optional test directory.
574
- * @returns A reference-counted handle that restores the native service on final disposal.
575
- */
576
- export function decorateAgentPresets(
577
- presets: OverlayableAgentPresets,
578
- options: PresetOverlayOptions,
579
- ): PresetOverlayInstallation {
580
- const optionsKey = overlayOptionsKey(options)
581
- const carrier = presets as OverlayableAgentPresets & { [SHARED_DECORATION]?: SharedDecoration }
582
- let shared = carrier[SHARED_DECORATION]
583
- if (shared === undefined) {
584
- shared = {
585
- optionsKey,
586
- references: 0,
587
- installation: installAgentPresetsDecoration(presets, options),
588
- }
589
- Object.defineProperty(carrier, SHARED_DECORATION, {
590
- configurable: true,
591
- enumerable: false,
592
- writable: false,
593
- value: shared,
594
- })
595
- } else if (shared.optionsKey !== optionsKey) {
596
- throw new Error('context-compression selector: AgentPresets already has a different compression overlay')
597
- }
598
- const lease = shared
599
- lease.references += 1
600
-
601
- let disposed = false
602
- return {
603
- async dispose(): Promise<void> {
604
- if (disposed) return
605
- disposed = true
606
- lease.references -= 1
607
- if (lease.references !== 0) return
608
- if (carrier[SHARED_DECORATION] === lease) {
609
- Reflect.deleteProperty(carrier, SHARED_DECORATION)
610
- }
611
- await lease.installation.dispose()
612
- },
613
- }
614
- }
615
-
616
- /** Stable equality for two rows asking to share one physical overlay. */
617
- function overlayOptionsKey(options: PresetOverlayOptions): string {
618
- return JSON.stringify({
619
- modules: options.modules,
620
- excludedPresetIds: [...(options.excludedPresetIds ?? ['minimal'])].sort(),
621
- tempParent: options.tempParent,
622
- metadataIo: metadataIoKey(options.metadataIo ?? DEFAULT_METADATA_IO),
623
- })
624
- }
625
-
626
- /**
627
- * Install the one physical method decoration leased by public callers.
628
- *
629
- * Direct resolution and authoring stay source-preserving. AsyncLocalStorage
630
- * scopes the overlay to the async call tree of mount/recompose/standingKeyFor,
631
- * so an unrelated resolve racing the mount cannot inherit its generated path.
632
- */
633
- function installAgentPresetsDecoration(
634
- presets: OverlayableAgentPresets,
635
- options: PresetOverlayOptions,
636
- ): PresetOverlayInstallation {
637
- const excluded = new Set(options.excludedPresetIds ?? ['minimal'])
638
- const operations = new AsyncLocalStorage<CompositionOperation>()
639
- const store = new PresetOverlayStore(options)
640
- const raw = rawService(presets)
641
- const snapshots = snapshotMethods(presets)
642
- const resolveSnapshot = snapshotFor(snapshots, 'resolve')
643
-
644
- const resolveWrapped = async (id?: string): Promise<AgentPreset> => {
645
- const preset = await Reflect.apply(resolveSnapshot.original, raw, [id]) as AgentPreset
646
- const composing = operations.getStore()?.composing === true
647
- if (!composing || excluded.has(preset.id)) return preset
648
- return await store.overlay(preset)
649
- }
650
- installMethod(resolveSnapshot, resolveWrapped)
651
-
652
- for (const method of ['mount', 'recompose', 'standingKeyFor'] as const) {
653
- const snapshot = snapshots.find(candidate => candidate.name === method)
654
- if (snapshot === undefined) continue
655
- const wrapped = (...args: unknown[]): unknown => {
656
- return operations.run(
657
- { composing: true },
658
- (): unknown => Reflect.apply(snapshot.original, raw, args) as unknown,
659
- )
660
- }
661
- installMethod(snapshot, wrapped)
662
- }
663
-
664
- const registerSnapshot = snapshots.find(candidate => candidate.name === 'register')
665
- if (registerSnapshot !== undefined) {
666
- const registerWrapped = async (definition: unknown): Promise<unknown> => {
667
- injectCompressionRows(definition, options, excluded)
668
- return await Reflect.apply(registerSnapshot.original, raw, [definition]) as unknown
669
- }
670
- installMethod(registerSnapshot, registerWrapped)
671
- }
672
-
673
- let disposed = false
674
- return {
675
- async dispose(): Promise<void> {
676
- if (disposed) return
677
- disposed = true
678
- for (const snapshot of [...snapshots].reverse()) restoreMethod(snapshot)
679
- await store.dispose()
680
- },
681
- }
682
- }
683
-
684
- /** Capture callable methods and whether each was inherited or owned. */
685
- function snapshotMethods(presets: OverlayableAgentPresets): MethodSnapshot[] {
686
- const methods: MethodSnapshot[] = []
687
- for (const name of ['resolve', 'mount', 'recompose', 'standingKeyFor', 'register'] as const) {
688
- const original = presets[name]
689
- if (typeof original !== 'function') {
690
- // `resolve` 是 overlay 自身的重写器,必须有。其余生命周期方法(mount/
691
- // recompose/standingKeyFor)仅需被 AsyncLocalStorage 作用域包裹:宿主线
692
- // 缺其中一个(0.1.7-rc.2 无 `standingKeyFor`)不得让整个 overlay 失败,
693
- // 跳过它即可——否则压缩栈永远注入不了(实证:overlay:err)。
694
- if (name === 'resolve') {
695
- throw new TypeError(`context-compression selector: AgentPresets.${name} is unavailable`)
696
- }
697
- continue
698
- }
699
- // Cordis 的 traceable 代理每次读取都会重绑方法,且把**未代理的原始 target**
700
- // 暴露在 `Symbol.for('cordis.original')` 下。因此装饰代理或"原型代理"都对
701
- // target 内部的 `this.resolve(...)` 无效(实证:overlay:composition{mount} 触发、
702
- // 却无嵌套 overlay:resolve)。装饰**原始 target 自身**方能同时命中两种接收者。
703
- const home = rawService(presets)
704
- methods.push({
705
- name,
706
- home,
707
- own: Object.getOwnPropertyDescriptor(home, name),
708
- original,
709
- })
710
- }
711
- return methods
712
- }
713
-
714
- /** Return the captured method or fail loudly if the snapshot set is corrupt. */
715
- function snapshotFor(
716
- snapshots: readonly MethodSnapshot[],
717
- name: MethodSnapshot['name'],
718
- ): MethodSnapshot {
719
- const snapshot = snapshots.find(candidate => candidate.name === name)
720
- if (snapshot === undefined) {
721
- throw new Error(`context-compression selector: missing method snapshot for ${name}`)
722
- }
723
- return snapshot
724
- }
725
-
726
- /** Install one own method while retaining its identity for safe disposal. */
727
- function installMethod(
728
- snapshot: MethodSnapshot,
729
- wrapped: (...args: never[]) => unknown,
730
- ): void {
731
- snapshot.wrapped = wrapped
732
- Object.defineProperty(snapshot.home, snapshot.name, {
733
- configurable: true,
734
- writable: true,
735
- value: wrapped,
736
- })
737
- }
738
-
739
- /** Restore the captured own/prototype state after the final shared lease. */
740
- function restoreMethod(snapshot: MethodSnapshot): void {
741
- // Cordis' traceable service proxy rebinds a method on every read, so function
742
- // identity cannot prove ownership here. The shared reference count is the
743
- // ownership guard: this path runs only after the final decorator lease ends.
744
- if (snapshot.own === undefined) {
745
- Reflect.deleteProperty(snapshot.home, snapshot.name)
746
- } else {
747
- Object.defineProperty(snapshot.home, snapshot.name, snapshot.own)
748
- }
749
- }