@capybara-hq/kernel 0.1.0-rc.109 → 0.1.0-rc.110

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 (51) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/background/wake-rules.js +2 -0
  3. package/dist/conversations/conversations.service.js +4 -2
  4. package/dist/conversations/event-log.js +11 -1
  5. package/dist/conversations/events.d.ts +5 -0
  6. package/dist/conversations/events.js +11 -2
  7. package/dist/conversations/prompt-suggestion-store.d.ts +3 -1
  8. package/dist/conversations/prompt-suggestion-store.js +5 -1
  9. package/dist/db/kernel-schema.d.ts +7 -0
  10. package/dist/identity/accounts.d.ts +8 -9
  11. package/dist/identity/accounts.js +18 -3
  12. package/dist/identity/me.controller.d.ts +4 -2
  13. package/dist/identity/me.controller.js +4 -2
  14. package/dist/identity/me.schemas.d.ts +3 -0
  15. package/dist/identity/me.schemas.js +5 -0
  16. package/dist/identity/settings.d.ts +15 -0
  17. package/dist/identity/settings.js +12 -0
  18. package/dist/infra/outbox/registry.d.ts +14 -0
  19. package/dist/infra/outbox/registry.js +14 -0
  20. package/dist/orgs/settings.service.d.ts +6 -0
  21. package/dist/platform/ops/org-settings.ops.js +1 -1
  22. package/dist/platform/ops/platform.ops.js +9 -3
  23. package/dist/push/recipients.js +4 -2
  24. package/dist/runtime/abort.d.ts +22 -3
  25. package/dist/runtime/abort.js +37 -17
  26. package/dist/runtime/compaction.service.d.ts +43 -12
  27. package/dist/runtime/compaction.service.js +60 -16
  28. package/dist/runtime/context/idle-compaction-rules.d.ts +94 -0
  29. package/dist/runtime/context/idle-compaction-rules.js +84 -0
  30. package/dist/runtime/idle-arm.d.ts +38 -0
  31. package/dist/runtime/idle-arm.js +269 -0
  32. package/dist/runtime/idle-compaction-jobs.d.ts +25 -0
  33. package/dist/runtime/idle-compaction-jobs.js +21 -0
  34. package/dist/runtime/idle-compaction.d.ts +43 -0
  35. package/dist/runtime/idle-compaction.js +316 -0
  36. package/dist/runtime/idle-return.d.ts +62 -0
  37. package/dist/runtime/idle-return.js +170 -0
  38. package/dist/runtime/maintenance.d.ts +5 -2
  39. package/dist/runtime/maintenance.js +14 -4
  40. package/dist/runtime/model-call.d.ts +113 -5
  41. package/dist/runtime/model-call.js +119 -71
  42. package/dist/runtime/run-finish.d.ts +16 -1
  43. package/dist/runtime/run-finish.js +27 -4
  44. package/dist/runtime/run-queue.d.ts +56 -2
  45. package/dist/runtime/run-queue.js +257 -8
  46. package/dist/runtime/run-worker.d.ts +22 -8
  47. package/dist/runtime/run-worker.js +75 -28
  48. package/dist/runtime/runtime.module.js +11 -0
  49. package/dist/runtime/waits.js +1 -1
  50. package/package.json +1 -1
  51. package/src/migrations/0195_idle_compaction.sql +7 -0
