File size: 28,864 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/**
 * Queues embedded-agent session compaction onto the correct command lane.
 */
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import {
  loadSessionEntryReadOnly,
  type SessionTranscriptRuntimeTarget,
} from "../../config/sessions/session-accessor.js";
import { projectPublicSessionEntry } from "../../config/sessions/session-entry-projection.js";
import { OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST } from "../../context-engine/host-compat.js";
import { ensureContextEnginesInitialized } from "../../context-engine/init.js";
import {
  resolveContextEngine,
  resolveContextEngineOwnerPluginId,
} from "../../context-engine/registry.js";
import { buildContextEngineRuntimeSettings } from "../../context-engine/runtime-settings.js";
import type {
  ContextEngine,
  ContextEngineRuntimeContext,
  ContextEngineRuntimeSettings,
} from "../../context-engine/types.js";
import { formatErrorMessage } from "../../infra/errors.js";
import type { ProviderRuntimeModel } from "../../plugins/provider-runtime-model.types.js";
import { requireActivePluginRegistry } from "../../plugins/runtime.js";
import { withPluginRuntimeGenerationScope } from "../../plugins/runtime/generation-scope.js";
import { resolveSessionPinnedHarnessId } from "../../sessions/agent-harness-session-key.js";
import { resolveUserPath } from "../../utils.js";
import { resolveAgentDir, resolveSessionAgentIds } from "../agent-scope.js";
import { isRecoverableNativeHarnessBindingFailure } from "../harness/compaction-recovery.js";
import { maybeCompactAgentHarnessSession } from "../harness/compaction.js";
import { ensureSelectedAgentHarnessPlugin } from "../harness/runtime-plugin.js";
import {
  acquireAgentRunPreparedModelRuntime,
  type PreparedModelRuntimeSnapshot,
} from "../prepared-model-runtime.js";
import { resolveAgentRunSessionTarget } from "../run-session-target.js";
import { materializePreparedRuntimeModel } from "../runtime-plan/materialize-model.js";
import type { SandboxContext } from "../sandbox/types.js";
import { beginForegroundSessionMaintenance } from "../session-maintenance/coordinator.js";
import { resolveSessionPlacementSandbox } from "../session-placement-admission.js";
import { DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON } from "./compact-reasons.js";
import {
  runForegroundCompactionWork,
  type ForegroundCompactionOwner,
} from "./compact.foreground-work.js";
import { compactNativeCliSession } from "./compact.js";
import {
  createQueuedCompactionAbortedResult,
  projectQueuedCompactionSessionTarget,
  executeQueuedContextEngineCompaction,
  runPrimaryNativeCompactionInLanes,
  type QueuedCompactionHostOptions,
  withQueuedCompactionCancellationResult,
} from "./compact.queued-execution.js";
import type { CompactEmbeddedAgentSessionParams } from "./compact.types.js";
import {
  buildEmbeddedCompactionRuntimeContext,
  resolveCompactionContextTokenBudget,
} from "./compaction-runtime-context.js";
import {
  prepareCompactionHarnessAuth,
  projectCodexHostTranscriptBytePreflightConfig,
  resolveCompactionRuntimeSelection,
} from "./compaction-runtime-preparation.js";
import type { acceptCompactionSuccessor } from "./compaction-successor.js";
import { resolveContextEngineCapabilities } from "./context-engine-capabilities.js";
import type { ContextEngineMaintenanceResources } from "./context-engine-maintenance-work.js";
import { runContextEngineMaintenance } from "./context-engine-maintenance.js";
import { log } from "./logger.js";
import { resolveTieredModel } from "./model-resolution.js";
import { resolveModelAsync } from "./model.js";
import type { EmbeddedAgentQueueHandle } from "./run-state.js";
import {
  clearActiveEmbeddedRun,
  isEmbeddedAgentRunHandleActive,
  resolveActiveEmbeddedRunHandleSessionId,
  resolveActiveEmbeddedRunHandleSessionIdBySessionFile,
  setActiveEmbeddedRun,
} from "./runs.js";
import { resolveTranscriptBytePreflightAuthority } from "./transcript-byte-preflight-authority.js";
import type { EmbeddedAgentCompactResult } from "./types.js";

type QueuedCompactionParams = CompactEmbeddedAgentSessionParams & {
  sessionTarget: SessionTranscriptRuntimeTarget;
  sandbox?: SandboxContext | null;
};

