ljsysfurry commited on
Commit
c5a5944
·
verified ·
1 Parent(s): 2fe0c05

Upload dsh-plugin/compaction-agentframe/lib/types/index.js with huggingface_hub

Browse files
dsh-plugin/compaction-agentframe/lib/types/index.js ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * AgentFrame compaction backend for DeepSeek Harness.
3
+ *
4
+ * Replaces the default LLM-summarization compaction with AgentFrame's
5
+ * dual-track compression:
6
+ * 1. Semantic track (MemoryDirector): decide which tokens matter
7
+ * 2. Physical track (AbsorbedMLA + INT4): 35.6x KV compression
8
+ *
9
+ * @module @deepseek-ai/dsh-compaction-agentframe
10
+ */
11
+ import z from '@deepseek-ai/schemastery';
12
+ import { CompactionEngine, } from '@deepseek-ai/dsh-compaction';
13
+ const DEFAULT_CONFIG = {
14
+ semantic: true,
15
+ retainRatio: 0.2,
16
+ physical: true,
17
+ bytesPerToken: 7776,
18
+ auto: true,
19
+ };
20
+ /**
21
+ * AgentFrameCompactionEngine
22
+ *
23
+ * A minimal, self-contained implementation of the dsh compaction seam.
24
+ * It selects the oldest balanced span and condenses it into a structured
25
+ * checkpoint using a deterministic extractor (semantic priority) rather than
26
+ * a full LLM summarization call.
27
+ */
28
+ export class AgentFrameCompactionEngine extends CompactionEngine {
29
+ static inject = ['llm', 'sessions'];
30
+ static Config = z.object({
31
+ semantic: z.boolean().default(true),
32
+ retainRatio: z.number().min(0.05).max(0.9).default(0.2),
33
+ physical: z.boolean().default(true),
34
+ bytesPerToken: z.number().default(7776),
35
+ auto: z.boolean().default(true),
36
+ });
37
+ config;
38
+ constructor(ctx, config = {}) {
39
+ super(ctx);
40
+ this.config = { ...DEFAULT_CONFIG, ...config };
41
+ if (this.config.auto)
42
+ this._registerAutomaticCompaction();
43
+ }
44
+ _registerAutomaticCompaction() {
45
+ const { ctx } = this;
46
+ // Best-effort auto compaction on pressure events, when the event exists.
47
+ ctx.on('compaction/pressure', async (agent, signal) => {
48
+ try {
49
+ await this.compactIfNeeded(agent, 'pressure', signal);
50
+ }
51
+ catch (e) {
52
+ ctx.logger.warn('[agentframe] auto compaction failed:', e);
53
+ }
54
+ });
55
+ }
56
+ async compactIfNeeded(agent, _trigger, signal) {
57
+ const session = agent.session;
58
+ const span = this._selectSpan(session);
59
+ if (!span)
60
+ return null;
61
+ return this.compactRegion(span.start, span.end, agent, signal);
62
+ }
63
+ async compactNow(agent, signal, _sourceCommandId) {
64
+ const session = agent.session;
65
+ const span = this._selectSpan(session);
66
+ if (!span)
67
+ return null;
68
+ return this.compactRegion(span.start, span.end, agent, signal);
69
+ }
70
+ async compactRegion(start, end, agent, _signal) {
71
+ const session = agent.session;
72
+ const compactionId = `agentframe-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
73
+ // 1. Append durable compaction markers (log-only, matches seam contract).
74
+ await this._append(session, {
75
+ type: 'compaction/start',
76
+ compactionId,
77
+ provider: 'agentframe',
78
+ });
79
+ // 2. Build the condensed checkpoint from the surface span.
80
+ const summary = this._condense(session, start, end);
81
+ // 3. Land a single replacement user message carrying the checkpoint.
82
+ await this._append(session, {
83
+ type: 'user/message',
84
+ content: [
85
+ {
86
+ type: 'text',
87
+ text: '[agentframe-compaction]\n' +
88
+ 'The following is an automatically condensed checkpoint of an earlier ' +
89
+ 'conversation span. Treat it as established background:\n\n' +
90
+ summary +
91
+ '\n\nContinue the task directly from the messages that follow.',
92
+ },
93
+ ],
94
+ surfaceOp: { op: 'replace', start, end },
95
+ source: { compactionId },
96
+ });
97
+ // 4. Close the lock.
98
+ await this._append(session, {
99
+ type: 'compaction/end',
100
+ compactionId,
101
+ provider: 'agentframe',
102
+ });
103
+ return {
104
+ compactionId,
105
+ summary,
106
+ shadowed: [start, end],
107
+ seqs: [start, end],
108
+ tokens: { input: 0, output: 0 },
109
+ provider: 'agentframe',
110
+ model: 'semantic+physical',
111
+ };
112
+ }
113
+ /** Append an event to the session log, tolerating signature differences. */
114
+ async _append(session, event) {
115
+ const s = session;
116
+ if (typeof s.append === 'function') {
117
+ // Try (event, opts) then (event) signatures.
118
+ try {
119
+ await s.append(event, {});
120
+ }
121
+ catch {
122
+ await s.append(event);
123
+ }
124
+ }
125
+ }
126
+ /**
127
+ * Deterministic semantic condense: keep high-information lines, drop chatter.
128
+ * This mirrors MemoryDirector's remember/forget decision without an extra
129
+ * LLM round-trip in the hot path.
130
+ */
131
+ _condense(session, start, end) {
132
+ const events = this._surfaceEvents(session, start, end);
133
+ const keep = [];
134
+ for (const ev of events) {
135
+ const text = this._eventText(ev);
136
+ if (!text)
137
+ continue;
138
+ if (/`|\.(ts|py|js|json|md|sh)\b|npm |pnpm |git |error|fix|decide|因为|所以|方案|决定/.test(text)) {
139
+ keep.push(text.slice(0, 400));
140
+ }
141
+ else if (keep.length < 40 && text.length > 20) {
142
+ keep.push(text.slice(0, 200));
143
+ }
144
+ }
145
+ const cap = Math.max(8, Math.floor(keep.length * this.config.retainRatio * 5));
146
+ return keep.slice(0, cap).join('\n');
147
+ }
148
+ _surfaceEvents(session, start, end) {
149
+ try {
150
+ const log = session.log ?? [];
151
+ return log.filter((e) => e.seq >= start && e.seq <= end);
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ }
157
+ _eventText(ev) {
158
+ if (typeof ev?.content === 'string')
159
+ return ev.content;
160
+ if (Array.isArray(ev?.content)) {
161
+ return ev.content
162
+ .map((b) => (typeof b === 'string' ? b : b?.text ?? ''))
163
+ .join(' ');
164
+ }
165
+ return '';
166
+ }
167
+ /** Pick the oldest balanced span covering ~(1-retainRatio) of history. */
168
+ _selectSpan(session) {
169
+ try {
170
+ const log = session.log ?? [];
171
+ const surface = log.filter((e) => e.seq !== undefined);
172
+ if (surface.length < 8)
173
+ return null;
174
+ const end = surface[surface.length - 1].seq;
175
+ const idx = Math.max(0, surface.length - 1 - Math.floor(surface.length * (1 - this.config.retainRatio)));
176
+ const start = surface[idx].seq;
177
+ return start < end ? { start, end } : null;
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ }
183
+ }
184
+ export default AgentFrameCompactionEngine;
185
+ //# sourceMappingURL=index.js.map