@capybara-hq/kernel 0.1.0-rc.114 → 0.1.0-rc.115

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 (35) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/conversations/events.d.ts +8 -0
  4. package/dist/conversations/events.js +11 -0
  5. package/dist/db/kernel-schema.d.ts +3 -0
  6. package/dist/identity/settings.d.ts +5 -0
  7. package/dist/identity/settings.js +4 -0
  8. package/dist/models/purposes.js +5 -0
  9. package/dist/orgs/settings.service.d.ts +2 -0
  10. package/dist/platform/ops/org-settings.ops.js +1 -1
  11. package/dist/runtime/compaction-model.d.ts +57 -0
  12. package/dist/runtime/compaction-model.js +87 -0
  13. package/dist/runtime/compaction.service.d.ts +23 -8
  14. package/dist/runtime/compaction.service.js +15 -10
  15. package/dist/runtime/context/compaction.d.ts +19 -2
  16. package/dist/runtime/context/compaction.js +23 -2
  17. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  18. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  19. package/dist/runtime/idle-arm.d.ts +12 -2
  20. package/dist/runtime/idle-arm.js +66 -18
  21. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  22. package/dist/runtime/idle-compaction.d.ts +11 -3
  23. package/dist/runtime/idle-compaction.js +61 -30
  24. package/dist/runtime/model-call.d.ts +52 -16
  25. package/dist/runtime/model-call.js +71 -24
  26. package/dist/runtime/run-finish.d.ts +12 -3
  27. package/dist/runtime/run-finish.js +14 -7
  28. package/dist/runtime/run-queue.d.ts +5 -2
  29. package/dist/runtime/run-queue.js +7 -4
  30. package/dist/runtime/run-steps.d.ts +4 -1
  31. package/dist/runtime/run-steps.js +9 -2
  32. package/dist/runtime/run-worker.js +4 -2
  33. package/dist/runtime/runtime.module.js +3 -0
  34. package/package.json +1 -1
  35. package/src/migrations/0200_runs_idle_mode.sql +4 -0