function lockedCompactionRuntimeFailure(runtime?: string): EmbeddedAgentCompactResult {
  return {
    ok: false,
    compacted: false,
    reason: runtime
      ? `Model selection is locked to native agent harness "${runtime}", but native compaction is unavailable.`
      : "Model selection is locked but the persisted agent harness is unavailable.",
    failure: { reason: "model_selection_locked" },
  };
}

const DEFERRED_CONTEXT_ENGINE_COMPACTION_SCHEDULE_FAILURE_REASON =
  "failed to schedule background context-engine maintenance";
const MANUAL_COMPACTION_ACTIVE_RUN_REASON =
  "manual compaction unavailable while another embedded run is active";

function assertQueuedCompactionPreparationActive(
  params: CompactEmbeddedAgentSessionParams,
  host: QueuedCompactionHostOptions,
): void {
  // Preparation runs outside the execution queue. Revalidate after each await
  // so a cancelled or replaced owner cannot continue expensive setup.
  params.abortSignal?.throwIfAborted();
  host.assertActive?.();
}

function resolveManualCompactionActiveRunSessionId(
  params: CompactEmbeddedAgentSessionParams,
): string | undefined {
  return (
    (isEmbeddedAgentRunHandleActive(params.sessionId) ? params.sessionId : undefined) ??
    (params.sessionKey ? resolveActiveEmbeddedRunHandleSessionId(params.sessionKey) : undefined) ??
    resolveActiveEmbeddedRunHandleSessionIdBySessionFile(params.sessionFile)
  );
}

async function deferOwningContextEngineBudgetCompaction(params: {
  compactParams: CompactEmbeddedAgentSessionParams;
  contextEngineSessionKey?: string;
  contextEngine: ContextEngine;
  contextEngineRuntimeContext: ContextEngineRuntimeContext;
  contextEngineRuntimeSettings: ContextEngineRuntimeSettings;
  onDeferredMaintenance: (completion: Promise<void>) => void;
  factoryResources: ContextEngineMaintenanceResources;
}): Promise<EmbeddedAgentCompactResult> {
  let deferredScheduled = false;
  let deferredScheduleFailure: unknown;
  try {
    await runContextEngineMaintenance({
      contextEngine: params.contextEngine,
      sessionId: params.compactParams.sessionId,
      sessionKey: params.contextEngineSessionKey ?? params.compactParams.sessionKey,
      sessionTarget: projectQueuedCompactionSessionTarget(params.compactParams),
      sessionFile: params.compactParams.sessionFile,
      reason: "turn",
      runtimeContext: params.contextEngineRuntimeContext,
      runtimeSettings: params.contextEngineRuntimeSettings,
      config: params.compactParams.config,
      contextEngineAgentId: params.compactParams.contextEngineAgentId,
      disposeDeferredContextEngineAfterMaintenance: true,
      factoryResources: params.factoryResources,
      onDeferredMaintenance: (completion) => {
        deferredScheduled = true;
        params.onDeferredMaintenance(completion);
      },
      onDeferredMaintenanceFailure: (error) => {
        deferredScheduleFailure = error;
      },
    });
  } catch (err) {
    log.warn("failed to defer context-engine budget compaction", {
      errorMessage: formatErrorMessage(err),
    });
  }

  if (!deferredScheduled || deferredScheduleFailure) {
    log.warn(
      `[compaction] failed to schedule context-engine-owned budget compaction background maintenance ` +
        `(sessionKey=${params.compactParams.sessionKey ?? params.compactParams.sessionId}` +
        `${deferredScheduleFailure ? ` error=${formatErrorMessage(deferredScheduleFailure)}` : ""})`,
    );
    return {
      ok: false,
      compacted: false,
      reason: DEFERRED_CONTEXT_ENGINE_COMPACTION_SCHEDULE_FAILURE_REASON,
      failure: { reason: "deferred_compaction_not_scheduled" },
    };
  }

  log.info(
    `[compaction] deferred context-engine-owned budget compaction to background maintenance ` +
      `(sessionKey=${params.compactParams.sessionKey ?? params.compactParams.sessionId} ` +
      `scheduled=${String(deferredScheduled)})`,
  );
  return {
    ok: true,
    compacted: false,
    reason: DEFERRED_CONTEXT_ENGINE_COMPACTION_REASON,
  };
}

