dsh-super-code 0.3.4 → 0.3.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 (43) hide show
  1. package/README.md +20 -8
  2. package/client/index.js +251 -20
  3. package/cordis.patch.yml +2 -2
  4. package/docs/Changelog.md +9 -0
  5. package/docs/Compatibility.md +86 -0
  6. package/docs/UsageGuide.md +51 -0
  7. package/lib/dsh/budget-settings.d.ts +51 -0
  8. package/lib/dsh/budget-settings.d.ts.map +1 -0
  9. package/lib/dsh/budget-settings.js +188 -0
  10. package/lib/dsh/budget-settings.js.map +1 -0
  11. package/lib/dsh/budgets.d.ts +34 -0
  12. package/lib/dsh/budgets.d.ts.map +1 -0
  13. package/lib/dsh/budgets.js +65 -0
  14. package/lib/dsh/budgets.js.map +1 -0
  15. package/lib/dsh/compaction.d.ts +40 -0
  16. package/lib/dsh/compaction.d.ts.map +1 -0
  17. package/lib/dsh/compaction.js +146 -0
  18. package/lib/dsh/compaction.js.map +1 -0
  19. package/lib/dsh/index.d.ts +4 -1
  20. package/lib/dsh/index.d.ts.map +1 -1
  21. package/lib/dsh/index.js +7 -1
  22. package/lib/dsh/index.js.map +1 -1
  23. package/lib/dsh/official-budgets.d.ts +3 -0
  24. package/lib/dsh/official-budgets.d.ts.map +1 -0
  25. package/lib/dsh/official-budgets.js +114 -0
  26. package/lib/dsh/official-budgets.js.map +1 -0
  27. package/lib/dsh/ptc-budget.d.ts +5 -0
  28. package/lib/dsh/ptc-budget.d.ts.map +1 -0
  29. package/lib/dsh/ptc-budget.js +65 -0
  30. package/lib/dsh/ptc-budget.js.map +1 -0
  31. package/lib/dsh/super-code.d.ts.map +1 -1
  32. package/lib/dsh/super-code.js +26 -8
  33. package/lib/dsh/super-code.js.map +1 -1
  34. package/lib/index.d.ts +5 -1
  35. package/lib/index.d.ts.map +1 -1
  36. package/lib/index.js +5 -2
  37. package/lib/index.js.map +1 -1
  38. package/lib/task-memory-projection.d.ts +1 -1
  39. package/lib/task-memory-projection.d.ts.map +1 -1
  40. package/lib/task-memory-projection.js +7 -4
  41. package/lib/task-memory-projection.js.map +1 -1
  42. package/package.json +17 -7
  43. package/presets/super-code/agent.cordis.yml +2 -2
@@ -24,6 +24,57 @@ The default guidance calls for parallel reads when useful, ordered writes, tests
24
24
 
25
25
  Batching reduces round trips between the model and tools. It does not guarantee that every operation runs faster or change model, permission, or memory settings.
26
26
 