@@ -34,21 +34,36 @@ export function idleArmDecision(f) {
34
34
  return { arm: false, reason: "disabled" };
35
35
  if (f.personalOff)
36
36
  return { arm: false, reason: "personal_off" };
37
- if (f.expiry === null || f.lastCall === null)
37
+ const cache = f.mode === "cache";
38
+ if (cache && (f.expiry === null || f.lastCall === null)) {
38
39
  return { arm: false, reason: "no_cache" };
39
- if (f.expiry.ttl < IDLE_MIN_CACHE_TTL)
40
+ }
41
+ if (cache && f.expiry !== null && f.expiry.ttl < IDLE_MIN_CACHE_TTL) {
40
42
  return { arm: false, reason: "short_ttl" };
43
+ }
41
44
  const c = f.lastCall;
45
+ if (c === null)
46
+ return { arm: false, reason: "small" };
42
47
  if (c.input + c.cacheRead + c.cacheWrite + c.output < idleMinTokens(c.window, f.settings)) {
43
48
  return { arm: false, reason: "small" };
44
49
  }
50
+ if (!cache) {
51
+ return {
52
+ arm: true,
53
+ mode: "compaction_model",
54
+ runAt: f.now + f.settings.idleDelayMinutes * 60_000,
55
+ };
56
+ }
45
57
  if (!f.inContextAllowed)
46
58
  return { arm: false, reason: "quality_gate" };
47
59
  if (f.fitPlan)
48
60
  return { arm: false, reason: "fit_plan" };
49
61
  if (!f.settled)
50
62
  return { arm: false, reason: "unsettled" };
63
+ if (f.expiry === null)
64
+ return { arm: false, reason: "no_cache" };
51
65
  return {
66
+ mode: "cache",
52
67
  arm: true,
53
68
  runAt: f.expiry.fireAt,
54
69
  expiresAt: f.expiry.expiresAt,
@@ -65,11 +80,11 @@ export function idleFireDecision(f) {
65
80
  return { fire: false, outcome: "busy" };
66
81
  if (!f.enabled)
67
82
  return { fire: false, outcome: "disabled" };
68
- if (f.now >= f.expiresAt - CACHE_EXPIRY_MARGIN_MS)
83
+ if (f.mode === "cache" && f.now >= f.expiresAt - CACHE_EXPIRY_MARGIN_MS)
69
84
  return { fire: false, outcome: "expired" };
70
85
  if (f.backoff)
71
86
  return { fire: false, outcome: "backoff" };
72
- if (!f.sameModel)
87
+ if (!f.modelReady)
73
88
  return { fire: false, outcome: "no_model" };
74
89
  const p = f.probe;
75
90
  if (p === null ||
@@ -78,7 +93,7 @@ export function idleFireDecision(f) {
78
93
  p.growth < IDLE_MIN_GROWTH_TOKENS) {
79
94
  return { fire: false, outcome: "small" };
80
95
  }
81
- if (!f.inContext)
96
+ if (f.mode === "cache" && !f.inContext)
82
97
  return { fire: false, outcome: "no_prefix" };
83
98
  return { fire: true };
84
99
  }
@@ -2,6 +2,7 @@ import type { ConversationKind } from "../db/kernel-schema.js";
2
2
  import { AccountsService } from "../identity/accounts.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import type { KernelLogger } from "../log.js";
5
+ import { ModelPurposesService } from "../models/purposes.js";
5
6
  import { CompactionSettingsService } from "./compaction-settings.service.js";
6
7
  import { type IdleArmFacts } from "./context/idle-compaction-rules.js";
7
8
  import { ProviderRegistry } from "./providers.js";
@@ -12,7 +13,12 @@ export type IdleArmOutcome = IdleArmFacts["outcome"];
12
13
  * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
13
14
  * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
14
15
  * transaction owes an `idle-compaction` job. The run worker calls it before `RunFinish.finish`,
15
- * outside any transaction (the model registry may list a provider's models over the network).
16
+ * outside any transaction (the model registry and the `compaction` purpose may list a provider's
17
+ * models over the network).
18
+ *
19
+ * The job's mode (compaction model spec §6.1, §6.2): `compaction_model` when the summarizer a
20
+ * compaction would choose now against the last step call's model is the compaction model (usable
21
+ * and eligible, the same `chooseSummarizer` the compaction runs), else `cache`.
16
22
  */
17
23
  export declare class IdleArm {
18
24
  private readonly kdb;
@@ -20,7 +26,9 @@ export declare class IdleArm {
20
26
  private readonly accounts;
21
27
  private readonly models;
22
28
  private readonly log;
23
- constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, log: Pick<KernelLogger, "debug" | "warn">);
29
+ /** The org's `compaction` purpose, read from PG on every decision (nothing cached). */
30
+ private readonly compactionModel;
31
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, purposes: Pick<ModelPurposesService, "resolve">, log: KernelLogger);
24
32
  /**
25
33
  * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
26
34
  * Never throws: any failure is logged at `warn` and arms nothing, so arming never fails or holds
@@ -35,4 +43,6 @@ export declare class IdleArm {
35
43
  account_id: string | null;
36
44
  }, outcome: IdleArmOutcome): Promise<IdleCompactionIntent | undefined>;
37
45
  private decideOrSkip;
46
+ /** The final decision over every fact gathered: the intent, or undefined with the skip logged. */
47
+ private armed;
38
48
  }
@@ -12,9 +12,11 @@ import { AccountsService } from "../identity/accounts.js";
12
12
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
14
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ import { ModelPurposesService } from "../models/purposes.js";
16
+ import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
15
17
  import { CompactionSettingsService } from "./compaction-settings.service.js";
16
18
  import { deriveCacheExpiry } from "./context/cache-expiry.js";
17
- import { idleArmDecision, } from "./context/idle-compaction-rules.js";
19
+ import { idleArmDecision, idleMinTokens, } from "./context/idle-compaction-rules.js";
18
20
  import { inContextSummaryAllowed, unansweredAfterReply } from "./context/in-context-compaction.js";
19
21
  import { ProviderRegistry } from "./providers.js";
20
22
  /**
@@ -28,6 +30,8 @@ const PASSING = {
28
30
  automationRunId: null,
29
31
  outcome: "completed",
30
32
  settings: COMPACTION_SETTINGS.parse({}),
33
+ mode: "cache",
34
+ now: 0,
31
35
  personalOff: false,
32
36
  expiry: {
33
37
  callSeq: 0,
@@ -71,7 +75,12 @@ const modelKey = (provider, model) => `${provider}\u0000${model}`;
71
75
  * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
72
76
  * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
73
77
  * transaction owes an `idle-compaction` job. The run worker calls it before `RunFinish.finish`,
74
- * outside any transaction (the model registry may list a provider's models over the network).
78
+ * outside any transaction (the model registry and the `compaction` purpose may list a provider's
79
+ * models over the network).
80
+ *
81
+ * The job's mode (compaction model spec §6.1, §6.2): `compaction_model` when the summarizer a
82
+ * compaction would choose now against the last step call's model is the compaction model (usable
83
+ * and eligible, the same `chooseSummarizer` the compaction runs), else `cache`.
75
84
  */
76
85
  let IdleArm = class IdleArm {
77
86
  kdb;
@@ -79,12 +88,15 @@ let IdleArm = class IdleArm {
79
88
  accounts;
80
89
  models;
81
90
  log;
82
- constructor(kdb, compaction, accounts, models, log) {
91
+ /** The org's `compaction` purpose, read from PG on every decision (nothing cached). */
92
+ compactionModel;
93
+ constructor(kdb, compaction, accounts, models, purposes, log) {
83
94
  this.kdb = kdb;
84
95
  this.compaction = compaction;
85
96
  this.accounts = accounts;
86
97
  this.models = models;
87
98
  this.log = log;
99
+ this.compactionModel = compactionModelPort(purposes);
88
100
  }
89
101
  /**
90
102
  * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
@@ -144,7 +156,8 @@ let IdleArm = class IdleArm {
144
156
  reason = failing();
145
157
  if (reason !== undefined)
146
158
  return skip(reason);
147
- known.settings = await this.compaction.resolve(conv.org_id);
159
+ const settings = await this.compaction.resolve(conv.org_id);
160
+ known.settings = settings;
148
161
  reason = failing();
149
162
  if (reason !== undefined)
150
163
  return skip(reason);
@@ -162,23 +175,44 @@ let IdleArm = class IdleArm {
162
175
  .where("type", "in", ["model_call", "usage"])
163
176
  .orderBy("seq")
164
177
  .execute()).map(toEvent);
165
- const infos = new Map();
178
+ const resolved = new Map();
166
179
  for (const e of calls) {
167
180
  if (e.type !== "model_call")
168
181
  continue;
169
182
  const key = modelKey(e.payload.provider, e.payload.model);
170
- if (infos.has(key))
183
+ if (resolved.has(key))
171
184
  continue;
172
- const { info } = await this.models.resolve(conv.org_id, {
185
+ resolved.set(key, await this.models.resolve(conv.org_id, {
173
186
  provider: e.payload.provider,
174
187
  model: e.payload.model,
175
- });
176
- infos.set(key, info);
188
+ }));
177
189
  }
178
- const infoOf = (provider, model) => infos.get(modelKey(provider, model));
179
- known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
190
+ const infoOf = (provider, model) => resolved.get(modelKey(provider, model))?.info;
180
191
  const last = lastStepCall(calls);
181
- const lastInfo = last && infoOf(last.call.payload.provider, last.call.payload.model);
192
+ const lastModel = last && resolved.get(modelKey(last.call.payload.provider, last.call.payload.model));
193
+ const lastInfo = lastModel?.info;
194
+ // a context under the size floor arms in neither mode: skip before the purpose read (and the
195
+ // summarizer choice's fallback warnings) a small finish would otherwise pay every time
196
+ if (last !== undefined && lastInfo !== undefined) {
197
+ const u = last.usage.payload;
198
+ const total = u.inputTokens + u.cacheReadTokens + u.cacheWriteTokens + u.outputTokens;
199
+ if (total < idleMinTokens(lastInfo.contextWindow, settings))
200
+ return skip("small");
201
+ }
202
+ // compaction model spec §6.1, C2: the mode is the summarizer a compaction would choose now,
203
+ // V = the last step call's model under the effective settings; a failed purpose read throws
204
+ // (no job, logged by `decide`)
205
+ if (last !== undefined && lastModel !== undefined) {
206
+ const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, conv.org_id, {
207
+ ref: { provider: last.call.payload.provider, model: last.call.payload.model },
208
+ provider: lastModel.provider,
209
+ info: lastModel.info,
210
+ }, settings);
211
+ known.mode = summarizer.source === "compaction_model" ? "compaction_model" : "cache";
212
+ }
213
+ // C4: the run's end is not written yet; the terminal transaction follows within milliseconds
214
+ known.now = Date.now();
215
+ known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
182
216
  known.lastCall =
183
217
  last && lastInfo
184
218
  ? {
@@ -195,6 +229,8 @@ let IdleArm = class IdleArm {
195
229
  if (reason !== undefined || last === undefined || lastInfo === undefined) {
196
230
  return skip(reason ?? "no_cache");
197
231
  }
232
+ if (known.mode === "compaction_model")
233
+ return this.armed(runId, conv, known);
198
234
  // S7: the in-context quality gate (ruling R8) and the settled point (ruling R9)
199
235
  known.inContextAllowed = inContextSummaryAllowed(last.call.payload.provider, lastInfo.id);
200
236
  // a fit plan reshaped the last request's prefix: the fire-time in-context build skips it
@@ -217,18 +253,29 @@ let IdleArm = class IdleArm {
217
253
  absorbedUpToSeq: Number.POSITIVE_INFINITY,
218
254
  openers: [],
219
255
  });
256
+ return this.armed(runId, conv, known);
257
+ }
258
+ /** The final decision over every fact gathered: the intent, or undefined with the skip logged. */
259
+ armed(runId, conv, known) {
220
260
  const d = idleArmDecision({ ...PASSING, ...known });
221
- if (!d.arm)
222
- return skip(d.reason);
261
+ const fields = { context: "IdleCompaction", conversationId: conv.id, runId };
262
+ if (!d.arm) {
263
+ this.log.debug("idle compaction not armed", { ...fields, reason: d.reason });
264
+ return undefined;
265
+ }
266
+ if (d.mode === "compaction_model") {
267
+ this.log.debug("idle compaction armed", { ...fields, mode: d.mode, runAt: d.runAt });
268
+ return { orgId: conv.org_id, mode: "compaction_model", runAt: d.runAt };
269
+ }
223
270
  this.log.debug("idle compaction armed", {
224
- context: "IdleCompaction",
225
- conversationId: conv.id,
226
- runId,
271
+ ...fields,
272
+ mode: d.mode,
227
273
  runAt: d.runAt,
228
274
  expiresAt: d.expiresAt,
229
275
  });
230
276
  return {
231
277
  orgId: conv.org_id,
278
+ mode: "cache",
232
279
  cacheCallSeq: d.cacheCallSeq,
233
280
  expiresAt: d.expiresAt,
234
281
  runAt: d.runAt,
@@ -241,7 +288,8 @@ IdleArm = __decorate([
241
288
  __param(1, Inject(CompactionSettingsService)),
242
289
  __param(2, Inject(AccountsService)),
243
290
  __param(3, Inject(ProviderRegistry)),
244
- __param(4, Inject(KERNEL_LOGGER))
291
+ __param(4, Inject(ModelPurposesService)),
292
+ __param(5, Inject(KERNEL_LOGGER))
245
293
  ], IdleArm);
246
294
  export { IdleArm };
247
295
  /**
@@ -8,18 +8,39 @@ import type { OutboxService } from "../infra/outbox/outbox.service.js";
8
8
  export declare const IDLE_COMPACTION_JOB = "idle-compaction";
9
9
  /** One job per arming run (no `:`): a duplicate owe of the same run is a no-op. */
10
10
  export declare const idleCompactionJobId: (runId: string) => string;
11
- /** The `idle-compaction` job's data. */
12
- export interface IdleCompactionJobData {
11
+ /** What every `idle-compaction` job carries. */
12
+ interface IdleCompactionJobBase {
13
13
  orgId: string;
14
14
  conversationId: string;
15
15
  /** The run that armed the job. */
16
16
  runId: string;
17
17
  /** The seq of that run's terminal `run_finished` event (S4). */
18
18
  armedSeq: number;
19
+ }
20
+ /**
21
+ * The `idle-compaction` job's data, by how the job compacts (compaction model spec §6.2): in the
22
+ * armed prompt cache (`cache`, with the call the expiry was derived from and the expiry), or on the
23
+ * compaction model (`compaction_model`, due `idleDelayMinutes` after the run, no expiry). A row
24
+ * owed by the previous release has no `mode`: readers take `data.mode ?? "cache"` (C5).
25
+ */
26
+ export type IdleCompactionJobData = (IdleCompactionJobBase & {
27
+ mode: "cache";
19
28
  /** The seq of the `model_call` the cache expiry was derived from (`CacheExpiry.callSeq`). */
20
29
  cacheCallSeq: number;
21
30
  /** When the prompt cache entry expires, epoch ms. */
22
31
  expiresAt: number;
23
- }
32
+ }) | (IdleCompactionJobBase & {
33
+ mode: "compaction_model";
34
+ });
35
+ /**
36
+ * A delivered job's data: {@link IdleCompactionJobData}, or a cache-mode row owed before `mode`
37
+ * existed (still in the outbox or the queue across the deploy, C5).
38
+ */
39
+ export type IdleCompactionJobInput = IdleCompactionJobData | (Omit<Extract<IdleCompactionJobData, {
40
+ mode: "cache";
41
+ }>, "mode"> & {
42
+ mode?: undefined;
43
+ });
24
44
  /** Owes the idle compaction job in the caller's transaction (throws outside one), due at `runAt`. */
25
45
  export declare function oweIdleCompaction(outbox: Pick<OutboxService, "add">, data: IdleCompactionJobData, runAt: number): Promise<boolean>;
46
+ export {};
@@ -1,10 +1,11 @@
1
1
  import { AccountsService } from "../identity/accounts.js";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  import type { KernelLogger } from "../log.js";
4
+ import { ModelPurposesService } from "../models/purposes.js";
4
5
  import { CompactionService } from "./compaction.service.js";
5
6
  import { CompactionSettingsService } from "./compaction-settings.service.js";
6
7
  import { type IdleFireOutcome } from "./context/idle-compaction-rules.js";
7
- import type { IdleCompactionJobData } from "./idle-compaction-jobs.js";
8
+ import type { IdleCompactionJobInput } from "./idle-compaction-jobs.js";
8
9
  import { ProviderRegistry } from "./providers.js";
9
10
  import { RunQueue } from "./run-queue.js";
10
11
  /**
@@ -15,6 +16,11 @@ import { RunQueue } from "./run-queue.js";
15
16
  * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
16
17
  * from the database and the event log, so a duplicate delivery on another replica sees the first
17
18
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
19
+ *
20
+ * The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
21
+ * delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
22
+ * effective definition's model, read from PG on every delivery) and never falls back to the
23
+ * conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
18
24
  */
19
25
  export declare class IdleCompactionJob {
20
26
  private readonly kdb;
@@ -24,13 +30,15 @@ export declare class IdleCompactionJob {
24
30
  private readonly compactions;
25
31
  private readonly runs;
26
32
  private readonly log;
27
- constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, compactions: Pick<CompactionService, "probeIdle">, runs: Pick<RunQueue, "startIdleCompaction">, log: Pick<KernelLogger, "info" | "warn">);
33
+ /** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
34
+ private readonly compactionModel;
35
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, purposes: Pick<ModelPurposesService, "resolve">, compactions: Pick<CompactionService, "probeIdle">, runs: Pick<RunQueue, "startIdleCompaction">, log: Pick<KernelLogger, "info" | "warn" | "error" | "debug">);
28
36
  /**
29
37
  * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
30
38
  * first, stopping at the first failing check, decides, and starts the run. Logs one `info` line,
31
39
  * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
32
40
  */
33
- fire(data: IdleCompactionJobData, now?: number): Promise<IdleFireOutcome | "started">;
41
+ fire(data: IdleCompactionJobInput, now?: number): Promise<IdleFireOutcome | "started">;
34
42
  private decide;
35
43
  /**
36
44
  * Check 1's reads: the conversation (live, chat, owned), and its agent when the org is live, the
@@ -15,7 +15,9 @@ import { AccountsService } from "../identity/accounts.js";
15
15
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { ModelPurposesService } from "../models/purposes.js";
18
19
  import { CompactionService } from "./compaction.service.js";
20
+ import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
19
21
  import { CompactionSettingsService } from "./compaction-settings.service.js";
20
22
  import { CACHE_EXPIRY_MARGIN_MS, CACHE_FIRE_RATIO } from "./context/cache-expiry.js";
21
23
  import { idleFireDecision, } from "./context/idle-compaction-rules.js";
@@ -38,7 +40,8 @@ const PASSING = {
38
40
  now: 0,
39
41
  expiresAt: Number.POSITIVE_INFINITY,
40
42
  backoff: false,
41
- sameModel: true,
43
+ mode: "cache",
44
+ modelReady: true,
42
45
  probe: {
43
46
  estimate: Number.POSITIVE_INFINITY,
44
47
  window: 0,
@@ -56,6 +59,11 @@ const PASSING = {
56
59
  * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
57
60
  * from the database and the event log, so a duplicate delivery on another replica sees the first
58
61
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
62
+ *
63
+ * The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
64
+ * delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
65
+ * effective definition's model, read from PG on every delivery) and never falls back to the
66
+ * conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
59
67
  */
60
68
  let IdleCompactionJob = class IdleCompactionJob {
61
69
  kdb;
@@ -65,7 +73,9 @@ let IdleCompactionJob = class IdleCompactionJob {
65
73
  compactions;
66
74
  runs;
67
75
  log;
68
- constructor(kdb, compaction, accounts, models, compactions, runs, log) {
76
+ /** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
77
+ compactionModel;
78
+ constructor(kdb, compaction, accounts, models, purposes, compactions, runs, log) {
69
79
  this.kdb = kdb;
70
80
  this.compaction = compaction;
71
81
  this.accounts = accounts;
@@ -73,6 +83,7 @@ let IdleCompactionJob = class IdleCompactionJob {
73
83
  this.compactions = compactions;
74
84
  this.runs = runs;
75
85
  this.log = log;
86
+ this.compactionModel = compactionModelPort(purposes);
76
87
  }
77
88
  /**
78
89
  * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
@@ -80,7 +91,8 @@ let IdleCompactionJob = class IdleCompactionJob {
80
91
  * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
81
92
  */
82
93
  async fire(data, now = Date.now()) {
83
- const extra = {};
94
+ // a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
95
+ const extra = { mode: data.mode ?? "cache" };
84
96
  const outcome = await this.decide(data, now, extra);
85
97
  this.log.info("idle compaction job", {
86
98
  context: "IdleCompaction",
@@ -96,27 +108,31 @@ let IdleCompactionJob = class IdleCompactionJob {
96
108
  async decide(data, now, extra) {
97
109
  const t = this.kdb.db;
98
110
  const { orgId, conversationId, armedSeq } = data;
99
- const known = {};
111
+ // a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
112
+ const cache = data.mode === "compaction_model" ? undefined : data;
113
+ const mode = cache === undefined ? "compaction_model" : "cache";
114
+ const known = { mode };
100
115
  const failing = () => {
101
116
  const d = idleFireDecision({ ...PASSING, ...known });
102
117
  return d.fire ? undefined : d.outcome;
103
118
  };
104
- // the armed call: its lifetime (for the log) and its model (check 7)
105
- const call = await t
106
- .selectFrom("conversation_events")
107
- .select("payload")
108
- .where("conversation_id", "=", conversationId)
109
- .where("seq", "=", String(data.cacheCallSeq))
110
- .where("type", "=", "model_call")
111
- .executeTakeFirst();
119
+ // cache mode: the armed call, its lifetime (for the log) and its model (check 7)
120
+ const call = cache &&
121
+ (await t
122
+ .selectFrom("conversation_events")
123
+ .select("payload")
124
+ .where("conversation_id", "=", conversationId)
125
+ .where("seq", "=", String(cache.cacheCallSeq))
126
+ .where("type", "=", "model_call")
127
+ .executeTakeFirst());
112
128
  const armed = call?.payload;
113
129
  const lifetime = (ttl) => {
114
- if (ttl === undefined || extra.ttl !== undefined)
130
+ if (cache === undefined || ttl === undefined || extra.ttl !== undefined)
115
131
  return;
116
132
  extra.ttl = ttl;
117
133
  // the arm decision's fire time, `min(t0 + 0.9 L, expiresAt - 30 s)` with t0 = expiresAt - L
118
- const t0 = data.expiresAt - ttl * 1000;
119
- const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000, data.expiresAt - CACHE_EXPIRY_MARGIN_MS);
134
+ const t0 = cache.expiresAt - ttl * 1000;
135
+ const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000, cache.expiresAt - CACHE_EXPIRY_MARGIN_MS);
120
136
  extra.lateMs = now - runAt;
121
137
  };
122
138
  lifetime(armed?.request?.cacheTtl);
@@ -171,9 +187,10 @@ let IdleCompactionJob = class IdleCompactionJob {
171
187
  outcome = failing();
172
188
  if (outcome !== undefined)
173
189
  return outcome;
174
- // check 5 needs no read: the job's time against the armed call's expiry
190
+ // check 5 (cache mode only) needs no read: the job's time against the armed call's expiry
175
191
  known.now = now;
176
- known.expiresAt = data.expiresAt;
192
+ if (cache)
193
+ known.expiresAt = cache.expiresAt;
177
194
  outcome = failing();
178
195
  if (outcome !== undefined)
179
196
  return outcome;
@@ -191,7 +208,9 @@ let IdleCompactionJob = class IdleCompactionJob {
191
208
  if (outcome !== undefined)
192
209
  return outcome;
193
210
  // check 7: the effective definition (the agent's current version under the conversation's
194
- // model selection, what the idle run will use) resolves, is enabled, and is the armed call's
211
+ // model selection, what the idle run will use) resolves and is enabled; in cache mode it is the
212
+ // armed call's model, in compaction-model mode the compaction model summarizes for it (C6: a
213
+ // model switch since arming does not end the job, the probe sizes against the new model)
195
214
  const version = await t
196
215
  .selectFrom("agent_versions")
197
216
  .select("definition")
@@ -200,12 +219,11 @@ let IdleCompactionJob = class IdleCompactionJob {
200
219
  .executeTakeFirst();
201
220
  const definition = version &&
202
221
  effectiveDefinition(normalizeStoredDefinition(version.definition), await readSelection(t, conversationId));
203
- let resolved = false;
204
- if (definition && armed && sameModel(definition.model, armed)) {
222
+ let ready = false;
223
+ if (definition && (cache === undefined || (armed && sameModel(definition.model, armed)))) {
224
+ let model;
205
225
  try {
206
- const { info } = await this.models.resolve(orgId, definition.model);
207
- lifetime(info.cache?.defaultTtl);
208
- resolved = true;
226
+ model = await this.models.resolve(orgId, definition.model);
209
227
  }
210
228
  catch (err) {
211
229
  // unknown, disabled, or a provider list that failed: no model to compact with now
@@ -216,12 +234,24 @@ let IdleCompactionJob = class IdleCompactionJob {
216
234
  err,
217
235
  });
218
236
  }
237
+ if (model && cache) {
238
+ lifetime(model.info.cache?.defaultTtl);
239
+ ready = true;
240
+ }
241
+ else if (model) {
242
+ // the same choice the idle run makes; a cleared, disabled, unavailable or too small
243
+ // compaction model ends the job (never V, never cache mode); a failed purpose read throws
244
+ const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, orgId, { ref: definition.model, provider: model.provider, info: model.info }, settings);
245
+ ready = summarizer.source === "compaction_model";
246
+ }
219
247
  }
220
- known.sameModel = resolved;
248
+ known.modelReady = ready;
221
249
  outcome = failing();
222
250
  if (outcome !== undefined || !definition)
223
251
  return outcome ?? "no_model";
224
- // checks 8 and 9 (S13): the compaction's dry run (reads every event and the media: last)
252
+ // checks 8 and 9 (S13): the compaction's dry run in the job's mode (reads every event and the
253
+ // media: last); in compaction-model mode a null probe (C gone since check 7) is `small`, and
254
+ // in cache mode a compaction model mapped since arming reports no in-context build (C3)
225
255
  const probe = await this.compactions.probeIdle({
226
256
  orgId,
227
257
  conversationId,
@@ -231,7 +261,7 @@ let IdleCompactionJob = class IdleCompactionJob {
231
261
  source: conv.source,
232
262
  conversationKind: "chat",
233
263
  absorbedUpToSeq: Number(conv.consumed_seq),
234
- });
264
+ }, mode);
235
265
  // an unavailable model or storage during the dry run: nothing to compact with now
236
266
  known.probe = probe;
237
267
  known.inContext = probe?.inContext ?? false;
@@ -242,7 +272,7 @@ let IdleCompactionJob = class IdleCompactionJob {
242
272
  return outcome;
243
273
  // §5.1: the run, under the conversation row lock (checks 1-3 again); a refusal is a message,
244
274
  // a run or a queued message that arrived in between
245
- const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq);
275
+ const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq, mode);
246
276
  if (idleRunId === null) {
247
277
  // label the refusal by the first check it now fails (the order of checks 1-3)
248
278
  if ((await this.readLive(orgId, conversationId)).agent === undefined)
@@ -309,8 +339,9 @@ IdleCompactionJob = __decorate([
309
339
  __param(1, Inject(CompactionSettingsService)),
310
340
  __param(2, Inject(AccountsService)),
311
341
  __param(3, Inject(ProviderRegistry)),
312
- __param(4, Inject(CompactionService)),
313
- __param(5, Inject(RunQueue)),
314
- __param(6, Inject(KERNEL_LOGGER))
342
+ __param(4, Inject(ModelPurposesService)),
343
+ __param(5, Inject(CompactionService)),
344
+ __param(6, Inject(RunQueue)),
345
+ __param(7, Inject(KERNEL_LOGGER))
315
346
  ], IdleCompactionJob);
316
347
  export { IdleCompactionJob };