/**
 * Compacts a session with lane queueing (session lane + global lane).
 * Use this from outside a lane context. If already inside a lane, use
 * `compactEmbeddedAgentSessionDirect` to avoid deadlocks.
 */
export async function compactEmbeddedAgentSession(
  params: CompactEmbeddedAgentSessionParams,
  host: QueuedCompactionHostOptions = {},
): Promise<EmbeddedAgentCompactResult> {
  const projectedConfig = projectCodexHostTranscriptBytePreflightConfig(
    params.config,
    Boolean(host.transcriptBytePreflightHarness),
  );
  const contextEngineAgentId =
    normalizeOptionalString(params.contextEngineAgentId) ?? normalizeOptionalString(params.agentId);
  const contextEngineSessionKey =
    normalizeOptionalString(params.sessionKey) ??
    normalizeOptionalString(params.sessionTarget?.sessionKey);
  const runtimeTarget = await resolveAgentRunSessionTarget({
    ...params,
    missingSessionKey: "resolve-existing",
  });
  const releaseForeground =
    params.trigger === "manual"
      ? await beginForegroundSessionMaintenance(runtimeTarget.sessionKey)
      : undefined;
  try {
    // Resolve the storage address first, then freeze its owner before runtime/plugin awaits.
    const entry = loadSessionEntryReadOnly({ ...runtimeTarget, readConsistency: "latest" });
    const expectedEntry = {
      sessionId: runtimeTarget.sessionId,
      lifecycleRevision: entry?.lifecycleRevision,
      activeWriterRunId: entry?.activeWriterRunId,
    };
    const resolvedParams = {
      ...params,
      config: projectedConfig,
      sessionEntry: entry ? projectPublicSessionEntry(entry) : undefined,
      agentHarnessId: resolveSessionPinnedHarnessId(entry) ?? params.agentHarnessId,
      modelSelectionLocked: entry?.modelSelectionLocked ?? params.modelSelectionLocked,
      agentId: runtimeTarget.agentId,
      sessionId: runtimeTarget.sessionId,
      sessionKey: runtimeTarget.sessionKey,
      sessionTarget: runtimeTarget,
      sessionFile: runtimeTarget.sessionKey,
      contextEngineAgentId,
    };
    if (resolvedParams.trigger !== "manual") {
      return await withQueuedCompactionCancellationResult(resolvedParams, () =>
        compactEmbeddedAgentSessionImpl(
          resolvedParams,
          expectedEntry,
          host,
          contextEngineSessionKey,
        ),
      );
    }
    // Reply operations and embedded handles are separate lifecycle owners. A
    // /compact reply may coexist with this handle, but another embedded writer may not.
    if (resolveManualCompactionActiveRunSessionId(resolvedParams)) {
      return {
        ok: false,
        compacted: false,
        reason: MANUAL_COMPACTION_ACTIVE_RUN_REASON,
        failure: { reason: "active_run" },
      };
    }

    const controller = new AbortController();
    const abortSignal = resolvedParams.abortSignal
      ? AbortSignal.any([resolvedParams.abortSignal, controller.signal])
      : controller.signal;
    const handle: EmbeddedAgentQueueHandle = {
      kind: "embedded",
      queueMessage: async () => {},
      isStreaming: () => true,
      isAborted: () => abortSignal.aborted,
      isCompacting: () => true,
      abort: (reason) => controller.abort(reason ?? "user_abort"),
      cancel: (reason) => controller.abort(reason ?? "user_abort"),
    };
    const activeParams = { ...resolvedParams, abortSignal };
    setActiveEmbeddedRun(
      resolvedParams.sessionId,
      handle,
      resolvedParams.sessionKey,
      resolvedParams.sessionFile,
      resolvedParams.agentId,
    );
    try {
      return await withQueuedCompactionCancellationResult(activeParams, () =>
        compactEmbeddedAgentSessionImpl(activeParams, expectedEntry, host, contextEngineSessionKey),
      );
    } finally {
      clearActiveEmbeddedRun(
        resolvedParams.sessionId,
        handle,
        resolvedParams.sessionKey,
        resolvedParams.sessionFile,
      );
    }
  } finally {
    releaseForeground?.();
  }
}