27
+ ## 运行预算 · Runtime Budgets
28
+
29
+ 打开设置中的“Super Code 模式”(部分版本位于“插件”→“插件配置”)。顶部“预设状态”用于查看和安装预设;“上下文配置”用于调整预算。插件默认已使用此前 Pro 测试中的旧预算,无需手动填写。界面使用百分数和秒;括号内仍显示当前宿主的默认值,便于与输入框中的实际配置比较。
30
+
31
+ Open “Super Code” in Settings (under “Plugins” → “Plugin configuration” in some versions). “Preset status” shows and installs the preset; “Context settings” contains the budgets. The plugin already uses the older Pro-test budgets without manual setup. The form uses percentages and seconds; parentheses still show the current host defaults for comparison with the effective values in the inputs.
32
+
33
+ | 类型 / Type | 配置 / Settings | 生效范围 / Applies to |
34
+ |---|---|---|
35
+ | 通用预算 / Common budgets | 压缩比例、摘要上限、PTC 时限及重试次数 / Compression ratios, summary limit, PTC deadlines, and retries | 默认仅 Super Code;打开“同时应用到官方预设”后,也用于标准、PTC、极简、创造模式 / Super Code by default; also Standard, PTC, Minimal, and Create when “Also apply to official presets” is enabled |
36
+ | Super Code 专属预算 / Super Code budgets | 活跃任务记录上限、任务记忆上下文容量 / Active task record limit and task-memory context capacity | 始终仅 Super Code / Always Super Code only |
37
+
38
+ 官方预设开关默认关闭,不影响自定义预设;开启后也只修改通用预算,不改变官方预设的工具和提示词。修改保存后对新建 Agent 生效,运行中的 Agent 保留原配置。切换顶部标签不会丢失尚未保存的输入。
39
+
40
+ The official-preset switch is off by default and leaves custom presets untouched. When enabled, it changes only common budgets, preserving official tools and prompts. Saved changes apply to new Agents; running Agents keep their configuration. Switching tabs retains unsaved input.
41
+
42
+ 留空沿用插件默认预算;“恢复默认”会清除界面的覆盖,回到插件加载配置,未配置的字段使用旧预算。用户已保存的配置优先生效。保存失败时保留输入,若提示预算已在别处修改,先重新读取再调整。
43
+
44
+ Leave fields blank to inherit plugin defaults. “Reset to defaults” clears UI overrides and restores the plugin configuration, using the older budgets for unconfigured fields. Saved user values take precedence. Failed saves retain your input. If budgets changed elsewhere, reload before editing again.
45
+
46
+ 也可以通过插件的 `budgets` 配置调整通用预算;将 `applyToOfficialPresets` 设为 `true` 可同时应用到上述四种官方预设。保存预算不会重启 Agent。
47
+
48
+ You can also set common budgets in the plugin's `budgets` configuration. Set `applyToOfficialPresets: true` to include the four official presets above. Saving budgets does not restart Agents.
49
+
50
+ 旧宿主未提供 `ptcRuntime` 时,“批量工具执行”的时限输入框会禁用;压缩预算和任务记忆容量仍可设置。
51
+
52
+ On older hosts without `ptcRuntime`, batch-tool deadline inputs are disabled; compression and task-memory budgets remain configurable.
53
+
54
+ 下面是插件已默认使用的旧预算,无需再将它手动添加到 `name: dsh-super-code` 的加载配置中。需要自定义时,可以在界面或加载项的 `config.budgets` 中修改对应字段。
55
+
56
+ The plugin already uses these older budgets by default; there is no need to add them manually to the `dsh-super-code` entry. Customize individual fields in the UI or the entry's `config.budgets` when needed.
57
+
58
+ ```yaml
59
+ budgets:
60
+ pressureBasis: window
61
+ thresholdRatio: 0.8
62
+ retainRatio: 0.16
63
+ summaryMaxTokens: 8192
64
+ compactionRetries: 1
65
+ maxOverflowRetries: 1
66
+ ptcTimeoutMs: 600000
67
+ ptcMaxTimeoutMs: 600000
68
+ ```
69
+
70
+ `pressureBasis: window` 为插件默认,按完整上下文窗口计算;选择 `host` 则按当前宿主策略计算。`retainRatio` 必须小于 `thresholdRatio`。PTC 两项的单位是毫秒,包含工具等待时间;显式更短的调用期限仍然生效,上限不会超过宿主允许值。PTC 时间覆盖需要提供 `ptcRuntime` 的新版宿主;旧版的 CPU 忙碌计时与新版总耗时计时不能等同。这些配置不改变执行后端、权限或取消行为。
71
+
72
+ `pressureBasis: window` is the plugin default and uses the full context window; choose `host` to follow the current host budget policy. `retainRatio` must be lower than `thresholdRatio`. PTC values are milliseconds, including tool waits; explicit shorter call deadlines still apply, and the host ceiling remains authoritative. PTC overrides require a newer host with `ptcRuntime`. The old busy-CPU timer and the new elapsed timer are different. These settings preserve the host execution backend, permissions, and cancellation.
73
+
74
+ Super Code 专属的 `maxTasks`(默认 32)和 `maxContextBytes`(默认 32,768),分别控制会话中活跃任务记录数量和任务记忆上下文的字节预算。增加预算会占用更多上下文;通常保持默认即可。
75
+
76
+ Super Code also has `maxTasks` (default 32) and `maxContextBytes` (default 32,768), which bound the active task records and task-memory context bytes per conversation. Larger budgets use more context; the defaults are usually sufficient.
77
+
27
78
  ## 找不到预设 · Can't Find the Preset?
28
79
 
29
80
  先确认插件已启用,并按[兼容矩阵](Compatibility.md)核对宿主版本与实际依赖。插件按宿主提供的预设机制选择以下两条路径。