@@ -0,0 +1,62 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import type { KernelLogger } from "../log.js";
3
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
4
+ import { idleMinTokens } from "./context/idle-compaction-rules.js";
5
+ import { ProviderRegistry } from "./providers.js";
6
+ /** A return to a conversation is logged when the gap since its previous run ended exceeds this. */
7
+ export declare const IDLE_RETURN_GAP_MS: number;
8
+ export interface IdleReturnInput {
9
+ /** When this run started, epoch ms. */
10
+ startedAt: number;
11
+ /** The previous run's `finished_at`, epoch ms. */
12
+ previousFinishedAt: number;
13
+ /** The previous run's last step call; null when it had none. */
14
+ lastCall: {
15
+ window: number;
16
+ input: number;
17
+ cacheRead: number;
18
+ cacheWrite: number;
19
+ output: number;
20
+ /** The call's recorded `cacheTtl`. */
21
+ recordedTtl: number | undefined;
22
+ /** The model's declared default lifetime. */
23
+ defaultTtl: number | undefined;
24
+ } | null;
25
+ /** A `compaction_summary` of an idle compact run was written after `previousFinishedAt`. */
26
+ idleSummary: boolean;
27
+ settings: Parameters<typeof idleMinTokens>[1];
28
+ }
29
+ export interface IdleReturnFacts {
30
+ gapMs: number;
31
+ contextTokens: number;
32
+ threshold: number;
33
+ /** The previous run's last call's cache lifetime in seconds; null when none is known. */
34
+ ttl: number | null;
35
+ idleSummary: boolean;
36
+ }
37
+ /**
38
+ * The facts of an `idle_return` log line (idle compaction spec S11), or null when the return does
39
+ * not qualify: a gap of at most 30 minutes, no step call, or a context below the size threshold.
40
+ * Cache lifetimes shorter than 30 minutes are included on purpose: they show the opportunities the
41
+ * 30-minute rule leaves out.
42
+ */
43
+ export declare function idleReturnFacts(i: IdleReturnInput): IdleReturnFacts | null;
44
+ /**
45
+ * Logs one `info` line (`idle_return`, context=IdleCompaction) when a chat run starts on a
46
+ * conversation that sat idle past the cache lifetimes idle compaction aims at, so the first weeks
47
+ * of production show how often people return and what the compaction would have saved (spec §10).
48
+ * Best effort: never throws.
49
+ */
50
+ export declare class IdleReturn {
51
+ private readonly kdb;
52
+ private readonly compaction;
53
+ private readonly models;
54
+ private readonly log;
55
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, models: Pick<ProviderRegistry, "resolve">, log: Pick<KernelLogger, "info" | "debug">);
56
+ /** Outside any transaction (the model registry may list models over the network). */
57
+ record(conv: {
58
+ id: string;
59
+ org_id: string;
60
+ }, runId: string, now?: number): Promise<void>;
61
+ private recordOrThrow;
62
+ }
@@ -0,0 +1,170 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
14
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
15
+ import { trustedCache } from "./context/cache-ttl.js";
16
+ import { IDLE_MIN_CACHE_TTL, idleMinTokens } from "./context/idle-compaction-rules.js";
17
+ import { ProviderRegistry } from "./providers.js";
18
+ /** A return to a conversation is logged when the gap since its previous run ended exceeds this. */
19
+ export const IDLE_RETURN_GAP_MS = IDLE_MIN_CACHE_TTL * 1000;
20
+ /**
21
+ * The facts of an `idle_return` log line (idle compaction spec S11), or null when the return does
22
+ * not qualify: a gap of at most 30 minutes, no step call, or a context below the size threshold.
23
+ * Cache lifetimes shorter than 30 minutes are included on purpose: they show the opportunities the
24
+ * 30-minute rule leaves out.
25
+ */
26
+ export function idleReturnFacts(i) {
27
+ const gapMs = i.startedAt - i.previousFinishedAt;
28
+ if (gapMs <= IDLE_RETURN_GAP_MS || i.lastCall === null)
29
+ return null;
30
+ const c = i.lastCall;
31
+ const contextTokens = c.input + c.cacheRead + c.cacheWrite + c.output;
32
+ const threshold = idleMinTokens(c.window, i.settings);
33
+ if (contextTokens < threshold)
34
+ return null;
35
+ return {
36
+ gapMs,
37
+ contextTokens,
38
+ threshold,
39
+ ttl: c.recordedTtl ?? c.defaultTtl ?? null,
40
+ idleSummary: i.idleSummary,
41
+ };
42
+ }
43
+ /**
44
+ * Logs one `info` line (`idle_return`, context=IdleCompaction) when a chat run starts on a
45
+ * conversation that sat idle past the cache lifetimes idle compaction aims at, so the first weeks
46
+ * of production show how often people return and what the compaction would have saved (spec §10).
47
+ * Best effort: never throws.
48
+ */
49
+ let IdleReturn = class IdleReturn {
50
+ kdb;
51
+ compaction;
52
+ models;
53
+ log;
54
+ constructor(kdb, compaction, models, log) {
55
+ this.kdb = kdb;
56
+ this.compaction = compaction;
57
+ this.models = models;
58
+ this.log = log;
59
+ }
60
+ /** Outside any transaction (the model registry may list models over the network). */
61
+ async record(conv, runId, now = Date.now()) {
62
+ try {
63
+ await this.recordOrThrow(conv, runId, now);
64
+ }
65
+ catch (err) {
66
+ this.log.debug("idle return not logged", {
67
+ context: "IdleCompaction",
68
+ conversationId: conv.id,
69
+ runId,
70
+ err,
71
+ });
72
+ }
73
+ }
74
+ async recordOrThrow(conv, runId, now) {
75
+ const t = this.kdb.db;
76
+ const prev = await t
77
+ .selectFrom("runs")
78
+ .select(["id", "finished_at"])
79
+ .where("conversation_id", "=", conv.id)
80
+ .where("compact", "=", false)
81
+ .where("id", "!=", runId)
82
+ .where("finished_at", "is not", null)
83
+ .orderBy("finished_at", "desc")
84
+ .limit(1)
85
+ .executeTakeFirst();
86
+ if (prev?.finished_at == null)
87
+ return;
88
+ const finishedAt = prev.finished_at.getTime();
89
+ if (now - finishedAt <= IDLE_RETURN_GAP_MS)
90
+ return;
91
+ // the previous run's last step usage (a side call's usage carries a `purpose`)
92
+ const usageRow = await t
93
+ .selectFrom("conversation_events")
94
+ .select("payload")
95
+ .where("conversation_id", "=", conv.id)
96
+ .where("run_id", "=", prev.id)
97
+ .where("type", "=", "usage")
98
+ .where(sql `payload->>'purpose' IS NULL`)
99
+ .orderBy("seq", "desc")
100
+ .limit(1)
101
+ .executeTakeFirst();
102
+ const usage = usageRow?.payload;
103
+ let lastCall = null;
104
+ if (usage !== undefined) {
105
+ const call = await t
106
+ .selectFrom("conversation_events")
107
+ .select("payload")
108
+ .where("conversation_id", "=", conv.id)
109
+ .where("run_id", "=", prev.id)
110
+ .where("type", "=", "model_call")
111
+ .where(sql `(payload->>'step')::int`, "=", usage.step)
112
+ .orderBy("seq", "desc")
113
+ .limit(1)
114
+ .executeTakeFirst();
115
+ const { info } = await this.models.resolve(conv.org_id, {
116
+ provider: usage.provider,
117
+ model: usage.model,
118
+ });
119
+ lastCall = {
120
+ window: info.contextWindow,
121
+ input: usage.inputTokens,
122
+ cacheRead: usage.cacheReadTokens,
123
+ cacheWrite: usage.cacheWriteTokens,
124
+ output: usage.outputTokens,
125
+ recordedTtl: call?.payload?.request
126
+ ?.cacheTtl,
127
+ defaultTtl: trustedCache(info.cache)?.defaultTtl,
128
+ };
129
+ }
130
+ const settings = await this.compaction.resolve(conv.org_id);
131
+ const facts = idleReturnFacts({
132
+ startedAt: now,
133
+ previousFinishedAt: finishedAt,
134
+ lastCall,
135
+ idleSummary: false,
136
+ settings,
137
+ });
138
+ if (facts === null)
139
+ return;
140
+ const summary = await t
141
+ .selectFrom("conversation_events as e")
142
+ .innerJoin("runs as r", "r.id", "e.run_id")
143
+ .select("e.seq")
144
+ .where("e.conversation_id", "=", conv.id)
145
+ .where("e.type", "=", "compaction_summary")
146
+ .where("e.created_at", ">", prev.finished_at)
147
+ .where("r.compact_origin", "=", "idle")
148
+ .limit(1)
149
+ .executeTakeFirst();
150
+ this.log.info("idle_return", {
151
+ context: "IdleCompaction",
152
+ orgId: conv.org_id,
153
+ conversationId: conv.id,
154
+ runId,
155
+ gapMs: facts.gapMs,
156
+ contextTokens: facts.contextTokens,
157
+ threshold: facts.threshold,
158
+ ttl: facts.ttl,
159
+ idleSummary: summary !== undefined,
160
+ });
161
+ }
162
+ };
163
+ IdleReturn = __decorate([
164
+ Injectable(),
165
+ __param(0, Inject(KernelDb)),
166
+ __param(1, Inject(CompactionSettingsService)),
167
+ __param(2, Inject(ProviderRegistry)),
168
+ __param(3, Inject(KERNEL_LOGGER))
169
+ ], IdleReturn);
170
+ export { IdleReturn };
@@ -19,6 +19,7 @@ import { ShareObjects } from "../shares/share-objects.js";
19
19
  import { PlatformIconObjects } from "../themes/platform-icon-objects.js";
