dsh-compact-saviour 0.2.6

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 (100) hide show
  1. package/ACCEPTANCE.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -0
  4. package/THIRD_PARTY_NOTICES.md +50 -0
  5. package/cordis.patch.yml +3 -0
  6. package/cordis.yml +2 -0
  7. package/docs/development.md +28 -0
  8. package/dshx.yml +16 -0
  9. package/lib/client.js +5933 -0
  10. package/lib/client.js.map +1 -0
  11. package/lib/dsh-compact-saviour.js +1206 -0
  12. package/lib/types/client/context-elements.d.ts +6 -0
  13. package/lib/types/client/context-elements.d.ts.map +1 -0
  14. package/lib/types/client/context-elements.js +41 -0
  15. package/lib/types/client/context-elements.js.map +1 -0
  16. package/lib/types/client/index.d.ts +10 -0
  17. package/lib/types/client/index.d.ts.map +1 -0
  18. package/lib/types/client/index.js +217 -0
  19. package/lib/types/client/index.js.map +1 -0
  20. package/lib/types/client/meter-bridge.d.ts +12 -0
  21. package/lib/types/client/meter-bridge.d.ts.map +1 -0
  22. package/lib/types/client/meter-bridge.js +89 -0
  23. package/lib/types/client/meter-bridge.js.map +1 -0
  24. package/lib/types/client/ring-control.d.ts +32 -0
  25. package/lib/types/client/ring-control.d.ts.map +1 -0
  26. package/lib/types/client/ring-control.js +191 -0
  27. package/lib/types/client/ring-control.js.map +1 -0
  28. package/lib/types/client/satellite.d.ts +32 -0
  29. package/lib/types/client/satellite.d.ts.map +1 -0
  30. package/lib/types/client/satellite.js +163 -0
  31. package/lib/types/client/satellite.js.map +1 -0
  32. package/lib/types/client/waiting-copy.d.ts +10 -0
  33. package/lib/types/client/waiting-copy.d.ts.map +1 -0
  34. package/lib/types/client/waiting-copy.js +31 -0
  35. package/lib/types/client/waiting-copy.js.map +1 -0
  36. package/lib/types/compress.d.ts +31 -0
  37. package/lib/types/compress.d.ts.map +1 -0
  38. package/lib/types/compress.js +265 -0
  39. package/lib/types/compress.js.map +1 -0
  40. package/lib/types/controller.d.ts +31 -0
  41. package/lib/types/controller.d.ts.map +1 -0
  42. package/lib/types/controller.js +323 -0
  43. package/lib/types/controller.js.map +1 -0
  44. package/lib/types/dsh-compact-saviour.d.ts +10 -0
  45. package/lib/types/dsh-compact-saviour.d.ts.map +1 -0
  46. package/lib/types/dsh-compact-saviour.js +104 -0
  47. package/lib/types/dsh-compact-saviour.js.map +1 -0
  48. package/lib/types/message-source.d.ts +9 -0
  49. package/lib/types/message-source.d.ts.map +1 -0
  50. package/lib/types/message-source.js +2 -0
  51. package/lib/types/message-source.js.map +1 -0
  52. package/lib/types/pressure.d.ts +17 -0
  53. package/lib/types/pressure.d.ts.map +1 -0
  54. package/lib/types/pressure.js +71 -0
  55. package/lib/types/pressure.js.map +1 -0
  56. package/lib/types/shared.d.ts +42 -0
  57. package/lib/types/shared.d.ts.map +1 -0
  58. package/lib/types/shared.js +2 -0
  59. package/lib/types/shared.js.map +1 -0
  60. package/lib/types/summary-types.d.ts +20 -0
  61. package/lib/types/summary-types.d.ts.map +1 -0
  62. package/lib/types/summary-types.js +7 -0
  63. package/lib/types/summary-types.js.map +1 -0
  64. package/lib/types/vendor/region.d.ts +65 -0
  65. package/lib/types/vendor/region.d.ts.map +1 -0
  66. package/lib/types/vendor/region.js +412 -0
  67. package/lib/types/vendor/region.js.map +1 -0
  68. package/package.json +101 -0
  69. package/scripts/link-harness-dependencies.mjs +41 -0
  70. package/scripts/normalize-artifacts.mjs +7 -0
  71. package/src/client/assets.d.ts +1 -0
  72. package/src/client/context-elements.ts +39 -0
  73. package/src/client/index.tsx +214 -0
  74. package/src/client/meter-bridge.ts +65 -0
  75. package/src/client/ring-control.ts +134 -0
  76. package/src/client/satellite.ts +121 -0
  77. package/src/client/style.css +54 -0
  78. package/src/client/vendor/LICENSE +21 -0
  79. package/src/client/vendor/open-bot-motion.cjs +1673 -0
  80. package/src/client/vendor/open-bot-motion.d.cts +9 -0
  81. package/src/client/waiting-copy.tsx +29 -0
  82. package/src/compress.ts +210 -0
  83. package/src/controller.ts +248 -0
  84. package/src/dsh-compact-saviour.ts +82 -0
  85. package/src/message-source.ts +4 -0
  86. package/src/pressure.ts +69 -0
  87. package/src/shared.ts +13 -0
  88. package/src/summary-types.ts +11 -0
  89. package/src/vendor/region.ts +583 -0
  90. package/tests/compression.test.ts +130 -0
  91. package/tests/controller.test.ts +279 -0
  92. package/tests/interaction-fixture.tsx +38 -0
  93. package/tests/interaction.browser.mjs +201 -0
  94. package/tests/meter-bridge.browser.mjs +83 -0
  95. package/tests/motion.test.ts +26 -0
  96. package/tests/peer-range.test.ts +23 -0
  97. package/tests/pressure.test.ts +11 -0
  98. package/tests/transactions.test.ts +56 -0
  99. package/tsconfig.json +10 -0
  100. package/tsdown.config.ts +13 -0