async function compactEmbeddedAgentSessionImpl(
  params: QueuedCompactionParams,
  expectedEntry: Parameters<typeof acceptCompactionSuccessor>[0]["expectedEntry"],
  host: QueuedCompactionHostOptions,
  contextEngineSessionKey?: string,
): Promise<EmbeddedAgentCompactResult> {
  return await runForegroundCompactionWork((owner) =>
    compactEmbeddedAgentSessionPrepared(
      params,
      expectedEntry,
      host,
      contextEngineSessionKey,
      owner,
    ),
  );
}

async function compactEmbeddedAgentSessionPrepared(
  params: QueuedCompactionParams,
  expectedEntry: Parameters<typeof acceptCompactionSuccessor>[0]["expectedEntry"],
  host: QueuedCompactionHostOptions,
  contextEngineSessionKey: string | undefined,
  owner: ForegroundCompactionOwner,
): Promise<EmbeddedAgentCompactResult> {
  if (params.abortSignal?.aborted) {
    return createQueuedCompactionAbortedResult();
  }
  host.assertActive?.();
  const runtimeTarget = params.sessionTarget;
  const agentIds = resolveSessionAgentIds({
    sessionKey: runtimeTarget.sessionKey,
    config: params.config,
    agentId: runtimeTarget.agentId,
  });
  const agentDir = params.agentDir ?? resolveAgentDir(params.config ?? {}, agentIds.sessionAgentId);
  const resolvedWorkspaceDir = resolveUserPath(params.workspaceDir);
  const placementSandbox =
    params.sandbox === undefined
      ? await resolveSessionPlacementSandbox({
          agentId: runtimeTarget.agentId,
          config: params.config,
          sessionId: runtimeTarget.sessionId,
          sessionKey: runtimeTarget.sessionKey,
          workspaceDir: resolvedWorkspaceDir,
        })
      : null;
  assertQueuedCompactionPreparationActive(params, host);
  const requestedSelection = {
    ...params,
    modelId: params.model,
    boundHarnessRuntime: params.agentHarnessId,
    preparedRuntimePlan: params.runtimePlan,
    selectedHarnessRuntime: resolveSessionPinnedHarnessId(params.sessionEntry),
  };
  const runtimeSelection = resolveCompactionRuntimeSelection(requestedSelection);
  // Native control operations reuse the backend's existing authenticated session.
  // Run them before generic model preparation so subscription-only CLI sessions do
  // not incorrectly require an OpenClaw model API credential.
  const nativeCliResult = await compactNativeCliSession({
    runtime: runtimeSelection.selectedHarnessRuntime,
    compactParams: {
      ...params,
      agentDir,
      workspaceDir: resolvedWorkspaceDir,
    },
    runControlOperation: (run) =>
      runPrimaryNativeCompactionInLanes(params, expectedEntry, host, run),
  });
  if (nativeCliResult) {
    return nativeCliResult;
  }
  assertQueuedCompactionPreparationActive(params, host);
  const lease = await acquireAgentRunPreparedModelRuntime(
    {
      config: params.config ?? {},
      agentId: agentIds.sessionAgentId,
      agentDir,
      workspaceDir: resolvedWorkspaceDir,
      ...(params.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}),
    },
    {
      abortSignal: params.abortSignal,
      deriveRuntimePluginSelections: ({ config, metadataSnapshot }) => {
        const selected = resolveCompactionRuntimeSelection({
          ...requestedSelection,
          config: projectCodexHostTranscriptBytePreflightConfig(
            config,
            Boolean(host.transcriptBytePreflightHarness),
          ),
          manifestPlugins: metadataSnapshot,
          allowPluginNormalization: false,
        });
        return [
          {
            provider: selected.provider,
            modelId: selected.modelId,
            runtime: selected.selectedHarnessRuntime,
            agentId: agentIds.sessionAgentId,
          },
        ];
      },
    },
  );
  const factoryResources = owner.adoptLease(lease);
  // Admission can replace config and agent storage while preserving the requested workspace.
  const preparedParams = {
    ...params,
    ...(placementSandbox ? { sandbox: placementSandbox } : {}),
    config: projectCodexHostTranscriptBytePreflightConfig(
      lease.snapshot.config,
      Boolean(host.transcriptBytePreflightHarness),
    ),
    agentDir: lease.snapshot.agentDir,
  };
  const run = async () => {
    owner.captureContext();
    ensureContextEnginesInitialized();
    const contextEngine = await owner.resolveEngine(() =>
      resolveContextEngine(preparedParams.config, {
        agentDir: preparedParams.agentDir,
        workspaceDir: resolvedWorkspaceDir,
      }),
    );
    assertQueuedCompactionPreparationActive(params, host);
    return await compactResolvedContextEngine(
      preparedParams,
      expectedEntry,
      host,
      contextEngine,
      preparedParams.agentDir,
      resolvedWorkspaceDir,
      lease.snapshot,
      contextEngineSessionKey,
      owner.transferEngine,
      factoryResources,
    );
  };
  assertQueuedCompactionPreparationActive(params, host);
  return await withPluginRuntimeGenerationScope(lease.snapshot, run);
}