20
20
  import { ToolDrift } from "../tools/drift.js";
21
21
  import { PermissionApprovalJobs } from "../tools/permission-approval-jobs.js";
22
+ import { IdleCompactionJob } from "./idle-compaction.js";
22
23
  import { RunDeletion } from "./run-deletion.js";
23
24
  import { RunQueue } from "./run-queue.js";
24
25
  import { Waits } from "./waits.js";
@@ -35,7 +36,8 @@ export declare const MAINTENANCE_CONCURRENCY = 5;
35
36
  * {@link OwnedPluginCleanup}, `automation-fire` and `automation-settle` → {@link AutomationFirer}, `automation-coalesce` → {@link EventCoalescer}, `share-object-delete` → {@link ShareObjects}, `blob-delete`, `file-staging-delete` and `file-release` →
36
37
  * {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
37
38
  * `file-library-backfill` → {@link FileLibraryBackfill}, `platform-icon-delete` →
38
- * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
39
+ * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
40
+ * `idle-compaction` → {@link IdleCompactionJob}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
39
41
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
40
42
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
41
43
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -63,8 +65,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
63
65
  private readonly notices;
64
66
  private readonly triggers;
65
67
  private readonly coalescer;
68
+ private readonly idleCompaction;
66
69
  private readonly snapshots?;
67
- constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, backfill: Pick<FileLibraryBackfill, "run">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
70
+ constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, backfill: Pick<FileLibraryBackfill, "run">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
68
71
  process(job: Job, token?: string): Promise<void>;
69
72
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
70
73
  start(): void;
@@ -46,6 +46,8 @@ import { ToolDrift } from "../tools/drift.js";
46
46
  import { DRIFT_CONNECTOR_JOB } from "../tools/job-ids.js";
47
47
  import { PermissionApprovalJobs, } from "../tools/permission-approval-jobs.js";
48
48
  import { ToolsModule } from "../tools/tools.module.js";
49
+ import { IdleCompactionJob } from "./idle-compaction.js";
50
+ import { IDLE_COMPACTION_JOB } from "./idle-compaction-jobs.js";
49
51
  import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
50
52
  import { RunDeletion, STOP_DELETED_ORG_JOB } from "./run-deletion.js";
51
53
  import { ENSURE_RUN_JOB, RunQueue } from "./run-queue.js";
@@ -65,7 +67,8 @@ export const MAINTENANCE_CONCURRENCY = 5;
65
67
  * {@link OwnedPluginCleanup}, `automation-fire` and `automation-settle` → {@link AutomationFirer}, `automation-coalesce` → {@link EventCoalescer}, `share-object-delete` → {@link ShareObjects}, `blob-delete`, `file-staging-delete` and `file-release` →
66
68
  * {@link BlobObjects}, `file-library-hash`, `file-library-hash-org` → {@link FileLibraryHashJob},
67
69
  * `file-library-backfill` → {@link FileLibraryBackfill}, `platform-icon-delete` →
68
- * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
70
+ * {@link PlatformIconObjects}, `device-conversation-notice` → {@link ConversationNoticeDelivery},
71
+ * `idle-compaction` → {@link IdleCompactionJob}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
69
72
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
70
73
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
71
74
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -93,8 +96,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
93
96
  notices;
94
97
  triggers;
95
98
  coalescer;
99
+ idleCompaction;
96
100
  snapshots;
97
- constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, automations, scheduled, log, operations, shareObjects, blobObjects, hashing, backfill, platformIcons, notices, triggers, coalescer, snapshots) {
101
+ constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, automations, scheduled, log, operations, shareObjects, blobObjects, hashing, backfill, platformIcons, notices, triggers, coalescer, idleCompaction, snapshots) {
98
102
  super();
99
103
  this.permissionApprovals = permissionApprovals;
100
104
  this.waits = waits;
@@ -117,6 +121,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
117
121
  this.notices = notices;
118
122
  this.triggers = triggers;
119
123
  this.coalescer = coalescer;
124
+ this.idleCompaction = idleCompaction;
120
125
  this.snapshots = snapshots;
121
126
  }