@@ -0,0 +1,412 @@
1
+ // Adapted from deepseek-ai/deepseek-harness v0.1.5-rc.2 (MIT). See THIRD_PARTY_NOTICES.md.
2
+ /**
3
+ * Surface retention selection and the shared log-recorded compaction
4
+ * transaction for automatic open-turn and manual idle-session compaction.
5
+ *
6
+ * @module @deepseek-ai/dsh-compaction-basic/region
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { isDeepStrictEqual } from 'node:util';
10
+ import { CompactionId, ManualCompactionError, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore, } from '@deepseek-ai/dsh-compaction';
11
+ import { createUserMessage, errorChain } from '@deepseek-ai/dsh-llm';
12
+ import { SessionSeq } from '@deepseek-ai/dsh-session';
13
+ import { frameSummary } from '../summary-types.js';
14
+ /**
15
+ * Rejects a summary whose replacement boundaries are no longer the ones it was
16
+ * built from, distinguished from summarizer and shrink failures so a manual
17
+ * caller can report the two causes differently.
18
+ */
19
+ class SurfaceChangedError extends Error {
20
+ }
21
+ /**
22
+ * The `system/message` holding surface node 0, or `undefined` when another
23
+ * message-producing event starts the surface.
24
+ * @param session - session supplying the log behind the current surface.
25
+ * @param headSeq - seq at surface node 0 of a non-empty surface.
26
+ * @returns the system head event, or `undefined` without one.
27
+ */
28
+ function systemHead(session, headSeq) {
29
+ // Surface nodes are current log seqs, so the event exists.
30
+ // oxlint-disable-next-line typescript/no-non-null-assertion
31
+ const head = session.eventAt(headSeq);
32
+ return head.type === 'system/message' ? head : undefined;
33
+ }
34
+ /**
35
+ * Resolve the next range starting at the first non-system surface node while
36
+ * retaining a priced recent tail and never splitting an assistant
37
+ * tool-call/result pair. A `system/message` at surface node 0 is never inside
38
+ * the range; without one the range starts at node 0.
39
+ * @param session - session supplying authoritative current surface positions.
40
+ * @param measurement - unified pressure and surface measurement from the conversation meter.
41
+ * @param retainTokens - minimum recent tail budget retained verbatim.
42
+ * @returns the inclusive positional seq range to compact, or `null`.
43
+ */
44
+ export function selectCompactableRange(session, measurement, retainTokens) {
45
+ const pricedNodes = measurement.nodes;
46
+ if (pricedNodes.length === 0)
47
+ return null;
48
+ const surfaceNodes = session.surface.nodes;
49
+ if (surfaceNodes.length !== pricedNodes.length
50
+ || surfaceNodes.some((seq, index) => seq !== pricedNodes[index]?.seq)) {
51
+ throw new Error('compaction: token-meter surface does not match the current session surface');
52
+ }
53
+ // oxlint-disable-next-line typescript/no-non-null-assertion
54
+ const firstIdx = systemHead(session, surfaceNodes[0]) === undefined ? 0 : 1;
55
+ let accumulated = 0;
56
+ let keepFromIdx = pricedNodes.length;
57
+ for (let index = pricedNodes.length - 1; index >= 0; index -= 1) {
58
+ // oxlint-disable-next-line typescript/no-non-null-assertion
59
+ accumulated += pricedNodes[index].tokens;
60
+ keepFromIdx = index;
61
+ if (accumulated >= retainTokens)
62
+ break;
63
+ }
64
+ if (keepFromIdx <= firstIdx)
65
+ return null;
66
+ while (keepFromIdx > firstIdx) {
67
+ // oxlint-disable-next-line typescript/no-non-null-assertion
68
+ if (toolPairingBalancedBefore(session, surfaceNodes[keepFromIdx]))
69
+ break;
70
+ keepFromIdx -= 1;
71
+ }
72
+ if (keepFromIdx <= firstIdx)
73
+ return null;
74
+ // oxlint-disable-next-line typescript/no-non-null-assertion
75
+ const first = surfaceNodes[firstIdx];
76
+ // oxlint-disable-next-line typescript/no-non-null-assertion
77
+ const cutoff = surfaceNodes[keepFromIdx - 1];
78
+ return { start: first, end: cutoff };
79
+ }
80
+ /**
81
+ * Run the single compaction transaction over one selected positional span.
82
+ * Selection and validation are read-only. Idle/log validation and
83
+ * `compaction/start` are synchronously adjacent, so the durable opening marker is
84
+ * the compaction lock before summarization yields. Every later failure makes
85
+ * exactly one `compaction/end` attempt; a failed close deliberately leaves the
86
+ * unmatched start detectable.
87
+ * @param dependencies - conversation meter and dynamically dispatched summarizer hook.
88
+ * @param session - session whose surface is mutated.
89
+ * @param start - inclusive first surface-node seq.
90
+ * @param end - inclusive last surface-node seq.
91
+ * @param agent - agent used by the summarizer.
92
+ * @param options - bracket owner, stability rule, and optional durability checkpoint.
93
+ * @param signal - optional summarization cancellation signal.
94
+ * @returns the successful durable compaction result.
95
+ */
96
+ export async function compactSurfaceRegion(dependencies, session, start, end, agent, options, signal) {
97
+ if (options.owner === null)
98
+ signal?.throwIfAborted();
99
+ const selection = validateSurfaceRegion(session, start, end);
100
+ const entryState = inspectCompactionEntryState(session);
101
+ assertCompactionInactive(entryState.unmatchedCompactionStart, entryState.latestEndSeedSeq, 'compaction');
102
+ let owner;
103
+ if (options.owner === null) {
104
+ if (entryState.openTurn !== null) {
105
+ throw new ManualCompactionError('busy', 'manual compaction: the session already has an open turn');
106
+ }
107
+ owner = null;
108
+ }
109
+ else {
110
+ if (entryState.openTurn === null) {
111
+ throw new Error('compactRegion: no open turn — automatic compaction events must be enclosed in a turn');
112
+ }
113
+ owner = entryState.openTurn;
114
+ }
115
+ const compactionId = CompactionId(randomUUID());
116
+ const lifecycle = {
117
+ compactionId,
118
+ ...options.sourceCommandId === undefined ? {} : { sourceCommandId: options.sourceCommandId },
119
+ turn: owner,
120
+ };
121
+ const startEvent = session.append('compaction/start', lifecycle);
122
+ const assertStable = options.stability === 'whole-surface'
123
+ ? assertWholeSurfaceUnchanged
124
+ : assertSelectedSpanStable;
125
+ let failure;
126
+ let flushFailure;
127
+ let result;
128
+ let closed = false;
129
+ let closing = false;
130
+ let stage = 'summary';
131
+ try {
132
+ const prepared = prepareCompaction(dependencies, session, selection);
133
+ const summarized = await summarizeCompaction(dependencies, prepared, agent, compactionId, options.sourceCommandId, signal);
134
+ if (options.owner === null)
135
+ signal?.throwIfAborted();
136
+ assertStable(dependencies, session, summarized);
137
+ stage = 'commit';
138
+ const pending = commitCompactionBody(session, startEvent, summarized);
139
+ closing = true;
140
+ const endEvent = session.append('compaction/end', lifecycle);
141
+ closed = true;
142
+ result = completeCompaction(pending, endEvent);
143
+ }
144
+ catch (error) {
145
+ failure = { error, stage: closing ? 'commit' : stage };
146
+ if (!closing) {
147
+ closing = true;
148
+ try {
149
+ session.append('compaction/end', { ...lifecycle, error: errorChain(error) });
150
+ closed = true;
151
+ }
152
+ catch (closeError) {
153
+ failure = { error: closeError, stage: 'commit' };
154
+ }
155
+ }
156
+ }
157
+ if (closed && options.flush !== undefined) {
158
+ try {
159
+ await options.flush();
160
+ }
161
+ catch (error) {
162
+ flushFailure = error;
163
+ }
164
+ }
165
+ if (options.owner === null)
166
+ signal?.throwIfAborted();
167
+ if (failure !== undefined) {
168
+ if (options.owner === null)
169
+ throwManualFailure(failure);
170
+ throw failure.error;
171
+ }
172
+ if (flushFailure !== undefined) {
173
+ throw new ManualCompactionError('persistence', 'manual compaction durability checkpoint failed', { cause: flushFailure });
174
+ }
175
+ /* v8 ignore next -- every path without a result records and throws a failure above. */
176
+ if (result === undefined)
177
+ throw new Error('compaction committed without a result');
178
+ return result;
179
+ }
180
+ /** Classify one closed manual attempt without weakening cancellation precedence. */
181
+ function throwManualFailure(failure) {
182
+ if (failure.stage === 'commit') {
183
+ throw new ManualCompactionError('commit', 'manual compaction did not commit cleanly', { cause: failure.error });
184
+ }
185
+ if (failure.error instanceof SurfaceChangedError) {
186
+ throw new ManualCompactionError('changed', 'the compacted history changed during manual compaction', { cause: failure.error });
187
+ }
188
+ throw new ManualCompactionError('summary', 'manual compaction could not produce a smaller summary', { cause: failure.error });
189
+ }
190
+ /**
191
+ * Reject a durable unmatched compaction marker unless a later constructor-seed
192
+ * boundary proves that its owner belongs to an earlier session lifecycle.
193
+ * @param unmatchedCompactionStart - latest unmatched opening marker, if any.
194
+ * @param latestEndSeedSeq - newest constructor-seed boundary, if any.
195
+ * @param stage - operation label included in the busy diagnostic.
196
+ */
197
+ function assertCompactionInactive(unmatchedCompactionStart, latestEndSeedSeq, stage) {
198
+ if (unmatchedCompactionStart === undefined
199
+ || (latestEndSeedSeq !== undefined
200
+ && latestEndSeedSeq > unmatchedCompactionStart.seq))
201
+ return;
202
+ throw new ManualCompactionError('busy', `${stage}: compaction already in progress; the session compaction lock is already active`);
203
+ }
204
+ /**
205
+ * Recheck the durable compaction lock after an asynchronous policy decision.
206
+ * @param session - session whose latest marker state is inspected.
207
+ * @param stage - operation label included in the busy diagnostic.
208
+ */
209
+ export function assertNoActiveCompaction(session, stage) {
210
+ const entryState = inspectCompactionEntryState(session);
211
+ assertCompactionInactive(entryState.unmatchedCompactionStart, entryState.latestEndSeedSeq, stage);
212
+ }
213
+ /** Validate one requested surface-position span before asynchronous work begins. */
214
+ function validateSurfaceRegion(session, start, end) {
215
+ const nodes = session.surface.nodes;
216
+ const startIdx = nodes.indexOf(start);
217
+ const endIdx = nodes.indexOf(end);
218
+ if (startIdx === -1)
219
+ throw new Error(`compactRegion: start seq ${start} not found in surface`);
220
+ if (endIdx === -1)
221
+ throw new Error(`compactRegion: end seq ${end} not found in surface`);
222
+ if (startIdx > endIdx) {
223
+ throw new Error(`compactRegion: start seq ${start} (position ${startIdx}) is after end seq ${end} (position ${endIdx}) on the surface`);
224
+ }
225
+ // oxlint-disable-next-line typescript/no-non-null-assertion
226
+ if (!toolPairingBalancedBefore(session, nodes[startIdx])) {
227
+ throw new Error(`compactRegion: start seq ${start} is not a balanced boundary (would split a step's tool-call/result pair)`);
228
+ }
229
+ // oxlint-disable-next-line typescript/no-non-null-assertion
230
+ if (!toolPairingBalancedAfter(session, nodes[endIdx])) {
231
+ throw new Error(`compactRegion: end seq ${end} is not a balanced boundary (would split a step, or the step is still open)`);
232
+ }
233
+ return { start, end, startIdx, endIdx, shadowedSeqs: nodes.slice(startIdx, endIdx + 1) };
234
+ }
235
+ /** Snapshot pricing and replay input for a validated surface range. */
236
+ function prepareCompaction(dependencies, session, selection) {
237
+ const measurement = dependencies.meter.measure(session);
238
+ const selectedNodes = measurement.nodes.slice(selection.startIdx, selection.endIdx + 1);
239
+ if (selectedNodes.length !== selection.shadowedSeqs.length
240
+ || selectedNodes.some((node, index) => node.seq !== selection.shadowedSeqs[index])) {
241
+ throw new SurfaceChangedError('compaction: selected surface changed before summarization began');
242
+ }
243
+ return {
244
+ ...selection,
245
+ measurement,
246
+ selectedNodes,
247
+ // The shadow-price protocol prices replacements with the fixed heuristic
248
+ // so the O(1) projection fold stays in agreement with its own appends;
249
+ // retention, range selection, and the shrink comparison read the
250
+ // route-priced `tokens` instead.
251
+ shadowedTokenCount: selectedNodes.reduce((total, node) => total + node.heuristicTokens, 0),
252
+ shadowedRouteTokenCount: selectedNodes.reduce((total, node) => total + node.tokens, 0),
253
+ input: buildSummarizationInput(session, selection.shadowedSeqs),
254
+ };
255
+ }
256
+ /** Run the summarizer and frame its replacement checkpoint. */
257
+ async function summarizeCompaction(dependencies, prepared, agent, compactionId, sourceCommandId, signal) {
258
+ const summaryResult = await dependencies.summarize(prepared.input, agent, signal);
259
+ const checkpointMessage = createUserMessage({
260
+ content: frameSummary(summaryResult.summary),
261
+ source: compactCheckpointSource(compactionId, sourceCommandId),
262
+ });
263
+ // The checkpoint is text-only, so its fixed-heuristic price IS its route
264
+ // price; comparing it against the span's route price asks the real
265
+ // question — does the replacement lower the next request's pressure.
266
+ const framedSummaryTokenCount = dependencies.meter.estimateMessage(checkpointMessage);
267
+ if (framedSummaryTokenCount >= prepared.shadowedRouteTokenCount) {
268
+ throw new Error(`summary is not smaller than the shadowed content (${framedSummaryTokenCount} estimated framed tokens >= ${prepared.shadowedRouteTokenCount})`);
269
+ }
270
+ return {
271
+ ...prepared,
272
+ ...summaryResult,
273
+ checkpointMessage,
274
+ };
275
+ }
276
+ /** Reject a summary prepared against any earlier surface generation. */
277
+ function assertWholeSurfaceUnchanged(dependencies, session, prepared) {
278
+ const current = dependencies.meter.measure(session);
279
+ if (!isDeepStrictEqual(current.nodes, prepared.measurement.nodes)) {
280
+ throw new SurfaceChangedError('compaction: session surface changed during summarization');
281
+ }
282
+ }
283
+ /**
284
+ * Require only that the selected span remain the same present, contiguous,
285
+ * equally priced, balanced replacement target. Nodes added outside it remain
286
+ * visible and do not invalidate the summary.
287
+ */
288
+ function assertSelectedSpanStable(dependencies, session, prepared) {
289
+ let current;
290
+ try {
291
+ current = validateSurfaceRegion(session, prepared.start, prepared.end);
292
+ }
293
+ catch (error) {
294
+ throw new SurfaceChangedError('compaction: the selected span is no longer a valid replacement target', { cause: error });
295
+ }
296
+ if (!isDeepStrictEqual([...current.shadowedSeqs], [...prepared.shadowedSeqs])) {
297
+ throw new SurfaceChangedError('compaction: the selected span changed during summarization');
298
+ }
299
+ const measured = dependencies.meter.measure(session).nodes.slice(current.startIdx, current.endIdx + 1);
300
+ if (!isDeepStrictEqual(measured, prepared.selectedNodes)) {
301
+ throw new SurfaceChangedError('compaction: the selected span was rewritten during summarization');
302
+ }
303
+ }
304
+ /** Append one completed summary record and replacement body without yielding. */
305
+ function commitCompactionBody(session, startEvent, summarized) {
306
+ const { start, end, shadowedSeqs, shadowedTokenCount, summary, provider, model, maxTokens, usage, checkpointMessage, } = summarized;
307
+ const callProvenance = summarized.llmStreamCall === true
308
+ ? { rawOutput: summarized.rawOutput, llmStreamCall: true }
309
+ : summarized.rawOutput === undefined ? {} : { rawOutput: summarized.rawOutput };
310
+ const summaryEvent = session.append('compaction/summary', {
311
+ compactionId: startEvent.data.compactionId,
312
+ ...startEvent.data.sourceCommandId === undefined
313
+ ? {}
314
+ : { sourceCommandId: startEvent.data.sourceCommandId },
315
+ summary,
316
+ ...callProvenance,
317
+ shadowedRange: { start, end },
318
+ shadowedSeqs: [...shadowedSeqs],
319
+ shadowedTokenCount,
320
+ provider,
321
+ model,
322
+ ...maxTokens === undefined ? {} : { maxTokens },
323
+ ...usage === undefined ? {} : { usage },
324
+ });
325
+ session.append('user/message', checkpointMessage, {
326
+ surfaceOp: { op: 'replace', startSeq: start, endSeq: end },
327
+ sourceEventSeqs: [startEvent.seq, summaryEvent.seq, ...shadowedSeqs],
328
+ });
329
+ return {
330
+ compactionId: startEvent.data.compactionId,
331
+ ...startEvent.data.sourceCommandId === undefined
332
+ ? {}
333
+ : { sourceCommandId: startEvent.data.sourceCommandId },
334
+ startSeq: startEvent.seq,
335
+ summarySeq: summaryEvent.seq,
336
+ summary,
337
+ shadowedRange: { start, end },
338
+ shadowedSeqs: [...shadowedSeqs],
339
+ shadowedTokenCount,
340
+ };
341
+ }
342
+ /** Attach the successfully appended close event to a pending result. */
343
+ function completeCompaction(pending, endEvent) {
344
+ return { ...pending, endSeq: endEvent.seq };
345
+ }
346
+ /**
347
+ * Reconstruct the last routed request's cacheable prefix for the shadowed
348
+ * region: the system prompt held by the `system/message` at surface node 0,
349
+ * the header's tool schemas, then the region's own derived messages in surface
350
+ * order. The summarizer appends only the compaction instruction after this, so
351
+ * the call is a genuine prefix of the conversation and reuses the provider's
352
+ * KV cache. A surface without a system head, or whose head projects to no
353
+ * message, contributes no leading system message.
354
+ * @param session - session supplying the surface head, request header, and per-node projection.
355
+ * @param shadowedSeqs - the surface-node seqs, in order, being compacted.
356
+ * @returns the replayed conversation prefix to condense.
357
+ */
358
+ function buildSummarizationInput(session, shadowedSeqs) {
359
+ const header = session.requestHeader();
360
+ // shadowedSeqs are current surface seqs, so the surface has a node 0.
361
+ // oxlint-disable-next-line typescript/no-non-null-assertion
362
+ const head = systemHead(session, session.surface.nodes[0]);
363
+ const system = head === undefined ? null : session.deriveEventMessage(head);
364
+ const regionMessages = shadowedSeqs
365
+ // shadowedSeqs are current surface seqs, so each is a valid log index.
366
+ // oxlint-disable-next-line typescript/no-non-null-assertion
367
+ .map(seq => session.deriveEventMessage(session.eventAt(seq)))
368
+ .filter((message) => message !== null);
369
+ return {
370
+ ...header?.tools === undefined ? {} : { tools: header.tools },
371
+ messages: system === null ? regionMessages : [system, ...regionMessages],
372
+ };
373
+ }
374
+ /** Inspect open-turn, unmatched-compaction, and latest seed-boundary state independently. */
375
+ function inspectCompactionEntryState(session) {
376
+ let openTurn = null;
377
+ let openTurnStateKnown = false;
378
+ let unmatchedCompactionStart;
379
+ let compactionEntryStateKnown = false;
380
+ let latestEndSeedSeq;
381
+ for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
382
+ // oxlint-disable-next-line typescript/no-non-null-assertion
383
+ const event = session.eventAt(SessionSeq(seq));
384
+ if (latestEndSeedSeq === undefined && event.type === 'session/end-seed') {
385
+ latestEndSeedSeq = event.seq;
386
+ }
387
+ if (!compactionEntryStateKnown) {
388
+ if (event.type === 'compaction/start') {
389
+ unmatchedCompactionStart = event;
390
+ compactionEntryStateKnown = true;
391
+ }
392
+ else if (event.type === 'compaction/end') {
393
+ compactionEntryStateKnown = true;
394
+ }
395
+ }
396
+ if (!openTurnStateKnown) {
397
+ if (event.type === 'turn/start') {
398
+ openTurn = event.data.turn;
399
+ openTurnStateKnown = true;
400
+ }
401
+ else if (event.type === 'turn/end') {
402
+ openTurnStateKnown = true;
403
+ }
404
+ }
405
+ if (openTurnStateKnown
406
+ && compactionEntryStateKnown
407
+ && latestEndSeedSeq !== undefined)
408
+ break;
409
+ }
410
+ return { openTurn, unmatchedCompactionStart, latestEndSeedSeq };
411
+ }
412
+ //# sourceMappingURL=region.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"region.js","sourceRoot":"","sources":["../../../src/vendor/region.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F;;;;;GAKG;AAEH,OAAO,E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AA;YAClC,CAAC;QACH,CAAC;QACD,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACxB,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;gBAChC,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAA;gBAC1B,kBAAkB,GAAG,IAAI,CAAA;YAC3B,CAAC;iBAAM,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;gBACrC,kBAAkB,GAAG,IAAI,CAAA;YAC3B,CAAC;QACH,CAAC;QACD,IAAI,kBAAkB;eACjB,yBAAyB;eACzB,gBAAgB,KAAK,SAAS;YAAE,MAAK;IAC5C,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,CAAA;AACjE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,101 @@
1
+ {
2
+ "name": "dsh-compact-saviour",
3
+ "version": "0.2.6",
4
+ "description": "Dedicated-model compaction rescue and manual compaction in the native context popup",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "lib/dsh-compact-saviour.js",
8
+ "types": "lib/types/dsh-compact-saviour.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/types/dsh-compact-saviour.d.ts",
12
+ "default": "./lib/dsh-compact-saviour.js"
13
+ },
14
+ "./client": {
15
+ "types": "./lib/types/client/index.d.ts",
16
+ "default": "./lib/client.js"
17
+ },
18
+ "./package.json": "./package.json"
19
+ },
20
+ "dsh": {
21
+ "client": {
22
+ "platform": "web",
23
+ "inject": [
24
+ "@deepseek-ai/dsh-client-ui-conversation",
25
+ "@deepseek-ai/dsh-client-ui-settings"
26
+ ]
27
+ },
28
+ "bundle": {
29
+ "patch": "./cordis.patch.yml"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json && tsdown && node scripts/normalize-artifacts.mjs",
34
+ "typecheck": "tsc -p tsconfig.json --noEmit",
35
+ "test": "node --import tsx/esm --test tests/*.test.ts",
36
+ "link:harness": "node scripts/link-harness-dependencies.mjs",
37
+ "test:browser": "node tests/meter-bridge.browser.mjs && node tests/interaction.browser.mjs"
38
+ },
39
+ "peerDependencies": {
40
+ "@deepseek-ai/cordis": "^4.0.4",
41
+ "@deepseek-ai/schemastery": "^3.18.4",
42
+ "@deepseek-ai/dsh-agent": ">=0.2.0-rc.1 <0.2.1",
43
+ "@deepseek-ai/dsh-compaction": ">=0.2.0-rc.1 <0.2.1",
44
+ "@deepseek-ai/dsh-compaction-basic": ">=0.2.0-rc.1 <0.2.1",
45
+ "@deepseek-ai/dsh-commands": ">=0.2.0-rc.1 <0.2.1",
46
+ "@deepseek-ai/dsh-llm": ">=0.2.0-rc.1 <0.2.1",
47
+ "@deepseek-ai/dsh-session": ">=0.2.0-rc.1 <0.2.1",
48
+ "@deepseek-ai/dsh-token-meter": ">=0.2.0-rc.1 <0.2.1",
49
+ "@deepseek-ai/dsh-settings": ">=0.2.0-rc.1 <0.2.1",
50
+ "@deepseek-ai/dsh-scope": ">=0.2.0-rc.1 <0.2.1",
51
+ "@deepseek-ai/dsh-client-ui-conversation": ">=0.2.0-rc.1 <0.2.1",
52
+ "@deepseek-ai/dsh-client-ui-settings": ">=0.2.0-rc.1 <0.2.1",
53
+ "@deepseek-ai/dsh-client-ui-slots": ">=0.2.0-rc.1 <0.2.1",
54
+ "@deepseek-ai/dsh-api-session-controller": ">=0.2.0-rc.1 <0.2.1",
55
+ "react": "^18.2.0",
56
+ "react-dom": "^18.2.0",
57
+ "@deepseek-ai/dsh-client-connection": ">=0.2.0-rc.1 <0.2.1",
58
+ "@deepseek-ai/dsh-host-webserver": ">=0.2.0-rc.1 <0.2.1",
59
+ "@deepseek-ai/dsh-session-projection": ">=0.2.0-rc.1 <0.2.1",
60
+ "@deepseek-ai/dsh-client-ui-renderer": ">=0.2.0-rc.1 <0.2.1"
61
+ },
62
+ "devDependencies": {
63
+ "@types/node": "^22.20.0",
64
+ "@types/react": "~18.3.1",
65
+ "@types/react-dom": "^18.3.0",
66
+ "typescript": "^6.0.3",
67
+ "tsx": "^4.22.4",
68
+ "tsdown": "^0.22.2",
69
+ "@deepseek-ai/dsh-agent-loop-testkit": "0.2.0-rc.2",
70
+ "@deepseek-ai/dsh-agent-loop": "0.2.0-rc.2",
71
+ "semver": "7.8.5",
72
+ "@deepseek-ai/cordis-plugin-loader": "*"
73
+ },
74
+ "files": [
75
+ "lib",
76
+ "src",
77
+ "scripts",
78
+ "tests",
79
+ "cordis.yml",
80
+ "dshx.yml",
81
+ "tsconfig.json",
82
+ "tsdown.config.ts",
83
+ "README.md",
84
+ "ACCEPTANCE.md",
85
+ "THIRD_PARTY_NOTICES.md",
86
+ "cordis.patch.yml",
87
+ "LICENSE",
88
+ "docs"
89
+ ],
90
+ "engines": {
91
+ "node": ">=24.0.0"
92
+ },
93
+ "repository": {
94
+ "type": "git",
95
+ "url": "git+https://github.com/aa2246740/dsh-compact-saviour.git"
96
+ },
97
+ "homepage": "https://github.com/aa2246740/dsh-compact-saviour#readme",
98
+ "bugs": {
99
+ "url": "https://github.com/aa2246740/dsh-compact-saviour/issues"
100
+ }
101
+ }
@@ -0,0 +1,41 @@
1
+ import { existsSync, mkdirSync, symlinkSync, realpathSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ const root = resolve(process.argv[2] || '');
5
+ if (!process.argv[2] || !existsSync(join(root, 'tools/dshx/src/client-build.js'))) throw new Error('Pass a prepared Harness checkout.');
6
+ const packages = new Map();
7
+ function walk(path, depth = 0) {
8
+ if (depth > 4) return;
9
+ if (existsSync(join(path, 'package.json'))) {
10
+ const pkg = JSON.parse(readFileSync(join(path, 'package.json'), 'utf8'));
11
+ packages.set(pkg.name, path); return;
12
+ }
13
+ for (const e of readdirSync(path, { withFileTypes: true })) if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') walk(join(path, e.name), depth + 1);
14
+ }
15
+ walk(join(root, 'packages')); walk(join(root, 'vendor'));
16
+ const local = resolve('node_modules');
17
+ function link(name, target) {
18
+ const destination = join(local, name);
19
+ mkdirSync(dirname(destination), { recursive: true });
20
+ if (existsSync(destination)) {
21
+ if (realpathSync(destination) !== realpathSync(target)) throw new Error(`Dependency mismatch: ${name}`);
22
+ } else symlinkSync(target, destination);
23
+ }
24
+ const rootRequire = createRequire(join(root, 'package.json'));
25
+ const uiRequire = createRequire(join(root, 'packages/client/ui-conversation/package.json'));
26
+ const webRequire = createRequire(join(root, 'packages/client/web/package.json'));
27
+ const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
28
+ for (const name of Object.keys({ ...pkg.peerDependencies, ...pkg.devDependencies })) {
29
+ let target = packages.get(name);
30
+ if (!target) for (const req of [rootRequire, uiRequire, webRequire]) {
31
+ try { target = dirname(req.resolve(`${name}/package.json`)); break; } catch {}
32
+ }
33
+ if (!target) throw new Error(`Cannot resolve ${name} in selected Harness`);
34
+ link(name, target);
35
+ }
36
+ mkdirSync(join(local, '.bin'), { recursive: true });
37
+ for (const name of ['typescript', 'tsdown']) {
38
+ const bins = JSON.parse(readFileSync(join(local, name, 'package.json'), 'utf8')).bin;
39
+ for (const [command, path] of Object.entries(bins)) if (!existsSync(join(local, '.bin', command))) symlinkSync(join(local, name, path), join(local, '.bin', command));
40
+ }
41
+ console.log('Development dependencies linked; Harness files unchanged.');
@@ -0,0 +1,7 @@
1
+ // Strip only the bundler's machine-local CSS region annotation. Runtime code
2
+ // and source-map line positions are unchanged; official Harness stays read-only.
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ const file = new URL('../lib/client.js', import.meta.url);
5
+ const before = await readFile(file, 'utf8');
6
+ const after = before.replace(/^(\s*\/\/#region \\0dshx-css-global:).*\/src\/(.*)$/gm, '$1src/$2');
7
+ if (after !== before) await writeFile(file, after);
@@ -0,0 +1 @@
1
+ declare module '*.css';
@@ -0,0 +1,39 @@
1
+ /** Keep the compatibility bridge local to its composer. RC2 places the meter
2
+ * in the dock outside the card and portals its popup directly to body. */
3
+ export function contextRoot(anchor: HTMLElement): HTMLElement | undefined {
4
+ return anchor.closest<HTMLElement>('[data-composer-card]')?.parentElement
5
+ ?? anchor.closest<HTMLElement>('[data-slot="conversation.input.right"]')?.parentElement
6
+ ?? undefined;
7
+ }
8
+
9
+ export function contextRing(root: HTMLElement): HTMLButtonElement | undefined {
10
+ const matches = [...root.querySelectorAll<HTMLButtonElement>('button[aria-haspopup="dialog"]')]
11
+ .filter(button => button.querySelector('svg[viewBox="0 0 14 14"]')?.querySelectorAll('circle').length === 2);
12
+ return matches.length === 1 ? matches[0] : undefined;
13
+ }
14
+
15
+ function isContextPanel(panel: HTMLElement): boolean {
16
+ const header = panel.firstElementChild;
17
+ return panel.getAttribute('role') === 'dialog' && header?.children.length === 4
18
+ && /^\d+%$/.test(header.children[1]?.textContent ?? '')
19
+ && (header.children[3]?.textContent ?? '').includes('/')
20
+ && Boolean(header.nextElementSibling);
21
+ }
22
+
23
+ export function contextPanel(ring?: HTMLButtonElement): HTMLElement | undefined {
24
+ if (!ring || ring.getAttribute('aria-expanded') !== 'true') return;
25
+ const controlled = ring.getAttribute('aria-controls');
26
+ const linked = controlled ? ring.ownerDocument.getElementById(controlled) : null;
27
+ if (linked && isContextPanel(linked)) return linked;
28
+ const local = ring.parentElement?.querySelector<HTMLElement>('[role="dialog"]');
29
+ if (local && isContextPanel(local)) return local;
30
+ // Upstream provides no aria-controls on the portalled popup. Only attach
31
+ // when both the open meter and matching body portal are unambiguous; never
32
+ // steal another conversation's popup or a model/settings dialog.
33
+ const doc = ring.ownerDocument;
34
+ const openRings = [...doc.querySelectorAll<HTMLButtonElement>('button[aria-haspopup="dialog"][aria-expanded="true"]')]
35
+ .filter(button => button.querySelector('svg[viewBox="0 0 14 14"]')?.querySelectorAll('circle').length === 2);
36
+ if (openRings.length !== 1 || openRings[0] !== ring) return;
37
+ const panels = [...doc.body.children].filter((element): element is HTMLElement => element instanceof HTMLElement && isContextPanel(element));
38
+ return panels.length === 1 ? panels[0] : undefined;
39
+ }