async function compactResolvedContextEngine(
  params: QueuedCompactionParams,
  expectedEntry: Parameters<typeof acceptCompactionSuccessor>[0]["expectedEntry"],
  host: QueuedCompactionHostOptions,
  contextEngine: ContextEngine,
  agentDir: string,
  resolvedWorkspaceDir: string,
  preparedModelRuntime: PreparedModelRuntimeSnapshot,
  contextEngineSessionKey: string | undefined,
  transferContextEngineOwnership: (completion: Promise<void>) => void,
  factoryResources: ContextEngineMaintenanceResources,
): Promise<EmbeddedAgentCompactResult> {
  const runtimeTarget = params.sessionTarget;
  const lockedHarnessRuntime = resolveSessionPinnedHarnessId(params.sessionEntry);
  if (lockedHarnessRuntime === "auto") {
    return lockedCompactionRuntimeFailure();
  }
  // A concrete model lock does not pin the observed or requested runtime. Only
  // durable native ownership can forbid a prepared transport's host fallback.
  const {
    runtimePolicySessionKey,
    runtimePolicyAgentId,
    selectedHarnessRuntime,
    target: resolvedCompactionTarget,
    runtimeModelAuth: { plan: reusableRuntimeAuthPlan, modelAuth: initialModelAuth },
    provider: ceProvider,
    runtimeProvider: ceRuntimeProvider,
    contextConfigProvider: ceContextConfigProvider,
    modelId: ceModelId,
    attemptNativeHarnessCompaction: selectedNativeHarnessCompaction,
  } = resolveCompactionRuntimeSelection({
    ...params,
    modelId: params.model,
    boundHarnessRuntime: params.agentHarnessId,
    preparedRuntimePlan: params.runtimePlan,
    selectedHarnessRuntime: lockedHarnessRuntime,
  });
  const lockedNativeHarness = Boolean(lockedHarnessRuntime && lockedHarnessRuntime !== "openclaw");
  // Ensure the policy-selected harness plugin so selection can pick implicit codex.
  await ensureSelectedAgentHarnessPlugin({
    config: params.config,
    provider: ceProvider,
    modelId: ceModelId,
    agentId: runtimePolicyAgentId,
    sessionKey: runtimePolicySessionKey,
    agentHarnessId: params.agentHarnessId,
    agentHarnessRuntimeOverride: selectedHarnessRuntime,
    workspaceDir: resolvedWorkspaceDir,
    pluginRegistry: requireActivePluginRegistry(),
  });
  assertQueuedCompactionPreparationActive(params, host);
  const { resolution: modelResolution } = await resolveTieredModel({
    provider: ceRuntimeProvider,
    modelId: ceModelId,
    agentDir,
    config: params.config,
    workspaceDir: resolvedWorkspaceDir,
    ...initialModelAuth,
    preparedModelRuntime,
  });
  assertQueuedCompactionPreparationActive(params, host);
  const { model: ceModel, authStorage, modelRegistry } = modelResolution;
  const ceRuntimeModel = ceModel as ProviderRuntimeModel | undefined;
  // Overrides stay unset when no bound/planned/explicit harness resolved so auth-aware
  // selection can pick the credential-owning harness (codex for ChatGPT OAuth).
  const {
    runtimeAuthPreparation,
    selectedPreparedHarness,
    providerUsesProfileScopedModelMetadata,
  } = await prepareCompactionHarnessAuth({
    ...params,
    provider: ceProvider,
    metadataProvider: ceRuntimeProvider,
    modelId: ceModelId,
    model: ceRuntimeModel,
    reusableRuntimeAuthPlan,
    agentDir,
    workspaceDir: resolvedWorkspaceDir,
    authProfileId: resolvedCompactionTarget.authProfileId,
    runtimePolicyAgentId,
    runtimePolicySessionKey,
    agentHarnessRuntimeOverride: selectedHarnessRuntime,
    convergenceErrorPrefix: "Prepared queued compaction",
  });
  assertQueuedCompactionPreparationActive(params, host);
  const preparedHarnessRuntime = selectedPreparedHarness.id;
  const transcriptBytePreflightAuthority =
    host.transcriptBytePreflightHarness === preparedHarnessRuntime
      ? resolveTranscriptBytePreflightAuthority(selectedPreparedHarness)
      : undefined;
  if (host.transcriptBytePreflightHarness && !transcriptBytePreflightAuthority) {
    return lockedCompactionRuntimeFailure(host.transcriptBytePreflightHarness);
  }
  const attemptNativeHarnessCompaction =
    selectedNativeHarnessCompaction && preparedHarnessRuntime !== "openclaw";
  const runtimeAuthPlan = runtimeAuthPreparation.plan;
  const effectiveRuntimeModel = await materializePreparedRuntimeModel<ProviderRuntimeModel>({
    plan: runtimeAuthPlan,
    provider: ceProvider,
    modelId: ceModelId,
    config: params.config,
    workspaceDir: resolvedWorkspaceDir,
    metadataSnapshot: preparedModelRuntime.metadataSnapshot,
    model: ceRuntimeModel,
    forceResolve:
      providerUsesProfileScopedModelMetadata && Boolean(runtimeAuthPlan.selectedAuthMode),
    resolveModel: async ({ config, authProfileId, authProfileMode }) => {
      const resolved = await resolveModelAsync(ceRuntimeProvider, ceModelId, agentDir, config, {
        authStorage,
        modelRegistry,
        preparedModelRuntime,
        skipAgentDiscovery: true,
        allowBundledStaticCatalogFallback: true,
        preferBundledStaticCatalogTransport: true,
        workspaceDir: resolvedWorkspaceDir,
        authProfileId,
        authProfileMode,
      });
      assertQueuedCompactionPreparationActive(params, host);
      return { ...resolved, model: resolved.model as ProviderRuntimeModel | undefined };
    },
  });
  assertQueuedCompactionPreparationActive(params, host);
  const preparedParams: QueuedCompactionParams = {
    ...params,
    provider: ceProvider,
    model: ceModelId,
    agentHarnessId: preparedHarnessRuntime,
    ...(reusableRuntimeAuthPlan
      ? {
          authProfileId: runtimeAuthPlan.forwardedAuthProfileId,
          authProfileIdSource: runtimeAuthPlan.forwardedAuthProfileSource,
          runtimeAuthPlan,
        }
      : {
          // Native compaction resolves this full attempt set itself. Legacy
          // compaction must re-plan too; forwarding one generated plan would
          // collapse cross-route and direct fallback before either dispatch.
          authProfileId: resolvedCompactionTarget.authProfileId,
          authProfileIdSource: resolvedCompactionTarget.authProfileId
            ? params.authProfileIdSource
            : undefined,
          runtimeAuthPlan: undefined,
          runtimePlan: undefined,
        }),
  };
  const contextTokenBudget = resolveCompactionContextTokenBudget({
    config: params.config,
    provider: ceContextConfigProvider,
    modelId: ceModelId,
    model: effectiveRuntimeModel,
    agentId: runtimeTarget.agentId,
    requestedTokenBudget: params.contextTokenBudget,
  });
  const contextEngineRuntimeContext = buildCompactionContextEngineRuntimeContext({
    params: preparedParams,
    agentDir,
    harnessRuntime: preparedHarnessRuntime,
    contextEngineSessionKey,
    contextTokenBudget,
    contextEnginePluginId: resolveContextEngineOwnerPluginId(contextEngine),
  });
  const contextEngineRuntimeSettings = buildContextEngineRuntimeSettings({
    contextEngineHost: OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST,
    provider: ceProvider,
    requestedModel: params.model,
    resolvedModel: ceModelId,
    selectedContextEngineId: contextEngine.info.id,
    contextEngineSelectionSource: contextEngine.info.id === "legacy" ? "default" : "configured",
    promptTokenBudget: contextTokenBudget,
  });
  const contextEngineOwnsCompaction = contextEngine.info.ownsCompaction === true;
  let requiredPreflightNativeCapabilityUsed = false;
  const harnessResult =
    attemptNativeHarnessCompaction &&
    !transcriptBytePreflightAuthority &&
    (!contextEngineOwnsCompaction || lockedNativeHarness)
      ? await runPrimaryNativeCompactionInLanes(preparedParams, expectedEntry, host, async () => {
          if (params.abortSignal?.aborted) {
            return createQueuedCompactionAbortedResult();
          }
          return await maybeCompactAgentHarnessSession(
            {
              ...preparedParams,
              runtimeModel: effectiveRuntimeModel,
              contextEngine,
              contextTokenBudget,
              contextEngineRuntimeContext,
            },
            {
              preparedModelRuntime,
              ...(preparedParams.preflightRequired === true
                ? {
                    nativeCompactionRequest: "required_preflight",
                    onNativeCompactionCapabilityUsed: () => {
                      requiredPreflightNativeCapabilityUsed = true;
                    },
                  }
                : {}),
            },
          );
        })
      : undefined;
  // Only the private dispatched native capability may authorize required-preflight
  // fallback for a locked harness; public result fields cannot escape the lock.
  if (
    lockedNativeHarness &&
    !transcriptBytePreflightAuthority &&
    !(
      preparedParams.preflightRequired === true &&
      requiredPreflightNativeCapabilityUsed &&
      isRecoverableNativeHarnessBindingFailure(harnessResult)
    )
  ) {
    return harnessResult ?? lockedCompactionRuntimeFailure(selectedHarnessRuntime);
  }
  if (harnessResult) {
    if (!isRecoverableNativeHarnessBindingFailure(harnessResult)) {
      return { ...harnessResult, compactionKind: "native-harness" };
    }
    log.warn(
      `native harness compaction could not use its session binding; falling back to context engine: ${harnessResult.reason ?? "unknown"}`,
    );
  }
  if (params.abortSignal?.aborted) {
    return createQueuedCompactionAbortedResult();
  }
  host.assertActive?.();
  // Budget maintenance may outlive reply preflight only when its engine owns
  // the transcript and explicitly supports background turn maintenance.
  if (
    preparedParams.deferOwningContextEngineCompaction === true &&
    preparedParams.trigger === "budget" &&
    contextEngineOwnsCompaction &&
    contextEngine.info.turnMaintenanceMode === "background" &&
    typeof contextEngine.maintain === "function"
  ) {
    return await deferOwningContextEngineBudgetCompaction({
      compactParams: preparedParams,
      contextEngineSessionKey,
      contextEngine,
      contextEngineRuntimeContext,
      contextEngineRuntimeSettings,
      onDeferredMaintenance: transferContextEngineOwnership,
      factoryResources,
    });
  }
  return await executeQueuedContextEngineCompaction({
    params,
    preparedParams,
    runtimeTarget,
    expectedEntry,
    host,
    contextEngine,
    contextEngineSessionKey,
    contextEngineRuntimeContext,
    contextEngineRuntimeSettings,
    resolvedWorkspaceDir,
    preparedModelRuntime,
    effectiveRuntimeModel,
    preparedHarnessRuntime,
    contextTokenBudget,
    attemptNativeHarnessCompaction,
    transcriptBytePreflightAuthority,
  });
}

function buildCompactionContextEngineRuntimeContext(params: {
  params: CompactEmbeddedAgentSessionParams;
  agentDir: string;
  contextEngineSessionKey?: string;
  harnessRuntime?: string;
  contextEnginePluginId?: string;
  contextTokenBudget?: number;
}): ContextEngineRuntimeContext {
  const { sessionFile: _sessionFile, contextEngineAgentId, ...runtimeParams } = params.params;
  return {
    ...runtimeParams,
    sessionTarget: projectQueuedCompactionSessionTarget(params.params),
    ...buildEmbeddedCompactionRuntimeContext({
      ...params.params,
      agentDir: params.agentDir,
      modelId: params.params.model,
      harnessRuntime: params.harnessRuntime,
    }),
    ...resolveContextEngineCapabilities({
      config: params.params.config,
      sessionKey: params.contextEngineSessionKey ?? params.params.sessionKey,
      explicitAgentId: contextEngineAgentId,
      authProfileId: params.params.authProfileId,
      contextEnginePluginId: params.contextEnginePluginId,
      purpose: "context-engine.compaction",
    }),
    tokenBudget: params.contextTokenBudget,
    currentTokenCount: params.params.currentTokenCount,
  };
}