@@ -0,0 +1,51 @@
1
+ /** Persist UI overrides through Harness settings; Agents take creation-time snapshots. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import type { SettingsScope } from '@deepseek-ai/dsh-settings';
4
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
5
+ import type { Configuration } from './budgets.js';
6
+ interface SettingsWriter {
7
+ readonly writable: boolean;
8
+ describe(options: {
9
+ redactSecrets: boolean;
10
+ }): {
11
+ ns: string;
12
+ revision: number;
13
+ }[];
14
+ replace(namespace: string, config: object, revision: number): Promise<void>;
15
+ }
16
+ export interface BudgetSettingsSnapshot {
17
+ readonly configuration: Configuration;
18
+ readonly revision: number;
19
+ readonly writable: boolean;
20
+ readonly ptcMaxTimeoutMs: number | false;
21
+ readonly defaults: Configuration;
22
+ }
23
+ export type BudgetSettingsResult = {
24
+ readonly ok: true;
25
+ readonly snapshot: BudgetSettingsSnapshot;
26
+ } | {
27
+ readonly ok: false;
28
+ readonly error: 'invalid' | 'conflict' | 'read-only' | 'ptc-unavailable' | 'ptc-ceiling' | 'save-failed';
29
+ };
30
+ export declare class BudgetSettings {
31
+ private readonly settings;
32
+ private readonly scope;
33
+ private readonly ptcCeiling;
34
+ private readonly key;
35
+ private readonly defaults;
36
+ constructor(settings: SettingsWriter, scope: Pick<SettingsScope<Configuration>, 'get'>, ptcCeiling: () => number | false, key?: string, defaults?: () => Configuration);
37
+ read(): BudgetSettingsSnapshot;
38
+ save(content: string, expected: string): Promise<BudgetSettingsResult>;
39
+ reset(expected: string): Promise<BudgetSettingsResult>;
40
+ private replace;
41
+ }
42
+ export declare class SuperCodeBudgets extends TypertRemoteService {
43
+ private readonly settings;
44
+ constructor(ctx: Context, settings: BudgetSettings);
45
+ readConfig(): BudgetSettingsSnapshot;
46
+ saveConfig(content: string, expected: string): Promise<BudgetSettingsResult>;
47
+ resetConfig(expected: string): Promise<BudgetSettingsResult>;
48
+ }
49
+ export declare function applyBudgetSettings(ctx: Context, config: Configuration): void;
50
+ export {};
51
+ //# sourceMappingURL=budget-settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget-settings.d.ts","sourceRoot":"","sources":["../../src/dsh/budget-settings.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AAC9D,OAAO,EAAU,mBAAmB,EAAE,MAAM,kCAAkC,CAAA;AAE9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAKjD,UAAU,cAAc;IACtB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;IAC1B,QAAQ,CAAC,OAAO,EAAE;QAAE,aAAa,EAAE,OAAO,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IACjF,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,M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AO,CAAC,oBAAoB,CAAC;YAE9C,OAAO;CAUtB;AAED,qBAAa,gBAAiB,SAAQ,mBAAmB;IAC7B,OAAO,CAAC,QAAQ,CAAC,QAAQ;gBAAvC,GAAG,EAAE,OAAO,EAAmB,QAAQ,EAAE,cAAc;IAEnE,UAAU,IAAI,sBAAsB;IAEpC,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAE5E,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;CAC7D;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,GAAG,IAAI,CA8C7E"}
@@ -0,0 +1,188 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
36
+ import { settingsConfigurationSchema, configurationValues, validateConfiguration } from './budgets.js';
37
+ import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
38
+ const namespace = 'super-code-budgets';
39
+ /** Keep the evaluated budgets independent of changes to the host's defaults. */
40
+ function withLegacyBudgets(config, ptcCeiling) {
41
+ const maxTimeout = ptcCeiling === false ? false : Math.min(ptcCeiling, config.budgets?.ptcMaxTimeoutMs ?? Math.max(600000, config.budgets?.ptcTimeoutMs ?? 0));
42
+ return {
43
+ applyToOfficialPresets: false, maxTasks: 32, maxContextBytes: 32768, ...config,
44
+ budgets: { pressureBasis: 'window', thresholdRatio: 0.8, retainRatio: 0.16,
45
+ summaryMaxTokens: 8192, compactionRetries: 1, maxOverflowRetries: 1,
46
+ ...(maxTimeout === false ? {} : { ptcTimeoutMs: Math.min(600000, maxTimeout), ptcMaxTimeoutMs: maxTimeout }),
47
+ ...config.budgets,
48
+ },
49
+ };
50
+ }
51
+ export class BudgetSettings {
52
+ settings;
53
+ scope;
54
+ ptcCeiling;
55
+ key;
56
+ defaults;
57
+ constructor(settings, scope, ptcCeiling, key = namespace, defaults = () => ({})) {
58
+ this.settings = settings;
59
+ this.scope = scope;
60
+ this.ptcCeiling = ptcCeiling;
61
+ this.key = key;
62
+ this.defaults = defaults;
63
+ }
64
+ read() {
65
+ const descriptor = this.settings.describe({ redactSecrets: true }).find(row => row.ns === this.key);
66
+ if (!descriptor)
67
+ throw new Error('Super Code budget settings are unavailable');
68
+ return { configuration: structuredClone(this.scope.get()), revision: descriptor.revision,
69
+ writable: this.settings.writable, ptcMaxTimeoutMs: this.ptcCeiling(), defaults: structuredClone(this.defaults()) };
70
+ }
71
+ async save(content, expected) {
72
+ if (!this.settings.writable)
73
+ return { ok: false, error: 'read-only' };
74
+ let config;
75
+ try {
76
+ if (content.length > 4096)
77
+ throw new Error('Configuration is too large');
78
+ config = validateConfiguration(JSON.parse(content));
79
+ }
80
+ catch {
81
+ return { ok: false, error: 'invalid' };
82
+ }
83
+ const budgets = config.budgets;
84
+ if (budgets?.ptcTimeoutMs !== undefined || budgets?.ptcMaxTimeoutMs !== undefined) {
85
+ const ceiling = this.ptcCeiling();
86
+ if (ceiling === false)
87
+ return { ok: false, error: 'ptc-unavailable' };
88
+ if ((budgets.ptcTimeoutMs ?? 0) > ceiling || (budgets.ptcMaxTimeoutMs ?? 0) > ceiling)
89
+ return { ok: false, error: 'ptc-ceiling' };
90
+ }
91
+ return this.replace(config, expected);
92
+ }
93
+ async reset(expected) { return this.replace({}, expected); }
94
+ async replace(config, expected) {
95
+ if (!this.settings.writable)
96
+ return { ok: false, error: 'read-only' };
97
+ if (!/^(0|[1-9]\d*)$/.test(expected) || !Number.isSafeInteger(Number(expected)))
98
+ return { ok: false, error: 'invalid' };
99
+ try {
100
+ await this.settings.replace(this.key, config, Number(expected));
101
+ return { ok: true, snapshot: this.read() };
102
+ }
103
+ catch (error) {
104
+ return { ok: false, error: error.code === 'SETTINGS_CONFLICT' ? 'conflict' : 'save-failed' };
105
+ }
106
+ }
107
+ }
108
+ let SuperCodeBudgets = (() => {
109
+ let _classSuper = TypertRemoteService;
110
+ let _instanceExtraInitializers = [];
111
+ let _readConfig_decorators;
112
+ let _saveConfig_decorators;
113
+ let _resetConfig_decorators;
114
+ return class SuperCodeBudgets extends _classSuper {
115
+ static {
116
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
117
+ _readConfig_decorators = [Remote];
118
+ _saveConfig_decorators = [Remote];
119
+ _resetConfig_decorators = [Remote];
120
+ __esDecorate(this, null, _readConfig_decorators, { kind: "method", name: "readConfig", static: false, private: false, access: { has: obj => "readConfig" in obj, get: obj => obj.readConfig }, metadata: _metadata }, null, _instanceExtraInitializers);
121
+ __esDecorate(this, null, _saveConfig_decorators, { kind: "method", name: "saveConfig", static: false, private: false, access: { has: obj => "saveConfig" in obj, get: obj => obj.saveConfig }, metadata: _metadata }, null, _instanceExtraInitializers);
122
+ __esDecorate(this, null, _resetConfig_decorators, { kind: "method", name: "resetConfig", static: false, private: false, access: { has: obj => "resetConfig" in obj, get: obj => obj.resetConfig }, metadata: _metadata }, null, _instanceExtraInitializers);
123
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
124
+ }
125
+ settings = __runInitializers(this, _instanceExtraInitializers);
126
+ constructor(ctx, settings) {
127
+ super(ctx, 'superCodeBudgets');
128
+ this.settings = settings;
129
+ }
130
+ readConfig() { return this.settings.read(); }
131
+ saveConfig(content, expected) { return this.settings.save(content, expected); }
132
+ resetConfig(expected) { return this.settings.reset(expected); }
133
+ };
134
+ })();
135
+ export { SuperCodeBudgets };
136
+ export function applyBudgetSettings(ctx, config) {
137
+ const base = configurationValues(config);
138
+ const hostDefaults = new BasicCompactionEngine(ctx.isolate('compaction'), { auto: false }).config;
139
+ const snapshots = new WeakMap();
140
+ let timeout = false;
141
+ let read = () => configurationValues(config);
142
+ const source = {
143
+ get: () => withLegacyBudgets(read(), timeout ? timeout.maxMs : false),
144
+ forAgent(agent) {
145
+ let snapshot = snapshots.get(agent);
146
+ if (!snapshot) {
147
+ snapshot = structuredClone(source.get());
148
+ snapshots.set(agent, snapshot);
149
+ }
150
+ return structuredClone(snapshot);
151
+ },
152
+ };
153
+ ctx.provide('superCodeConfiguration', source);
154
+ ctx.inject(['ptcRuntime'], ready => {
155
+ const runtime = ready.get('ptcRuntime');
156
+ timeout = runtime.timeout ?? false;
157
+ ready.effect(() => () => { timeout = false; });
158
+ });
159
+ // Recent hosts retain a preset generation across Agents; plugin apply is not an Agent boundary.
160
+ ctx.on('agent/created', ({ agent }) => { source.forAgent(agent); });
161
+ ctx.inject(['settings'], owner => {
162
+ const settings = owner.settings;
163
+ let key = namespace;
164
+ if (typeof settings.register === 'function') {
165
+ const scope = settings.register(namespace, settingsConfigurationSchema, { base, validate: validateConfiguration });
166
+ read = () => structuredClone(scope.get());
167
+ owner.effect(() => () => { read = () => structuredClone(base); });
168
+ }
169
+ else {
170
+ // SettingsForms edits this Loader entry's volatile values without remounting Agents.
171
+ const forms = settings;
172
+ const entryId = ctx.fiber.entry?.options.id;
173
+ if (!entryId)
174
+ throw new Error('Super Code budgets require a profile plugin entry');
175
+ key = entryId;
176
+ owner.effect(() => forms.configure({ auto: false }, ctx.fiber));
177
+ }
178
+ new SuperCodeBudgets(owner, new BudgetSettings(settings, source, () => timeout ? timeout.maxMs : false, key, () => ({
179
+ applyToOfficialPresets: false, maxTasks: 32, maxContextBytes: 32768,
180
+ budgets: { pressureBasis: 'host', thresholdRatio: hostDefaults.thresholdRatio, retainRatio: hostDefaults.retainRatio,
181
+ summaryMaxTokens: hostDefaults.maxTokens, compactionRetries: hostDefaults.compactionRetries,
182
+ maxOverflowRetries: hostDefaults.maxOverflowRetries,
183
+ ...(timeout ? { ptcTimeoutMs: timeout.defaultMs, ptcMaxTimeoutMs: timeout.maxMs } : {}),
184
+ },
185
+ })));
186
+ });
187
+ }
188
+ //# sourceMappingURL=budget-settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget-settings.js","sourceRoot":"","sources":["../../src/dsh/budget-settings.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,OAAO,EAAE,MAAM,EAAE,mBAAmB,E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,CAAC,CAAC;YAClH,sBAAsB,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,eAAe,EAAE,KAAK;YACnE,OAAO,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,cAAc,EAAE,YAAY,CAAC,cAAc,EAAE,WAAW,EAAE,YAAY,CAAC,WAAW;gBAClH,gBAAgB,EAAE,YAAY,CAAC,SAAS,EAAE,iBAAiB,EAAE,YAAY,CAAC,iBAAiB;gBAC3F,kBAAkB,EAAE,YAAY,CAAC,kBAAkB;gBACnD,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,OAAO,CAAC,SAAS,EAAE,eAAe,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACxF;SACF,CAAC,CAAC,CAAC,CAAA;IACN,CAAC,CAAC,CAAA;AACJ,CAAC"}
@@ -0,0 +1,34 @@
1
+ /** Optional policy overrides. Missing values remain owned by the host. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ import type { Context } from '@deepseek-ai/cordis';
4
+ declare global {
5
+ namespace Schemastery {
6
+ interface Meta<T = any> {
7
+ volatile?: boolean;
8
+ }
9
+ }
10
+ }
11
+ export interface Budgets {
12
+ readonly pressureBasis?: 'host' | 'window';
13
+ readonly thresholdRatio?: number;
14
+ readonly retainRatio?: number;
15
+ readonly summaryMaxTokens?: number;
16
+ readonly compactionRetries?: number;
17
+ readonly maxOverflowRetries?: number;
18
+ readonly ptcTimeoutMs?: number;
19
+ readonly ptcMaxTimeoutMs?: number;
20
+ }
21
+ export interface Configuration {
22
+ readonly applyToOfficialPresets?: boolean;
23
+ readonly budgets?: Budgets;
24
+ readonly maxTasks?: number;
25
+ readonly maxContextBytes?: number;
26
+ }
27
+ export declare const budgetSchema: z<Budgets>;
28
+ export declare const settingsConfigurationSchema: z<Configuration>;
29
+ export declare const configurationSchema: z<Configuration>;
30
+ export declare function validateConfiguration(config: Configuration): Configuration;
31
+ /** Newer Loader schemas expose volatile fields as references; older hosts return plain values. */
32
+ export declare function configurationValues(config: Configuration): Configuration;
33
+ export declare function configurationOf(ctx: Context, agent?: object): Configuration;
34
+ //# sourceMappingURL=budgets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budgets.d.ts","sourceRoot":"","sources":["../../src/dsh/budgets.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,OAAO,CAAC,MAAM,0BAA0B,CAAA;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAIlD,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,WAAW,CAAC;QACpB,UAAU,IAAI,CAAC,CAAC,GAAG,GAAG;YAAI,QAAQ,CAAC,EAAE,OAAO,CAAA;SAAE;KAC/C;CACF;AAED,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAA;IAC1C,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;IAChC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;IAC7B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAClC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAA;IACnC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;IACpC,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAClC;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,sBAAsB,CAAC,EAAE,OAAO,CAAA;IACzC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAClC;AAED,eAAO,MAAM,YAAY,EAAE,CAAC,CAAC,OAAO,CASlC,CAAA;AAGF,eAAO,MAAM,2BAA2B,EAAE,CAAC,CAAC,aAAa,CAKvD,CAAA;AAEF,eAAO,MAAM,mBAAmB,EAAE,CAAC,CAAC,aAAa,CAK/C,CAAA;AAuBF,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAE1E;AAED,kGAAkG;AAClG,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAMxE;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,aAAa,CAG3E"}
@@ -0,0 +1,65 @@
1
+ /** Optional policy overrides. Missing values remain owned by the host. */
2
+ import z from '@deepseek-ai/schemastery';
3
+ import { z as json } from 'zod';
4
+ export const budgetSchema = z.object({
5
+ pressureBasis: z.union(['host', 'window']).description('Compression budget basis: host policy or full context window.'),
6
+ thresholdRatio: z.number().min(0.01).max(1).description('Context fraction at which compression starts.'),
7
+ retainRatio: z.number().min(0).max(1).description('Recent context fraction retained verbatim.'),
8
+ summaryMaxTokens: z.number().step(1).min(1).description('Maximum summary output tokens.'),
9
+ compactionRetries: z.number().step(1).min(0).max(10),
10
+ maxOverflowRetries: z.number().step(1).min(0).max(10),
11
+ ptcTimeoutMs: z.number().step(1).min(1).description('Default PTC elapsed deadline, including tool waits, in milliseconds.'),
12
+ ptcMaxTimeoutMs: z.number().step(1).min(1).description('PTC elapsed ceiling; the host ceiling remains authoritative.'),
13
+ });
14
+ // SettingsProvider resolves plain data; volatile references belong only to Loader entries.
15
+ export const settingsConfigurationSchema = z.object({
16
+ applyToOfficialPresets: z.boolean().description('Apply common runtime budgets to Standard, PTC, Minimal and Create presets (default: off).'),
17
+ budgets: budgetSchema.description('Optional runtime budgets; leave blank to follow the host.'),
18
+ maxTasks: z.number().step(1).min(1).max(128),
19
+ maxContextBytes: z.number().step(1).min(1024).max(262144),
20
+ });
21
+ export const configurationSchema = z.object({
22
+ applyToOfficialPresets: settingsConfigurationSchema.dict.applyToOfficialPresets.extra('volatile', true),
23
+ budgets: settingsConfigurationSchema.dict.budgets.extra('volatile', true),
24
+ maxTasks: settingsConfigurationSchema.dict.maxTasks.extra('volatile', true),
25
+ maxContextBytes: settingsConfigurationSchema.dict.maxContextBytes.extra('volatile', true),
26
+ });
27
+ const validConfiguration = json.object({
28
+ applyToOfficialPresets: json.boolean().optional(),
29
+ budgets: json.object({
30
+ pressureBasis: json.enum(['host', 'window']).optional(),
31
+ thresholdRatio: json.number().min(0.01).max(1).optional(),
32
+ retainRatio: json.number().min(0).max(1).optional(),
33
+ summaryMaxTokens: json.number().int().positive().safe().optional(),
34
+ compactionRetries: json.number().int().min(0).max(10).optional(),
35
+ maxOverflowRetries: json.number().int().min(0).max(10).optional(),
36
+ ptcTimeoutMs: json.number().int().positive().safe().optional(),
37
+ ptcMaxTimeoutMs: json.number().int().positive().safe().optional(),
38
+ }).strict().optional(),
39
+ maxTasks: json.number().int().min(1).max(128).optional(),
40
+ maxContextBytes: json.number().int().min(1024).max(262144).optional(),
41
+ }).strict().superRefine((config, ctx) => {
42
+ const b = config.budgets;
43
+ if (!b)
44
+ return;
45
+ if ((b.retainRatio ?? 0.16) >= (b.thresholdRatio ?? 0.8))
46
+ ctx.addIssue({ code: 'custom', message: 'Retention must be below the compression threshold.' });
47
+ if (b.ptcTimeoutMs !== undefined && b.ptcMaxTimeoutMs !== undefined && b.ptcTimeoutMs > b.ptcMaxTimeoutMs)
48
+ ctx.addIssue({ code: 'custom', message: 'PTC default deadline exceeds its ceiling.' });
49
+ });
50
+ export function validateConfiguration(config) {
51
+ return validConfiguration.parse(config);
52
+ }
53
+ /** Newer Loader schemas expose volatile fields as references; older hosts return plain values. */
54
+ export function configurationValues(config) {
55
+ return validateConfiguration(Object.fromEntries(Object.entries(config).flatMap(([key, value]) => {
56
+ const reference = value;
57
+ const selected = typeof reference?.get === 'function' ? reference.get() : value;
58
+ return selected === undefined ? [] : [[key, selected]];
59
+ })));
60
+ }
61
+ export function configurationOf(ctx, agent) {
62
+ const source = ctx.get('superCodeConfiguration');
63
+ return source ? agent && source.forAgent ? source.forAgent(agent) : source.get() : {};
64
+ }
65
+ //# sourceMappingURL=budgets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budgets.js","sourceRoot":"","sources":["../../src/dsh/budgets.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAExC,OAAO,EAAE,CAAC,IAAI,IAAI,EAAE,MAAM,KAAK,CAAA;AA2B/B,MAAM,CAAC,MAAM,YAAY,GAAe,CAAC,CAAC,MAAM,CAAC;IAC/C,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,+DAA+D,CAAC;IACvH,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,+CAA+C,CAAC;IACxG,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,4CAA4C,CAAC;IAC/F,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,gCAAgC,CAAC;IACzF,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;IACpD,kBAAkB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;IACrD,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,I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G,KAAK,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,KAAK,CAAA;QAC/E,OAAO,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAA;IACxD,CAAC,CAAC,CAAC,CAAC,CAAA;AACN,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAY,EAAE,KAAc;IAC1D,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,wBAAwB,CAAkF,CAAA;IACjI,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;AACvF,CAAC"}
@@ -0,0 +1,40 @@
1
+ /** Change pressure policy while retaining the host's compaction transaction. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
4
+ import { CompactionEngine } from '@deepseek-ai/dsh-compaction';
5
+ import type { CompactionResult, CompactionTrigger } from '@deepseek-ai/dsh-compaction';
6
+ import type { Agent } from '@deepseek-ai/dsh-agent';
7
+ import type { Session, SessionSeq } from '@deepseek-ai/dsh-session';
8
+ import type { TokenMeasurement } from '@deepseek-ai/dsh-token-meter';
9
+ import type { CommandId } from '@deepseek-ai/dsh-commands/brand';
10
+ import { budgetSchema } from './budgets.js';
11
+ import type { Budgets } from './budgets.js';
12
+ export declare const name = "super-code-compaction";
13
+ export declare const inject: readonly string[];
14
+ export declare const Config: typeof budgetSchema;
15
+ /** Preserve the system head and extend the retained tail to a balanced tool boundary. */
16
+ export declare function compactableRange(session: Session, measurement: TokenMeasurement, retainTokens: number): {
17
+ start: SessionSeq;
18
+ end: SessionSeq;
19
+ } | {
20
+ kind: 'none';
21
+ };
22
+ export declare class BudgetCompactionEngine extends BasicCompactionEngine {
23
+ private readonly budgets;
24
+ constructor(ctx: Context, budgets?: Budgets);
25
+ compactIfNeeded(agent: Agent, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null>;
26
+ }
27
+ /** Share the window policy with an official engine without replacing its transaction or listeners. */
28
+ export declare function compactByWindow(engine: BasicCompactionEngine, budgets: Budgets, agent: Agent, signal: AbortSignal): Promise<CompactionResult | null>;
29
+ /** Retained preset generations share this router, while each Agent owns its host engine. */
30
+ export declare class AgentBudgetCompaction extends CompactionEngine {
31
+ private readonly overrides;
32
+ private readonly engines;
33
+ constructor(ctx: Context, overrides?: Budgets);
34
+ forAgent(agent: Agent): Promise<BudgetCompactionEngine>;
35
+ compactIfNeeded(agent: Agent, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null>;
36
+ compactRegion(start: SessionSeq, end: SessionSeq, agent: Agent, signal?: AbortSignal): Promise<CompactionResult>;
37
+ compactNow(agent: Agent, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null>;
38
+ }
39
+ export declare function apply(ctx: Context, config?: Budgets): void;
40
+ //# sourceMappingURL=compaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../src/dsh/compaction.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAA;AACzE,OAAO,EAAE,gBAAgB,EAA6B,MAAM,6BAA6B,CAAA;AAEzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AACtF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAA;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CA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E,OAAY;IAwBlE,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAqBxC,eAAe,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAIhH,aAAa,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAIhH,UAAU,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,CAAC,EAAE,SAAS,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;CAG5H;AAED,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,OAAY,GAAG,IAAI,CAE9D"}
@@ -0,0 +1,146 @@
1
+ import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
2
+ import { CompactionEngine, toolPairingBalancedBefore } from '@deepseek-ai/dsh-compaction';
3
+ import { createScope } from '@deepseek-ai/dsh-scope';
4
+ import { budgetSchema, configurationOf, validateConfiguration } from './budgets.js';
5
+ export const name = 'super-code-compaction';
6
+ export const inject = ['llm', 'tokenMeter', 'sessions'];
7
+ export const Config = budgetSchema;
8
+ /** Preserve the system head and extend the retained tail to a balanced tool boundary. */
9
+ export function compactableRange(session, measurement, retainTokens) {
10
+ const nodes = session.surface.nodes;
11
+ if (!nodes.length)
12
+ return { kind: 'none' };
13
+ if (nodes.length !== measurement.nodes.length || nodes.some((seq, index) => seq !== measurement.nodes[index]?.seq))
14
+ throw new Error('Compression measurement does not match the current surface');
15
+ const first = session.eventAt(nodes[0])?.type === 'system/message' ? 1 : 0;
16
+ let tokens = 0, keep = nodes.length;
17
+ for (let index = nodes.length - 1; index >= 0; index--) {
18
+ tokens += measurement.nodes[index].tokens;
19
+ keep = index;
20
+ if (tokens >= retainTokens)
21
+ break;
22
+ }
23
+ while (keep > first && !toolPairingBalancedBefore(session, nodes[keep]))
24
+ keep--;
25
+ return keep <= first ? { kind: 'none' } : { start: nodes[first], end: nodes[keep - 1] };
26
+ }
27
+ export class BudgetCompactionEngine extends BasicCompactionEngine {
28
+ budgets;
29
+ constructor(ctx, budgets = {}) {
30
+ validateConfiguration({ budgets });
31
+ super(ctx, {
32
+ thresholdRatio: budgets.thresholdRatio,
33
+ retainRatio: budgets.retainRatio,
34
+ maxTokens: budgets.summaryMaxTokens,
35
+ compactionRetries: budgets.compactionRetries,
36
+ maxOverflowRetries: budgets.maxOverflowRetries,
37
+ });
38
+ this.budgets = budgets;
39
+ }
40
+ async compactIfNeeded(agent, trigger, signal) {
41
+ if (this.budgets.pressureBasis !== 'window' || trigger !== 'pressure')
42
+ return super.compactIfNeeded(agent, trigger, signal);
43
+ return compactByWindow(this, this.budgets, agent, signal);
44
+ }
45
+ }
46
+ /** Share the window policy with an official engine without replacing its transaction or listeners. */
47
+ export async function compactByWindow(engine, budgets, agent, signal) {
48
+ const ctx = engine['ctx'];
49
+ signal.throwIfAborted();
50
+ const config = agent.session.requestHeader()?.config;
51
+ if (!config?.provider || !config.model)
52
+ return null;
53
+ const info = await ctx.llm.resolveModelInfo(config.provider, config.model, signal);
54
+ const window = info.context?.contextWindow;
55
+ if (!Number.isSafeInteger(window) || !window || window < 1)
56
+ throw new Error('Compression requires the routed model context window');
57
+ const threshold = Math.floor(window * (budgets.thresholdRatio ?? engine.config.thresholdRatio));
58
+ const retain = Math.floor(window * (budgets.retainRatio ?? engine.config.retainRatio ?? 0.16));
59
+ let measurement = ctx.tokenMeter.measure(agent.session);
60
+ if (measurement.totalTokens < threshold)
61
+ return null;
62
+ const pruner = ctx.get('toolResultPruner');
63
+ if (pruner) {
64
+ pruner.pruneSession(agent.session);
65
+ measurement = ctx.tokenMeter.measure(agent.session);
66
+ }
67
+ if (measurement.totalTokens < threshold)
68
+ return null;
69
+ let result = null;
70
+ for (let attempt = 0; attempt <= (budgets.compactionRetries ?? engine.config.compactionRetries); attempt++) {
71
+ signal.throwIfAborted();
72
+ const range = compactableRange(agent.session, measurement, retain);
73
+ if ('kind' in range)
74
+ return result;
75
+ result = await engine.compactRegion(range.start, range.end, agent, signal);
76
+ measurement = ctx.tokenMeter.measure(agent.session);
77
+ if (measurement.totalTokens < threshold)
78
+ return result;
79
+ }
80
+ throw new Error('Compression remains above the configured window threshold after its retry budget');
81
+ }
82
+ /** Retained preset generations share this router, while each Agent owns its host engine. */
83
+ export class AgentBudgetCompaction extends CompactionEngine {
84
+ overrides;
85
+ engines = new WeakMap();
86
+ constructor(ctx, overrides = {}) {
87
+ super(ctx);
88
+ this.overrides = overrides;
89
+ validateConfiguration({ budgets: overrides });
90
+ ctx.on('agent/created', async ({ agent }) => { await this.forAgent(agent); });
91
+ ctx.on('agent/disposed', async ({ agent }) => {
92
+ const entry = this.engines.get(agent);
93
+ this.engines.delete(agent);
94
+ await entry?.dispose();
95
+ });
96
+ // Older creation events do not await listeners; finish setup before the first pressure check.
97
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
98
+ const ready = this.engines.get(agent)?.ready;
99
+ const engine = await this.forAgent(agent);
100
+ if (!ready && !signal.aborted) {
101
+ try {
102
+ await engine.compactIfNeeded(agent, 'pressure', signal);
103
+ }
104
+ catch (error) {
105
+ const message = error instanceof Error ? error.message : String(error);
106
+ ctx.logger.warn(`step compaction failed: ${message}; continuing the turn`);
107
+ }
108
+ }
109
+ return next();
110
+ });
111
+ }
112
+ forAgent(agent) {
113
+ let entry = this.engines.get(agent);
114
+ if (!entry) {
115
+ const scope = createScope(this.ctx, agent);
116
+ const budgets = { ...configurationOf(this.ctx, agent).budgets, ...this.overrides };
117
+ const fiber = scope.ctx.isolate('compaction').plugin({ inject, apply(owner) { new BudgetCompactionEngine(owner, budgets); } });
118
+ const created = {
119
+ ready: false, dispose: scope.dispose,
120
+ engine: fiber.await().then(() => {
121
+ const engine = fiber.ctx.get('compaction');
122
+ if (!engine)
123
+ throw new Error('Agent compression engine did not become available');
124
+ created.ready = true;
125
+ return engine;
126
+ }).catch(async (error) => { await scope.dispose(); throw error; }),
127
+ };
128
+ entry = created;
129
+ this.engines.set(agent, entry);
130
+ }
131
+ return entry.engine;
132
+ }
133
+ async compactIfNeeded(agent, trigger, signal) {
134
+ return (await this.forAgent(agent)).compactIfNeeded(agent, trigger, signal);
135
+ }
136
+ async compactRegion(start, end, agent, signal) {
137
+ return (await this.forAgent(agent)).compactRegion(start, end, agent, signal);
138
+ }
139
+ async compactNow(agent, signal, sourceCommandId) {
140
+ return (await this.forAgent(agent)).compactNow(agent, signal, sourceCommandId);
141
+ }
142
+ }
143
+ export function apply(ctx, config = {}) {
144
+ new AgentBudgetCompaction(ctx, config);
145
+ }
146
+ //# sourceMappingURL=compaction.js.map