122
127
  process(job, token) {
@@ -260,6 +265,10 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
260
265
  await this.notices.attempt(orgId, noticeId, { timeoutMs: NOTICE_PROMPT_TIMEOUT_MS });
261
266
  return;
262
267
  }
268
+ // a large idle conversation's compaction before its prompt cache expires (idle compaction §4.3)
269
+ case IDLE_COMPACTION_JOB:
270
+ await this.idleCompaction.fire(job.data);
271
+ return;
263
272
  default:
264
273
  if (await this.scheduled.runNow(job.name))
265
274
  return;
@@ -305,8 +314,9 @@ MaintenanceProcessor = __decorate([
305
314
  __param(18, Inject(ConversationNoticeDelivery)),
306
315
  __param(19, Inject(TriggerDispatcher)),
307
316
  __param(20, Inject(EventCoalescer)),
308
- __param(21, Optional()),
309
- __param(21, Inject(CloudPermissionSnapshots))
317
+ __param(21, Inject(IdleCompactionJob)),
318
+ __param(22, Optional()),
319
+ __param(22, Inject(CloudPermissionSnapshots))
310
320
  ], MaintenanceProcessor);
311
321
  export { MaintenanceProcessor };
312
322
  /**
@@ -11,6 +11,7 @@ import type { CompactionProgressSink } from "./compaction-progress.js";
11
11
  import type { CompactionSettings, CompactionSettingsService } from "./compaction-settings.service.js";
12
12
  import { type BuildModelRequestInput, type MediaBytes, type MediaInfo, type ModelCallMeta, type RequestTool } from "./context/build.js";
13
13
  import { type FitPlan } from "./context/fit.js";
14
+ import { type InContextSkip } from "./context/in-context-compaction.js";
14
15
  import { type ConversationKindForHooks, type HookRunner } from "./hook-calls.js";
15
16
  import type { SubagentParent } from "./loop.js";
16
17
  import { MediaCache } from "./media-cache.js";
@@ -371,8 +372,8 @@ export declare function assembleModelRequest(input: AssembleModelRequestInput):
371
372
  meta: ModelCallMeta;
372
373
  mediaTokens: number;
373
374
  };
374
- /** Options of {@link maybeCompact}. */
375
- interface CompactOptions {
375
+ /** Options of {@link runCompaction} and {@link prepareCompaction}. */
376
+ export interface CompactOptions {
376
377
  /**
377
378
  * The reactive path (context compaction spec §4.4): summarise regardless of the trigger,
378
379
  * `enabled: false` and the failure backoff. A proactive call leaves all of them in force.
@@ -399,6 +400,12 @@ interface CompactOptions {
399
400
  * reactive path sets it, since its last request is the one that overflowed.
400
401
  */
401
402
  transcriptOnly?: boolean;
403
+ /**
404
+ * The idle compact run (idle compaction spec §4.3 check 9): an in-context skip ends the
405
+ * compaction with nothing written; never the transcript request. Implies nothing about `manual`
406
+ * (ruling R13: a manual compaction is transcript-only, so the idle run never sets it).
407
+ */
408
+ requireInContext?: boolean;
402
409
  }
403
410
  /** What one compaction execution wrote: the events, the summary's seq and whether it failed. */
404
411
  export interface CompactionOutcome {
@@ -409,6 +416,105 @@ export interface CompactionOutcome {
409
416
  /** Whether a `compaction_failed` was written (a failed call, a denial or a failed acceptance). */
410
417
  failed: boolean;
411
418
  }
419
+ /**
420
+ * Why a compaction summarizes the transcript instead of the in-context request (idle compaction
421
+ * spec §9.4): the builder's skips, plus the runtime's own reasons. Logged as a `debug` line with
422
+ * `context=Compaction`.
423
+ */
424
+ export type InContextFallback = InContextSkip
425
+ /**
426
+ * `CompactOptions.manual`: a manual compact run keeps the #990 plan on the transcript path
427
+ * (ruling R13).
428
+ */
429
+ | "manual"
430
+ /** `CompactOptions.transcriptOnly` (the reactive path: its last request overflowed). */
431
+ | "transcript_only"
432
+ /** The model is not in the quality-gate table ({@link inContextSummaryAllowed}). */
433
+ | "quality_gate"
434
+ /** No `ModelStepDeps.liveSnapshot` (eval replays). */
435
+ | "no_snapshot"
436
+ /** No agent id on the step input, or a last call without a run. */
437
+ | "no_agent" | "snapshot_failed"
438
+ /** The builder threw (a bug: it never throws for a snapshot's content). */
439
+ | "build_failed"
440
+ /** Boundary mode `all` would cover less than the plan: a covered message is not absorbed. */
441
+ | "covers_unabsorbed"
442
+ /**
443
+ * Input the model has not answered follows the last reply (ruling R9, {@link
444
+ * unansweredAfterReply}): a tool result, or an absorbed message other than a run opener.
445
+ */
446
+ | "pending_input";
447
+ /** The in-context summary call of one compaction. */
448
+ export interface InContextSummary {
449
+ request: ModelRequest;
450
+ /** The same request with the retry note, sent after a reply cut off at the output limit. */
451
+ retryRequest: ModelRequest;
452
+ /** What the summary covers (boundary mode `all`: every event the request includes). */
453
+ coversUpToSeq: number;
454
+ /** The unanswered run openers re-rendered after the summary ({@link unansweredOpeners}). */
455
+ opening: number[];
456
+ }
457
+ /**
458
+ * What {@link prepareCompaction} decided and built for one compaction, written nowhere: the call
459
+ * part of {@link runCompaction} sends it, `CompactionService.probeIdle` only reads it (idle
460
+ * compaction spec §4.3 checks 8 and 9).
461
+ */
462
+ export interface PreparedCompaction {
463
+ provider: BoundProvider;
464
+ info: ModelInfo;
465
+ /** The model the compaction summarizes with (`opts.ref` or the agent's main model). */
466
+ ref: ModelRef;
467
+ /** The calibrated estimate of the next step's request (what the trigger compares). */
468
+ estimate: number;
469
+ /** The model's context window. */
470
+ window: number;
471
+ /** The estimated tokens of the plan's transcript: what no summary covers yet. */
472
+ growthTokens: number;
473
+ plan: {
474
+ coversUpToSeq: number;
475
+ transcript: string;
476
+ };
477
+ /** Whether the manual rule planned it (`opts.manual`). */
478
+ manual: boolean;
479
+ /** The summary call's output cap (context compaction spec §4.8). */
480
+ summaryCap: number;
481
+ /** The in-context summary request, or why the compaction would summarize the transcript. */
482
+ inContext: InContextSummary | {
483
+ skip: InContextFallback;
484
+ };
485
+ }
486
+ /** Why {@link prepareCompaction} found no compaction to run. */
487
+ export type CompactionPrepareSkip =
488
+ /** Below the proactive trigger (never with `force`). */
489
+ {
490
+ skipped: "trigger";
491
+ }
492
+ /** The failure backoff holds a proactive attempt (never with `force`). */
493
+ | {
494
+ skipped: "backoff";
495
+ }
496
+ /** Nothing precedes the kept tail. */
497
+ | {
498
+ skipped: "no_plan";
499
+ estimate: number;
500
+ window: number;
501
+ }
502
+ /** The model or the attachment storage cannot be reached right now. */
503
+ | {
504
+ skipped: "unavailable";
505
+ reason: string;
506
+ };
507
+ /**
508
+ * The preparation of one compaction (idle compaction spec §4.3): resolve the model, load the media,
509
+ * build the next step's request and calibrate its estimate, apply the trigger and the backoff (unless
510
+ * `opts.force`), plan, and build the in-context summary request ({@link inContextSummary}). It writes
511
+ * nothing and sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
512
+ * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs once
513
+ * the plan exists, before the in-context build reads the live snapshot.
514
+ */
515
+ export declare function prepareCompaction(deps: ModelStepDeps, input: ModelStepInput, events: ConversationEvent[], runtime: Runtime, compaction: CompactionSettings, tools: StepTools, opts?: CompactOptions, hooks?: {
516
+ planned?: () => void;
517
+ }): Promise<PreparedCompaction | CompactionPrepareSkip>;
412
518
  /**
413
519
  * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
414
520
  * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
@@ -420,10 +526,12 @@ export interface CompactionOutcome {
420
526
  *
421
527
  * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
422
528
  * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
423
- * than the agent's main model.
529
+ * than the agent's main model. `opts.requireInContext` (the idle compact run, idle compaction spec
530
+ * §4.3) ends the compaction with nothing written when the in-context summary does not apply.
424
531
  *
425
- * The one execution both paths run: the automatic step path through {@link maybeCompact} and a
426
- * manual compact run through `CompactionService.force`.
532
+ * The one execution every path runs: the automatic step path through {@link maybeCompact} and a
533
+ * compact run (manual or idle) through `CompactionService.force`. The preparation is
534
+ * {@link prepareCompaction}; this adds the outcomes a manual run records and the call part.
427
535
  */
428
536
  export declare function runCompaction(deps: ModelStepDeps, input: ModelStepInput, events: ConversationEvent[], runtime: Runtime, compaction: CompactionSettings, tools: StepTools, opts?: CompactOptions): Promise<CompactionOutcome>;
429
537
  /** Characters one streamed delta carries, for the idle and size accounting of a stream. */