@agimon-ai/po-autocompact 0.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,855 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_compactionPolicy = require("../compactionPolicy-BIJJHcBP.cjs");
6
+ let _agimon_ai_po_core_serverFacet = require("@agimon-ai/po-core/serverFacet");
7
+ let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
8
+ let _agimon_ai_po_core_contextContributions = require("@agimon-ai/po-core/contextContributions");
9
+ let _agimon_ai_po_core_uiHub = require("@agimon-ai/po-core/uiHub");
10
+ let _agimon_ai_po_config = require("@agimon-ai/po-config");
11
+ let _agimon_ai_po_telemetry = require("@agimon-ai/po-telemetry");
12
+ let minimatch = require("minimatch");
13
+ const FOOTER_SOURCE = "doom-autocompact";
14
+ const STATUS_KEY = "doom-autocompact";
15
+ //#endregion
16
+ //#region src/services/autocompactRuntime/index.ts
17
+ function errorMessage(error) {
18
+ return error instanceof Error ? error.message : String(error);
19
+ }
20
+ function latestPlanSnapshot(branch) {
21
+ for (const entry of branch.toReversed()) {
22
+ if (entry.type !== "custom" || entry.customType !== "agent-harness-plan-document") continue;
23
+ if (!entry.data || typeof entry.data !== "object") return void 0;
24
+ const data = entry.data;
25
+ if (typeof data.content !== "string" || typeof data.path !== "string") return void 0;
26
+ return {
27
+ content: data.content,
28
+ path: data.path
29
+ };
30
+ }
31
+ }
32
+ const EMPTY_CONTEXT_CONTRIBUTIONS = Object.freeze({
33
+ entries: Object.freeze([]),
34
+ errors: Object.freeze([])
35
+ });
36
+ function readContextContributionsSnapshot(service) {
37
+ if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;
38
+ try {
39
+ return service.snapshot();
40
+ } catch (error) {
41
+ return {
42
+ entries: [],
43
+ errors: [{
44
+ source: _agimon_ai_po_core_contextContributions.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE,
45
+ id: "service-snapshot",
46
+ label: "Context contributions",
47
+ order: 0,
48
+ message: errorMessage(error)
49
+ }]
50
+ };
51
+ }
52
+ }
53
+ function formatContextContributions(snapshot) {
54
+ const sections = snapshot.entries.map((entry) => `### ${entry.label}\n${entry.text}`);
55
+ sections.push(...snapshot.errors.map((error) => `### ${error.label}\n(unavailable: ${error.message})`));
56
+ return sections.length > 0 ? sections.join("\n\n") : "(no registered context contributions)";
57
+ }
58
+ function runtimeStateSnapshot(branch, contextContributions) {
59
+ const plan = latestPlanSnapshot(branch);
60
+ return {
61
+ ...plan ? { planPath: plan.path } : {},
62
+ contributions: contextContributions.entries,
63
+ contributionErrors: contextContributions.errors
64
+ };
65
+ }
66
+ function formatRuntimeState(snapshot) {
67
+ return `<compaction-runtime-state>
68
+ Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
69
+ <active-plan>
70
+ ${snapshot.planPath ? `Source: ${snapshot.planPath}\nExact plan content is restored separately by Doom Plan.` : "(no active plan document)"}
71
+ </active-plan>
72
+ <context-contributions>
73
+ ${formatContextContributions({
74
+ entries: snapshot.contributions,
75
+ errors: snapshot.contributionErrors
76
+ })}
77
+ </context-contributions>
78
+ </compaction-runtime-state>`;
79
+ }
80
+ function steeringEnvelope(snapshot) {
81
+ const plan = snapshot.plan ? `Source: ${snapshot.plan.path}\n\n${snapshot.plan.content}` : "(no active plan document)";
82
+ const importantContext = [snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(", ")}` : void 0, snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(", ")}` : void 0].filter((value) => Boolean(value));
83
+ return `<compaction-steering priority="user,plan,context-contributions,important-context,recent-messages">
84
+ <user-prompt source="conversation">
85
+ Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
86
+ </user-prompt>
87
+ <active-plan>
88
+ ${plan}
89
+ </active-plan>
90
+ <context-contributions>
91
+ ${formatContextContributions(snapshot.contextContributions)}
92
+ </context-contributions>
93
+ <important-context>
94
+ ${importantContext.length > 0 ? importantContext.join("\n") : "(none recorded outside the conversation)"}
95
+ </important-context>
96
+ </compaction-steering>`;
97
+ }
98
+ function checkpointInstructions(pass, steering) {
99
+ const decision = pass === 2 ? "Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\n\n" : "";
100
+ return `Create Doom autocompact checkpoint pass ${pass}.
101
+
102
+ ${steeringEnvelope(steering)}
103
+
104
+ Apply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
105
+
106
+ ${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.
107
+
108
+ ## Goal
109
+ ## Constraints & Preferences
110
+ ## Progress
111
+ ### Done
112
+ ### In Progress
113
+ ### Blocked
114
+ ## Key Decisions
115
+ ## Next Steps
116
+ ## Critical Context`;
117
+ }
118
+ const DEFAULT_RUNTIME_CONFIG = {
119
+ enabled: true,
120
+ ratios: {},
121
+ overrides: []
122
+ };
123
+ /**
124
+ * What the Doom config says about this package.
125
+ *
126
+ * `modes.autocompact` is read first and `modes.planning.subagents` is the
127
+ * fallback, because summarization borrowed the planning subagent model before
128
+ * it had keys of its own and existing files still spell it that way.
129
+ */
130
+ function autocompactRuntimeConfig(root, onLoadFailure) {
131
+ let modes;
132
+ try {
133
+ modes = (0, _agimon_ai_po_config.loadDoomConfig)(root).modes;
134
+ } catch (error) {
135
+ process.emitWarning("Doom autocompact configuration could not be loaded; using the active session model instead.");
136
+ onLoadFailure?.(error);
137
+ return DEFAULT_RUNTIME_CONFIG;
138
+ }
139
+ const configured = modes?.autocompact;
140
+ const agent = (configured && (configured.model !== void 0 || configured.thinking !== void 0) ? {
141
+ ...configured.model ? { model: configured.model } : {},
142
+ ...configured.thinking ? { thinking: configured.thinking } : {}
143
+ } : void 0) ?? modes?.planning?.subagents;
144
+ const thresholds = configured?.thresholds;
145
+ return {
146
+ enabled: configured?.enabled ?? true,
147
+ ...agent ? { agent } : {},
148
+ ratios: {
149
+ ...thresholds?.pass1 === void 0 ? {} : { 1: thresholds.pass1 },
150
+ ...thresholds?.pass2 === void 0 ? {} : { 2: thresholds.pass2 },
151
+ ...thresholds?.pass3 === void 0 ? {} : { 3: thresholds.pass3 }
152
+ },
153
+ overrides: configured?.overrides ?? []
154
+ };
155
+ }
156
+ //#endregion
157
+ //#region src/services/autocompactTelemetry/index.ts
158
+ const SERVICE_NAME = "doom-autocompact";
159
+ const PACKAGE_NAME = "@agimon-ai/po-autocompact";
160
+ const AUTOCOMPACT_EVENT = {
161
+ checkpointStarted: "doom_autocompact.checkpoint_started",
162
+ checkpointCompleted: "doom_autocompact.checkpoint_completed",
163
+ checkpointFailed: "doom_autocompact.checkpoint_failed",
164
+ checkpointInvalid: "doom_autocompact.checkpoint_invalid",
165
+ configurationLoadFailed: "doom_autocompact.configuration_load_failed",
166
+ contextContributionDegraded: "doom_autocompact.context_contribution_degraded",
167
+ contextCommitted: "doom_autocompact.context_committed",
168
+ contextApplied: "doom_autocompact.context_applied",
169
+ contextMarkerInvalid: "doom_autocompact.context_marker_invalid",
170
+ contextHookSlow: "doom_autocompact.context_hook_slow",
171
+ nativeCompactionCompleted: "doom_autocompact.native_compaction_completed"
172
+ };
173
+ function createAutocompactTelemetry(options = {}) {
174
+ const telemetry = (0, _agimon_ai_po_telemetry.createDoomTelemetry)({
175
+ serviceName: SERVICE_NAME,
176
+ packageName: PACKAGE_NAME,
177
+ cwd: options.cwd,
178
+ workspaceRoot: options.workspaceRoot,
179
+ env: options.env,
180
+ telemetryFactory: options.telemetryFactory,
181
+ warn: options.warn,
182
+ enableLogs: true,
183
+ enableTraces: true
184
+ });
185
+ return {
186
+ recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),
187
+ recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),
188
+ recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),
189
+ runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),
190
+ flush: () => telemetry.flush(),
191
+ shutdown: () => telemetry.shutdown()
192
+ };
193
+ }
194
+ //#endregion
195
+ //#region src/services/modelOverrides/index.ts
196
+ /**
197
+ * A pattern naming a provider is matched against `provider/id`, anything else
198
+ * against the bare id. `*` does not cross `/`, so a bare pattern tested against a
199
+ * qualified subject would never match and would read as a silently dead rule.
200
+ */
201
+ function matchesModelPattern(pattern, model) {
202
+ const subject = pattern.includes("/") ? `${model.provider}/${model.id}` : model.id;
203
+ return (0, minimatch.minimatch)(subject, pattern, { nocase: true });
204
+ }
205
+ function resolveModelTokenOverrides(model, overrides) {
206
+ if (!model) return {};
207
+ const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));
208
+ if (!matched) return {};
209
+ const { pass1, pass2, pass3 } = matched.tokens;
210
+ return {
211
+ ...pass1 === void 0 ? {} : { 1: pass1 },
212
+ ...pass2 === void 0 ? {} : { 2: pass2 },
213
+ ...pass3 === void 0 ? {} : { 3: pass3 }
214
+ };
215
+ }
216
+ //#endregion
217
+ //#region src/services/summarizationModel/index.ts
218
+ const THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;
219
+ /** Splits a `provider/model` reference, tolerating the optional thinking suffix. */
220
+ function parseModelReference(reference) {
221
+ const trimmed = reference.trim();
222
+ const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1];
223
+ const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, "");
224
+ const separator = identity.indexOf("/");
225
+ if (separator <= 0 || separator >= identity.length - 1) return void 0;
226
+ return {
227
+ provider: identity.slice(0, separator),
228
+ modelId: identity.slice(separator + 1),
229
+ ...thinking ? { thinking } : {}
230
+ };
231
+ }
232
+ //#endregion
233
+ //#region src/services/nativeAutocompact/index.ts
234
+ /** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */
235
+ function tailAfter(snapshot, current) {
236
+ if (snapshot.length > current.length || snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))) return void 0;
237
+ return current.slice(snapshot.length);
238
+ }
239
+ function leaf(entries) {
240
+ return entries.findLast((entry) => entry.type !== "custom" || entry.customType !== "doom-autocompact-state" && entry.customType !== "doom-autocompact-checkpoint")?.id ?? "root";
241
+ }
242
+ function createNativeAutocompact(dependencies = {}) {
243
+ const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();
244
+ let active = true;
245
+ let generation = 0;
246
+ let state = require_compactionPolicy.createInitialState();
247
+ let snapshot;
248
+ let previousSnapshot;
249
+ let context;
250
+ let contributions;
251
+ let controller;
252
+ let serial = Promise.resolve();
253
+ const work = /* @__PURE__ */ new Set();
254
+ const applied = /* @__PURE__ */ new Set();
255
+ const invalid = /* @__PURE__ */ new Set();
256
+ let configFailureReported = false;
257
+ let footer;
258
+ let navigating = false;
259
+ let lastNativeCompactionId;
260
+ let checkpointBoundary;
261
+ const attributes = () => ({
262
+ "pi.session.id": context?.sessionId ?? "",
263
+ "autocompact.cycle": state.cycle,
264
+ "autocompact.pass": state.pass,
265
+ ...state.requestId ? { "autocompact.request.id": state.requestId } : {},
266
+ ...state.snapshotLeafId ? { "autocompact.snapshot_leaf_id": state.snapshotLeafId } : {},
267
+ ...state.snapshotTokens === void 0 ? {} : { "autocompact.tokens_before": state.snapshotTokens }
268
+ });
269
+ const configured = (execution) => autocompactRuntimeConfig(execution.repoRoot, (error) => {
270
+ if (!configFailureReported) {
271
+ configFailureReported = true;
272
+ telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, attributes());
273
+ }
274
+ });
275
+ const alive = (version) => active && !navigating && generation === version;
276
+ const refreshStatus = (execution) => {
277
+ const phase = state.phase === "checkpoint_pending" ? "summarizing" : state.phase === "checkpoint_ready" ? "applying" : void 0;
278
+ footer?.update(phase ? {
279
+ fullText: `Compacting p${state.pass}`,
280
+ compactText: `C${state.pass}`
281
+ } : void 0);
282
+ execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : void 0);
283
+ };
284
+ const enqueue = (callback) => {
285
+ const version = generation;
286
+ const operation = serial.then(async () => {
287
+ if (alive(version)) await callback();
288
+ });
289
+ serial = operation.catch(() => void 0);
290
+ return operation;
291
+ };
292
+ const persist = async (execution, version) => {
293
+ if (!alive(version)) return;
294
+ await execution.session.appendCustomEntry(require_compactionPolicy.STATE_CUSTOM_TYPE, {
295
+ ...state,
296
+ nativeSnapshot: snapshot,
297
+ nativePreviousSnapshot: previousSnapshot,
298
+ nativeLastCompactionId: lastNativeCompactionId
299
+ });
300
+ if (alive(version)) refreshStatus(execution);
301
+ };
302
+ const clear = () => {
303
+ delete state.requestId;
304
+ delete state.snapshotLeafId;
305
+ delete state.snapshotTokens;
306
+ delete state.pendingCheckpoint;
307
+ delete state.compactionPass;
308
+ snapshot = void 0;
309
+ };
310
+ const fail = async (execution, version, error, malformed = false) => {
311
+ if (!alive(version)) return;
312
+ const eventAttributes = attributes();
313
+ const attempts = state.invalidAttempts + 1;
314
+ const pass = state.pass;
315
+ const failedLeaf = state.snapshotLeafId;
316
+ state.invalidAttempts += 1;
317
+ if (state.invalidAttempts >= 3) {
318
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
319
+ state.exhaustedPasses.push(pass);
320
+ state.invalidAttempts = 0;
321
+ }
322
+ state.phase = "waiting";
323
+ clear();
324
+ state.lastAttemptLeafId = failedLeaf;
325
+ await persist(execution, version);
326
+ if (!alive(version)) return;
327
+ await execution.client.notify({
328
+ body: `Doom autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,
329
+ level: "error"
330
+ });
331
+ await telemetry.recordError(malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed, error, {
332
+ ...eventAttributes,
333
+ "autocompact.checkpoint.attempts": attempts,
334
+ "autocompact.checkpoint.exhausted": attempts >= 3
335
+ });
336
+ };
337
+ const branch = async (execution) => await execution.session.entries();
338
+ const canonical = async (execution, entries) => {
339
+ if (!execution.session.contextMessages) throw new Error("Canonical context is unavailable for autocompact.");
340
+ return require_compactionPolicy.projectContextMessages(await execution.session.contextMessages(), entries).messages;
341
+ };
342
+ const contributionSnapshot = async (execution) => {
343
+ const result = readContextContributionsSnapshot(contributions);
344
+ for (const error of result.errors) {
345
+ await execution.client.notify({
346
+ body: `Doom autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,
347
+ level: "warning"
348
+ });
349
+ await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {
350
+ ...attributes(),
351
+ "autocompact.context_contribution.source": error.source,
352
+ "autocompact.context_contribution.id": error.id,
353
+ "autocompact.context_contribution.order": error.order
354
+ });
355
+ }
356
+ return result;
357
+ };
358
+ const runtimeState = async (execution, entries, version, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
359
+ const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));
360
+ if (!alive(version)) return;
361
+ await appendMessage?.({
362
+ type: require_compactionPolicy.RUNTIME_STATE_MESSAGE_TYPE,
363
+ text: formatRuntimeState(saved),
364
+ display: false,
365
+ details: {
366
+ version: 2,
367
+ ...saved
368
+ }
369
+ });
370
+ return {
371
+ "autocompact.runtime.plan_present": Boolean(saved.planPath),
372
+ "autocompact.runtime.contribution_count": saved.contributions.length,
373
+ "autocompact.runtime.contribution_error_count": saved.contributionErrors.length
374
+ };
375
+ };
376
+ const resetCycle = () => {
377
+ state.phase = "waiting";
378
+ state.checkpointQueue = [];
379
+ state.exhaustedPasses = [];
380
+ state.invalidAttempts = 0;
381
+ state.baselinePending = true;
382
+ state.cycle += 1;
383
+ state.pass = 1;
384
+ delete state.lastAttemptLeafId;
385
+ delete state.latestCheckpointSnapshotLeafId;
386
+ clear();
387
+ previousSnapshot = void 0;
388
+ };
389
+ const applyReady = async (execution, version) => {
390
+ if (state.phase !== "checkpoint_ready" || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId) return false;
391
+ const decision = require_compactionPolicy.parseCheckpointDecision(state.pendingCheckpoint);
392
+ if (!require_compactionPolicy.isStructuredCheckpoint(decision.summary)) {
393
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an incomplete checkpoint."), true);
394
+ return false;
395
+ }
396
+ const entries = await branch(execution);
397
+ const messages = await canonical(execution, entries);
398
+ if (!alive(version)) return false;
399
+ const tail = snapshot && tailAfter(snapshot, messages);
400
+ if (!tail) {
401
+ await fail(execution, version, /* @__PURE__ */ new Error("Canonical checkpoint evidence changed; summary must be regenerated."));
402
+ return false;
403
+ }
404
+ const pass = state.pass;
405
+ if (pass === 1 || pass === 2 && decision.shouldCompact !== true) {
406
+ await execution.session.appendCustomEntry(require_compactionPolicy.CHECKPOINT_MESSAGE_TYPE, {
407
+ ...require_compactionPolicy.checkpointRequestDetails(state.cycle, pass, state.requestId),
408
+ summary: decision.summary
409
+ });
410
+ if (!alive(version)) return false;
411
+ previousSnapshot = snapshot;
412
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
413
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
414
+ state.pass = pass === 1 ? 2 : 3;
415
+ state.phase = "waiting";
416
+ state.invalidAttempts = 0;
417
+ clear();
418
+ await persist(execution, version);
419
+ return false;
420
+ }
421
+ if (!execution.session.appendMessage) throw new Error("Checkpoint messages are unavailable.");
422
+ const files = require_compactionPolicy.mergeFileDetails(state, require_compactionPolicy.fileOperationsFromMessages(messages));
423
+ const details = {
424
+ ...files,
425
+ doomAutocompact: {
426
+ version: 2,
427
+ cycle: state.cycle,
428
+ pass,
429
+ requestId: state.requestId,
430
+ snapshotLeafId: state.snapshotLeafId,
431
+ tokensBefore: state.snapshotTokens ?? 0
432
+ },
433
+ retainedMessages: tail
434
+ };
435
+ const idle = (await execution.session.activity()).isIdle;
436
+ if (!alive(version)) return false;
437
+ const id = await execution.session.appendMessage({
438
+ type: require_compactionPolicy.CONTEXT_MESSAGE_TYPE,
439
+ text: require_compactionPolicy.withCanonicalFileSections(decision.summary, files),
440
+ display: false,
441
+ details
442
+ });
443
+ if (!alive(version) || !id) return false;
444
+ await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);
445
+ if (!alive(version)) return false;
446
+ const runtimeAttributes = await runtimeState(execution, entries, version, execution.session.appendMessage.bind(execution.session));
447
+ if (!alive(version)) return false;
448
+ const committedAttributes = attributes();
449
+ state.readFiles = files.readFiles;
450
+ state.modifiedFiles = files.modifiedFiles;
451
+ resetCycle();
452
+ await persist(execution, version);
453
+ if (!alive(version)) return false;
454
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {
455
+ ...committedAttributes,
456
+ "autocompact.message_count.before": messages.length,
457
+ "autocompact.message_count.retained": tail.length,
458
+ "autocompact.apply_mode": idle ? "idle" : "turn_end",
459
+ ...runtimeAttributes
460
+ });
461
+ if (idle && alive(version)) await execution.session.admitPrompt?.("Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.", "steer", void 0, `${require_compactionPolicy.RESUME_MESSAGE_TYPE}:${details.doomAutocompact.requestId}`);
462
+ return true;
463
+ };
464
+ const progress = async (execution, allowBusy = false, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
465
+ const version = generation;
466
+ context = execution;
467
+ const activity = await execution.session.activity();
468
+ if (!alive(version) || activity.hasPendingMessages) return;
469
+ if (appendMessage && (activity.isIdle || allowBusy)) {
470
+ const checkpointExecution = {
471
+ ...execution,
472
+ session: {
473
+ ...execution.session,
474
+ appendMessage
475
+ }
476
+ };
477
+ if (await applyReady(checkpointExecution, version)) return;
478
+ }
479
+ if (!alive(version) || state.phase !== "waiting") return;
480
+ const configuration = configured(execution);
481
+ if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;
482
+ const usage = await execution.session.contextUsage();
483
+ const entries = await branch(execution);
484
+ if (!alive(version) || !usage || usage.tokens === null) return;
485
+ if (state.baselinePending) {
486
+ if (!require_compactionPolicy.baselineUsageIsSettled(entries)) return;
487
+ state.baselineTokens = usage.tokens;
488
+ state.baselinePending = false;
489
+ await persist(execution, version);
490
+ return;
491
+ }
492
+ const currentLeaf = leaf(entries);
493
+ if (currentLeaf === state.lastAttemptLeafId) return;
494
+ const thresholds = require_compactionPolicy.effectiveThresholds(usage.contextWindow, state.baselineTokens, configuration.ratios, resolveModelTokenOverrides(execution.model, configuration.overrides));
495
+ for (const pass of [
496
+ 1,
497
+ 2,
498
+ 3
499
+ ]) if (pass >= state.pass && !state.checkpointQueue.includes(pass) && !state.exhaustedPasses.includes(pass) && usage.tokens >= thresholds[pass]) state.checkpointQueue.push(pass);
500
+ const pass = state.checkpointQueue[0];
501
+ if (!pass) return;
502
+ const messages = await canonical(execution, entries);
503
+ const steering = await contributionSnapshot(execution);
504
+ if (!alive(version)) return;
505
+ snapshot = messages;
506
+ const previous = pass > 1 ? require_compactionPolicy.checkpointSummaryFromEntry(require_compactionPolicy.latestCheckpointArtifactEntry(entries)) : void 0;
507
+ const requestId = require_compactionPolicy.createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);
508
+ state.phase = "checkpoint_pending";
509
+ state.pass = pass;
510
+ state.requestId = requestId;
511
+ state.snapshotLeafId = currentLeaf;
512
+ state.snapshotTokens = usage.tokens;
513
+ delete state.lastAttemptLeafId;
514
+ delete state.pendingCheckpoint;
515
+ await persist(execution, version);
516
+ if (!alive(version)) return;
517
+ controller?.abort();
518
+ controller = new AbortController();
519
+ const signal = controller.signal;
520
+ const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : void 0;
521
+ const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : void 0;
522
+ const reference = candidate && execution.textCompletion.available(candidate) ? candidate : execution.model ? `${execution.model.provider}/${execution.model.id}` : "";
523
+ const thinking = configuration.agent?.thinking ?? (reference === candidate ? ownReference?.thinking : void 0) ?? (await execution.session.readModelSettings?.())?.thinkingLevel;
524
+ if (!alive(version)) return;
525
+ const requestAttributes = {
526
+ ...attributes(),
527
+ "autocompact.message_count.before": messages.length
528
+ };
529
+ const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
530
+ const completion = telemetry.runInSpan("doom_autocompact.checkpoint", requestAttributes, async () => {
531
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);
532
+ return execution.textCompletion.summarize(reference, {
533
+ messages: pass > 1 && delta ? delta : messages,
534
+ instructions: checkpointInstructions(pass, {
535
+ plan: latestPlanSnapshot(entries),
536
+ contextContributions: steering,
537
+ readFiles: state.readFiles,
538
+ modifiedFiles: state.modifiedFiles
539
+ }),
540
+ ...previous ? { previousSummary: previous } : {},
541
+ ...thinking ? { thinkingLevel: thinking } : {},
542
+ signal
543
+ });
544
+ }).then(async (summary) => {
545
+ await enqueue(async () => {
546
+ if (!alive(version) || signal.aborted || state.requestId !== requestId) return;
547
+ if (!summary.trim()) {
548
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an empty checkpoint."));
549
+ return;
550
+ }
551
+ state.phase = "checkpoint_ready";
552
+ state.pendingCheckpoint = summary.trim();
553
+ await persist(execution, version);
554
+ if (!alive(version)) return;
555
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {
556
+ ...requestAttributes,
557
+ "autocompact.checkpoint.characters": summary.length
558
+ });
559
+ if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);
560
+ });
561
+ }).catch(async (error) => {
562
+ await enqueue(async () => {
563
+ if (alive(version) && state.requestId === requestId) await fail(execution, version, error);
564
+ });
565
+ });
566
+ work.add(completion);
567
+ completion.then(() => work.delete(completion), () => work.delete(completion));
568
+ };
569
+ const restore = async (execution) => {
570
+ if (!active) return;
571
+ if (!checkpointBoundary) {
572
+ if (!execution.session.registerCheckpointBoundary) throw new Error("Native checkpoint boundaries are unavailable.");
573
+ checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {
574
+ if (!active || navigating || boundary.signal?.aborted) return;
575
+ const current = context ?? execution;
576
+ await enqueue(() => boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)));
577
+ });
578
+ }
579
+ navigating = false;
580
+ generation += 1;
581
+ const version = generation;
582
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact session generation changed."));
583
+ controller = void 0;
584
+ context = execution;
585
+ applied.clear();
586
+ invalid.clear();
587
+ const entries = await branch(execution);
588
+ if (!alive(version)) return;
589
+ const entry = entries.findLast((item) => item.type === "custom" && item.customType === "doom-autocompact-state");
590
+ const data = entry?.type === "custom" && entry.data && typeof entry.data === "object" ? entry.data : void 0;
591
+ state = require_compactionPolicy.parseState(data) ?? require_compactionPolicy.createInitialState();
592
+ lastNativeCompactionId = typeof data?.nativeLastCompactionId === "string" ? data.nativeLastCompactionId : void 0;
593
+ const validMessages = (value) => Array.isArray(value) && value.every((message) => message && typeof message === "object" && typeof message.role === "string");
594
+ snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
595
+ previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
596
+ if (state.phase === "checkpoint_ready" && state.requestId) {
597
+ const artifacts = entries.slice(entry ? entries.indexOf(entry) + 1 : 0);
598
+ const committed = artifacts.findLast((item) => {
599
+ const message = item.type === "message" ? item.message : void 0;
600
+ if (message?.role !== "custom" || message.customType !== "doom-autocompact-context") return false;
601
+ const details = require_compactionPolicy.contextDetailsFromUnknown(message.details);
602
+ return details !== void 0 && details.doomAutocompact.requestId === state.requestId && details.doomAutocompact.cycle === state.cycle && details.doomAutocompact.pass === state.pass && details.doomAutocompact.snapshotLeafId === state.snapshotLeafId && require_compactionPolicy.isStructuredCheckpoint(require_compactionPolicy.checkpointSummaryFromEntry(item) ?? "");
603
+ });
604
+ if (committed?.type === "message" && committed.message.role === "custom") {
605
+ const details = require_compactionPolicy.contextDetailsFromUnknown(committed.message.details);
606
+ state.readFiles = details.readFiles;
607
+ state.modifiedFiles = details.modifiedFiles;
608
+ resetCycle();
609
+ await persist(execution, version);
610
+ } else if (artifacts.findLast((item) => {
611
+ if (item.type !== "custom" || item.customType !== "doom-autocompact-checkpoint") return false;
612
+ const details = item.data;
613
+ return details?.version === 2 && details.requestId === state.requestId && details.cycle === state.cycle && details.pass === state.pass && require_compactionPolicy.isStructuredCheckpoint(require_compactionPolicy.checkpointSummaryFromEntry(item) ?? "");
614
+ }) && (state.pass === 1 || state.pass === 2)) {
615
+ previousSnapshot = snapshot;
616
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
617
+ state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);
618
+ state.pass = state.pass === 1 ? 2 : 3;
619
+ state.phase = "waiting";
620
+ state.invalidAttempts = 0;
621
+ clear();
622
+ await persist(execution, version);
623
+ }
624
+ }
625
+ if (state.phase !== "waiting" && state.phase !== "checkpoint_ready") {
626
+ state.phase = "waiting";
627
+ clear();
628
+ await persist(execution, version);
629
+ }
630
+ if (alive(version)) await enqueue(() => progress(execution));
631
+ };
632
+ return {
633
+ hooks: [
634
+ {
635
+ event: "session_start",
636
+ handle: (_event, execution) => restore(execution)
637
+ },
638
+ {
639
+ event: "session_tree",
640
+ handle: (event, execution) => {
641
+ if (!active) return;
642
+ if (event.status === "started") {
643
+ navigating = true;
644
+ generation += 1;
645
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact navigation started."));
646
+ return;
647
+ }
648
+ return restore(execution);
649
+ }
650
+ },
651
+ {
652
+ event: "turn_end",
653
+ handle: (_event, execution) => enqueue(() => progress(execution))
654
+ },
655
+ {
656
+ event: "agent_settled",
657
+ handle: (_event, execution) => enqueue(() => progress(execution))
658
+ },
659
+ {
660
+ event: "session_before_compact",
661
+ handle: (event, execution) => active && !navigating && configured(execution).enabled && event.reason === "threshold" && (state.phase === "checkpoint_pending" || state.phase === "checkpoint_ready" || state.baselinePending) ? { cancel: true } : void 0
662
+ },
663
+ {
664
+ event: "context",
665
+ async handle(event, execution) {
666
+ if (!active || navigating || !Array.isArray(event.messages)) return;
667
+ const started = Date.now();
668
+ try {
669
+ const version = generation;
670
+ const entries = await branch(execution);
671
+ if (!alive(version)) return;
672
+ const projection = require_compactionPolicy.projectContextMessages(event.messages, entries);
673
+ if (projection.invalidMarker) {
674
+ const id = leaf(entries);
675
+ if (!invalid.has(id)) {
676
+ invalid.add(id);
677
+ await telemetry.recordError(AUTOCOMPACT_EVENT.contextMarkerInvalid, /* @__PURE__ */ new Error("Doom autocompact context marker is malformed."), {
678
+ ...attributes(),
679
+ "autocompact.leaf_id": id
680
+ });
681
+ }
682
+ return;
683
+ }
684
+ if (!projection.marker) return;
685
+ if (!applied.has(projection.marker.requestId)) {
686
+ applied.add(projection.marker.requestId);
687
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {
688
+ ...attributes(),
689
+ "autocompact.request.id": projection.marker.requestId,
690
+ "autocompact.cycle": projection.marker.cycle,
691
+ "autocompact.pass": projection.marker.pass,
692
+ "autocompact.snapshot_leaf_id": projection.marker.snapshotLeafId,
693
+ "autocompact.tokens_before": projection.marker.tokensBefore,
694
+ "autocompact.message_count.before": event.messages.length,
695
+ "autocompact.message_count.after": projection.messages.length,
696
+ "autocompact.message_count.retained": projection.retainedMessageCount
697
+ });
698
+ }
699
+ return alive(version) ? { messages: projection.messages } : void 0;
700
+ } finally {
701
+ const hookMs = Date.now() - started;
702
+ if (active && hookMs >= 25) await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {
703
+ ...attributes(),
704
+ hook_ms: hookMs,
705
+ "autocompact.message_count": event.messages.length
706
+ });
707
+ }
708
+ }
709
+ },
710
+ {
711
+ event: "session_compact",
712
+ handle: (event, execution) => {
713
+ if (!active || event.status !== "completed" || typeof event.entryId !== "string" || event.entryId === lastNativeCompactionId) return;
714
+ const observedGeneration = generation;
715
+ return enqueue(async () => {
716
+ const entries = await branch(execution);
717
+ const compacted = entries.findLast((entry) => entry.type === "compaction");
718
+ if (!alive(observedGeneration) || !compacted || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
719
+ generation += 1;
720
+ const version = generation;
721
+ controller?.abort(/* @__PURE__ */ new Error("Native compaction superseded checkpoint."));
722
+ controller = void 0;
723
+ lastNativeCompactionId = compacted.id;
724
+ const files = require_compactionPolicy.mergeFileDetails(state, void 0, require_compactionPolicy.fileDetailsFromUnknown("details" in compacted ? compacted.details : void 0));
725
+ state.readFiles = files.readFiles;
726
+ state.modifiedFiles = files.modifiedFiles;
727
+ await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);
728
+ if (!alive(version)) return;
729
+ const runtimeAttributes = await runtimeState(execution, entries, version);
730
+ if (!alive(version)) return;
731
+ const nativeAttributes = attributes();
732
+ resetCycle();
733
+ await persist(execution, version);
734
+ if (alive(version)) await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {
735
+ ...nativeAttributes,
736
+ "autocompact.native.reason": typeof event.reason === "string" ? event.reason : "unknown",
737
+ "autocompact.native.from_extension": "fromHook" in compacted && compacted.fromHook === true,
738
+ "autocompact.tokens_before": compacted.tokensBefore,
739
+ ...runtimeAttributes
740
+ });
741
+ });
742
+ }
743
+ }
744
+ ],
745
+ plugin(cordis) {
746
+ cordis.inject([_agimon_ai_po_core_uiHub.DOOM_UI_HUB_SERVICE], (injected) => {
747
+ const contribution = (0, _agimon_ai_po_core_uiHub.requireDoomUiHub)(injected).registerFooter({
748
+ source: FOOTER_SOURCE,
749
+ id: "autocompact",
750
+ order: 20
751
+ });
752
+ footer = contribution;
753
+ if (context && active) refreshStatus(context);
754
+ return () => {
755
+ contribution.dispose();
756
+ if (footer === contribution) footer = void 0;
757
+ };
758
+ });
759
+ cordis.inject([_agimon_ai_po_core_contextContributions.DOOM_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {
760
+ const service = (0, _agimon_ai_po_core_contextContributions.requireDoomContextContributions)(injected);
761
+ contributions = service;
762
+ return () => {
763
+ if (contributions === service) contributions = void 0;
764
+ };
765
+ });
766
+ },
767
+ start: restore,
768
+ async stop() {
769
+ active = false;
770
+ checkpointBoundary?.dispose();
771
+ checkpointBoundary = void 0;
772
+ generation += 1;
773
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact is shutting down."));
774
+ await Promise.allSettled([...work, serial]);
775
+ context?.client.setStatus(STATUS_KEY, void 0);
776
+ footer?.update(void 0);
777
+ footer = void 0;
778
+ context = void 0;
779
+ contributions = void 0;
780
+ await telemetry.shutdown();
781
+ }
782
+ };
783
+ }
784
+ //#endregion
785
+ //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
786
+ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(() => {
787
+ const runtime = createNativeAutocompact();
788
+ return {
789
+ value: runtime,
790
+ services: [runtime.plugin],
791
+ onDispose: runtime.stop
792
+ };
793
+ });
794
+ //#endregion
795
+ //#region src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
796
+ var agent_settled_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "agent_settled"));
797
+ //#endregion
798
+ //#region src/extensions/workspaces/sessions/(backend)/hook/context.server.ts
799
+ var context_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "context"));
800
+ //#endregion
801
+ //#region src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts
802
+ var session_before_compact_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "session_before_compact"));
803
+ //#endregion
804
+ //#region src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts
805
+ var session_compact_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "session_compact"));
806
+ //#endregion
807
+ //#region src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts
808
+ var session_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "session_start"));
809
+ //#endregion
810
+ //#region src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts
811
+ var session_tree_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "session_tree"));
812
+ //#endregion
813
+ //#region src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts
814
+ var turn_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => root.hooks.find((hook) => hook.event === "turn_end"));
815
+ //#endregion
816
+ //#region generated/server.ts
817
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
818
+ const via = (identity, value) => value === void 0 ? void 0 : {
819
+ ...identity,
820
+ ...value
821
+ };
822
+ const facet = (0, _agimon_ai_po_core_serverFacet.defineServerPlugin)({
823
+ name: "@agimon-ai/po-autocompact",
824
+ providerOverrides: (0, _agimon_ai_po_core_serverFacet.composeServerProviderOverrides)(root_server_default),
825
+ session: async (context) => {
826
+ const scopeSession = await root_server_default(context);
827
+ const contextSession = {
828
+ ...context,
829
+ root: scopeSession.value
830
+ };
831
+ return {
832
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
833
+ get hooks() {
834
+ return [
835
+ via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)),
836
+ via({ event: "context" }, at(context_server_default, contextSession)),
837
+ via({ event: "session_before_compact" }, at(session_before_compact_server_default, contextSession)),
838
+ via({ event: "session_compact" }, at(session_compact_server_default, contextSession)),
839
+ via({ event: "session_start" }, at(session_start_server_default, contextSession)),
840
+ via({ event: "session_tree" }, at(session_tree_server_default, contextSession)),
841
+ via({ event: "turn_end" }, at(turn_end_server_default, contextSession))
842
+ ];
843
+ },
844
+ services: [...scopeSession.services ?? []],
845
+ get activities() {
846
+ return [...scopeSession.activities ?? []];
847
+ }
848
+ };
849
+ }
850
+ });
851
+ //#endregion
852
+ exports.default = facet;
853
+ exports.facet = facet;
854
+
855
+ //# sourceMappingURL=server.cjs.map